coverage-report

Code coverage report for All files

npmtest-babylonjs (v0.0.1)

Code coverage report for All files

Statements: 3.65% (2869 / 78515)      Branches: 0.53% (261 / 49585)      Functions: 1.41% (253 / 17952)      Lines: 3.78% (1605 / 42411)      Ignored: 26 statements, 1 function, 30 branches     

File Statements Branches Functions Lines
node-npmtest-babylonjs/ 100% (151 / 151) 100% (124 / 124) 100% (27 / 27) 100% (151 / 151)
node-npmtest-babylonjs/node_modules/babylonjs/ 3.47% (2718 / 78364) 0.28% (137 / 49461) 1.26% (226 / 17925) 3.44% (1454 / 42260)
Code coverage report for node-npmtest-babylonjs/

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/

Statements: 100% (151 / 151)      Branches: 100% (124 / 124)      Functions: 100% (27 / 27)      Lines: 100% (151 / 151)      Ignored: 26 statements, 1 function, 30 branches     

All files » node-npmtest-babylonjs/
File Statements Branches Functions Lines
example.js 100% (83 / 83) 100% (73 / 73) 100% (12 / 12) 100% (83 / 83)
lib.npmtest_babylonjs.js 100% (16 / 16) 100% (14 / 14) 100% (3 / 3) 100% (16 / 16)
test.js 100% (52 / 52) 100% (37 / 37) 100% (12 / 12) 100% (52 / 52)
Code coverage report for node-npmtest-babylonjs/example.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/example.js

Statements: 100% (83 / 83)      Branches: 100% (73 / 73)      Functions: 100% (12 / 12)      Lines: 100% (83 / 83)      Ignored: 26 statements, 1 function, 30 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                  2   2         2   2   2 2 2         1             2       2       2   2               1 2           2     2     2 2   1       2     1 1 1   1 1     1 1   1     1   2           1   1   1         1 2 2 2 2 2 2 1     2 2         2       1 3 1       1 1               1   1 1 1   1   1                                                                                                                                                                                       1 1                       1     6 6   1   2   1   2         1 1   1     1               1     1 1     1 1   1 1 1 1 1 1 1   1 1   1        
/*
example.js
 
quickstart example
 
instruction
    1. save this script as example.js
    2. run the shell command:
        $ npm install npmtest-babylonjs && PORT=8081 node example.js
    3. play with the browser-demo on http://127.0.0.1:8081
*/
 
 
 
/* istanbul instrument in package npmtest_babylonjs */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || (local.modeJs === 'browser'
            ? local.global.utility2_npmtest_babylonjs
            : global.utility2_moduleExports);
        // export local
        local.global.local = local;
    }());
    switch (local.modeJs) {
 
 
 
    // post-init
    // run browser js-env code - post-init
    /* istanbul ignore next */
    case 'browser':
        local.testRunBrowser = function (event) {
            Eif (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('onreset'))) {
                // reset output
                Array.from(
                    document.querySelectorAll('body > .resettable')
                ).forEach(function (element) {
                    switch (element.tagName) {
                    case 'INPUT':
                    case 'TEXTAREA':
                        element.value = '';
                        break;
                    default:
                        element.textContent = '';
                    }
                });
            }
            switch (event && event.currentTarget && event.currentTarget.id) {
            case 'testRunButton1':
                // show tests
                Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
                    document.querySelector('#testReportDiv1').style.display = 'block';
                    document.querySelector('#testRunButton1').textContent =
                        'hide internal test';
                    local.modeTest = true;
                    local.testRunDefault(local);
                // hide tests
                } else {
                    document.querySelector('#testReportDiv1').style.display = 'none';
                    document.querySelector('#testRunButton1').textContent = 'run internal test';
                }
                break;
            // custom-case
            default:
                break;
            }
            Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('oneval')))) {
                // try to eval input-code
                try {
                    /*jslint evil: true*/
                    eval(document.querySelector('#inputTextareaEval1').value);
                } catch (errorCaught) {
                    console.error(errorCaught);
                }
            }
        };
        // log stderr and stdout to #outputTextareaStdout1
        ['error', 'log'].forEach(function (key) {
            console[key + '_original'] = console[key];
            console[key] = function () {
                var element;
                console[key + '_original'].apply(console, arguments);
                element = document.querySelector('#outputTextareaStdout1');
                Iif (!element) {
                    return;
                }
                // append text to #outputTextareaStdout1
                element.value += Array.from(arguments).map(function (arg) {
                    return typeof arg === 'string'
                        ? arg
                        : JSON.stringify(arg, null, 4);
                }).join(' ') + '\n';
                // scroll textarea to bottom
                element.scrollTop = element.scrollHeight;
            };
        });
        // init event-handling
        ['change', 'click', 'keyup'].forEach(function (event) {
            Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
                element.addEventListener(event, local.testRunBrowser);
            });
        });
        // run tests
        local.testRunBrowser();
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        // export local
        module.exports = local;
        // require modules
        local.fs = require('fs');
        local.http = require('http');
        local.url = require('url');
        // init assets
        local.assetsDict = local.assetsDict || {};
        /* jslint-ignore-begin */
        local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
    box-sizing: false,\n\
    universal-selector: false\n\
*/\n\
* {\n\
    box-sizing: border-box;\n\
}\n\
body {\n\
    background: #dde;\n\
    font-family: Arial, Helvetica, sans-serif;\n\
    margin: 2rem;\n\
}\n\
body > * {\n\
    margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
    margin-top: 20px;\n\
    text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
    font-family: monospace;\n\
    height: 10rem;\n\
    width: 100%;\n\
}\n\
textarea[readonly] {\n\
    background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
    <a\n\
        {{#if env.npm_package_homepage}}\n\
        href="{{env.npm_package_homepage}}"\n\
        {{/if env.npm_package_homepage}}\n\
        target="_blank"\n\
    >\n\
utility2-comment -->\n\
        {{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
    </a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_babylonjs.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
    [ this app was created with\n\
    <a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
    ]\n\
</div>\n\
</body>\n\
</html>\n\
';
        /* jslint-ignore-end */
        Iif (local.templateRender) {
            local.assetsDict['/'] = local.templateRender(
                local.assetsDict['/assets.index.template.html'],
                {
                    env: local.objectSetDefault(local.env, {
                        npm_package_description: 'the greatest app in the world!',
                        npm_package_name: 'my-app',
                        npm_package_nameAlias: 'my_app',
                        npm_package_version: '0.0.1'
                    })
                }
            );
        } else {
            local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
                .replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
                    // jslint-hack
                    String(match0);
                    switch (match1) {
                    case 'npm_package_description':
                        return 'the greatest app in the world!';
                    case 'npm_package_name':
                        return 'my-app';
                    case 'npm_package_nameAlias':
                        return 'my_app';
                    case 'npm_package_version':
                        return '0.0.1';
                    }
                });
        }
        // run the cli
        Eif (local.global.utility2_rollup || module !== require.main) {
            break;
        }
        local.assetsDict['/assets.example.js'] =
            local.assetsDict['/assets.example.js'] ||
            local.fs.readFileSync(__filename, 'utf8');
        local.assetsDict['/assets.npmtest_babylonjs.rollup.js'] =
            local.assetsDict['/assets.npmtest_babylonjs.rollup.js'] ||
            local.fs.readFileSync(
                // buildCustomOrg-hack
                local.npmtest_babylonjs.__dirname +
                    '/lib.npmtest_babylonjs.js',
                'utf8'
            ).replace((/^#!/), '//');
        local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
        // if $npm_config_timeout_exit exists,
        // then exit this process after $npm_config_timeout_exit ms
        if (Number(process.env.npm_config_timeout_exit)) {
            setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
        }
        // start server
        if (local.global.utility2_serverHttp1) {
            break;
        }
        process.env.PORT = process.env.PORT || '8081';
        console.error('server starting on port ' + process.env.PORT);
        local.http.createServer(function (request, response) {
            request.urlParsed = local.url.parse(request.url);
            if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
                response.end(local.assetsDict[request.urlParsed.pathname]);
                return;
            }
            response.statusCode = 404;
            response.end();
        }).listen(process.env.PORT);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-babylonjs/lib.npmtest_babylonjs.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/lib.npmtest_babylonjs.js

Statements: 100% (16 / 16)      Branches: 100% (14 / 14)      Functions: 100% (3 / 3)      Lines: 100% (16 / 16)      Ignored: none     

All files » node-npmtest-babylonjs/ » lib.npmtest_babylonjs.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                      2   2         2   2   2 2 2         1             2       2   2   2 1   1 1 1          
/* istanbul instrument in package npmtest_babylonjs */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || local;
        // init lib
        local.local = local.npmtest_babylonjs = local;
        // init exports
        if (local.modeJs === 'browser') {
            local.global.utility2_npmtest_babylonjs = local;
        } else {
            module.exports = local;
            module.exports.__dirname = __dirname;
            module.exports.module = module;
        }
    }());
}());
 
 
Code coverage report for node-npmtest-babylonjs/test.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/test.js

Statements: 100% (52 / 52)      Branches: 100% (37 / 37)      Functions: 100% (12 / 12)      Lines: 100% (52 / 52)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187                      2   2         2   2   2 2 2         1             2     2     1       1     1   1     2           2 2   2           1           1           2 2   2             1     1             1             1 1     1             1 1 1 1 1 1     1         2 2     1             2 2     1             2 2     1             2 2     1             1 1       1 1        
/* istanbul instrument in package npmtest_babylonjs */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        switch (local.modeJs) {
        // re-init local from window.local
        case 'browser':
            local = local.global.utility2.objectSetDefault(
                local.global.utility2_rollup || local.global.local,
                local.global.utility2
            );
            break;
        // re-init local from example.js
        case 'node':
            local = (local.global.utility2_rollup || require('utility2'))
                .requireExampleJsFromReadme();
            break;
        }
        // export local
        local.global.local = local;
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - function
    case 'browser':
        break;
 
 
 
    // run node js-env code - function
    case 'node':
        break;
    }
 
 
 
    // run shared js-env code - post-init
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - post-init
    case 'browser':
        // run tests
        local.nop(local.modeTest &&
            document.querySelector('#testRunButton1') &&
            document.querySelector('#testRunButton1').click());
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApidoc's default handling-behavior-behavior
         */
            options = { modulePathList: module.paths };
            local.buildApidoc(options, onError);
        };
 
        local.testCase_buildApp_default = local.testCase_buildApp_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApp's default handling-behavior-behavior
         */
            local.testCase_buildReadme_default(options, local.onErrorThrow);
            local.testCase_buildLib_default(options, local.onErrorThrow);
            local.testCase_buildTest_default(options, local.onErrorThrow);
            local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
            options = [];
            local.buildApp(options, onError);
        };
 
        local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
            function (options, onError) {
            /*
             * this function will test buildCustomOrg's default handling-behavior
             */
                options = {};
                local.buildCustomOrg(options, onError);
            };
 
        local.testCase_buildLib_default = local.testCase_buildLib_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildLib's default handling-behavior
         */
            options = {};
            local.buildLib(options, onError);
        };
 
        local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildReadme's default handling-behavior-behavior
         */
            options = {};
            local.buildReadme(options, onError);
        };
 
        local.testCase_buildTest_default = local.testCase_buildTest_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildTest's default handling-behavior
         */
            options = {};
            local.buildTest(options, onError);
        };
 
        local.testCase_webpage_default = local.testCase_webpage_default || function (
            options,
            onError
        ) {
        /*
         * this function will test webpage's default handling-behavior
         */
            options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
            local.browserTest(options, onError);
        };
 
        // run test-server
        local.testRunServer(local);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/

Statements: 3.47% (2718 / 78364)      Branches: 0.28% (137 / 49461)      Functions: 1.26% (226 / 17925)      Lines: 3.44% (1454 / 42260)      Ignored: none     

All files » node-npmtest-babylonjs/node_modules/babylonjs/
File Statements Branches Functions Lines
Oimo.js 2.75% (244 / 8867) 0.42% (9 / 2140) 0.53% (2 / 380) 3.01% (243 / 8081)
babylon.core.js 3.79% (347 / 9152) 0.34% (32 / 9281) 1.64% (56 / 3423) 95.83% (23 / 24)
babylon.js 3.89% (500 / 12865) 0.26% (32 / 12390) 1.19% (56 / 4700) 97.06% (33 / 34)
babylon.max.js 3.26% (1127 / 34615) 0.24% (32 / 13260) 1.19% (56 / 4722) 3.29% (1122 / 34087)
babylon.noworker.js 3.89% (500 / 12865) 0.26% (32 / 12390) 1.19% (56 / 4700) 97.06% (33 / 34)
Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/Oimo.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/Oimo.js

Statements: 2.75% (244 / 8867)      Branches: 0.42% (9 / 2140)      Functions: 0.53% (2 / 380)      Lines: 3.01% (243 / 8081)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514                1                                                                                                                                                                     1 1   1 1                           1                 1                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                       1                                                                                                                 1                                                                                                                                                             1                                             1             1                                                                               1                                   1                                                                                       1                 1                                                                                         1                     1                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                               1 1 1 1 1     1                                                                                                                                                                                                                                                                                                     1             1                                                                                                                           1           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                 1   1   1       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1   1                                                                                                         1                                                     1                                           1                                     1             1           1                   1                     1                                                           1                                                                             1 1       1                       1                                 1                                                           1                 1     1     1         1           1                 1               1                                             1                                             1                             1                                                 1                                                                                   1                   1 1   1             1           1               1                                 1 1     1                                 1           1               1                                                                               1 1     1                                                                                                               1             1     1                         1                                                         1 1   1                                                                                         1             1               1                                                                                                   1 1   1                                                                                                                                             1             1     1                           1                                                                                                                                       1 1   1                                                                                                                                                 1             1     1                       1                                                       1                                                                                                                       1                                                                                                                       1                                                                                                                                                                                                                                                                                                           1                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                       1                                                                                                                                                                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                           1       1                         1                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                             1                                                       1                               1                             1                                                                                                                     1                                                                                                                                                                         1                         1                                                                   1                           1                                                                                             1                                                     1                                               1                                               1 1   1                         1                                                                                                                                                                                                                   1                   1 1   1                 1                                     1                             1 1   1                     1                                                                                               1                         1 1   1       1             1       1           1                             1                     1 1   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1             1 1   1                                                                                                                                                                                                                                                                                                                                   1           1 1   1                                             1         1 1   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                 1                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1           1 1   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1             1 1   1                                                                                                                                                 1     1 1   1                                                                                       1               1               1                   1                                                                                                                                                                                                                                                         1                 1                                   1               1 1   1             1                 1                                                                                                                                                                                     1                 1 1   1           1                                     1                                       1                                                                 1                     1                   1                                                                                                                                                                                                                                                                                                                         1                                                 1 1   1           1                                     1                                                                       1                                                                                                                                                                                                                                       1                                                   1                                                                     1 1       1             1                                           1                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                       1 1   1           1               1                     1                                           1                                                                                                                 1                                       1                 1 1   1     1                                                                                                                                                                                                                                                                                                                                                                    
/**
 * from OimoPhysics DEV 1.1.0a AS3
 * @author Saharan / http://el-ement.com/
 * 
 * to Oimo.js 2015 JAVASCRIPT
 * @author LoTh / http://lo-th.github.io/labs/
 */
 
var OIMO = {
    REVISION: "1.2",
 
    // Global identification of next shape.
    // This will be incremented every time a shape is created.
    nextID: 0,
 
    proxyID: 0,
 
    // BroadPhase
    BR_NULL: 0,
    BR_BRUTE_FORCE: 1,
    BR_SWEEP_AND_PRUNE: 2,
    BR_BOUNDING_VOLUME_TREE: 3,
 
    // body type
    BODY_NULL: 0,
    BODY_DYNAMIC: 1,
    BODY_STATIC: 2,
 
    // shape type
    SHAPE_NULL: 0,
    SHAPE_SPHERE: 1,
    SHAPE_BOX: 2,
    SHAPE_CYLINDER: 3,
    SHAPE_TETRA: 4,
 
    // joint type
    JOINT_NULL: 0,
    JOINT_DISTANCE: 1,
    JOINT_BALL_AND_SOCKET: 2,
    JOINT_HINGE: 3,
    JOINT_WHEEL: 4,
    JOINT_SLIDER: 5,
    JOINT_PRISMATIC: 6,
 
    // this world scale defaut is 0.1 to 10 meters max for dynamique body
    // scale all by 100 so object is between 10 to 10000 three unit.
    WORLD_SCALE: 100,
    INV_SCALE: 0.01,
 
    // AABB aproximation
    AABB_PROX: 0.005,
 
    // Math function
    sqrt: Math.sqrt,
    abs: Math.abs,
    floor: Math.floor,
    cos: Math.cos,
    sin: Math.sin,
    acos: Math.acos,
    asin: Math.asin,
    atan2: Math.atan2,
    round: Math.round,
    pow: Math.pow,
    max: Math.max,
    min: Math.min,
    random: Math.random,
 
    lerp: function (a, b, percent) { return a + (b - a) * percent; },
    rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
    randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
 
    int: function (x) { return ~~x; },
    fix: function (x, n) { return x.toFixed(n || 3, 10); },
 
    clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
 
    degtorad: 0.0174532925199432957,
    radtodeg: 57.295779513082320876,
    PI: 3.141592653589793,
    TwoPI: 6.283185307179586,
    PI90: 1.570796326794896,
    PI270: 4.712388980384689,
 
    CustomError: null,
 
    Error: function (Class, Msg) {
        if (OIMO.CustomError == null) console.error(Class, Msg);
        else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
    }
};
 
var OIMO_ARRAY_TYPE;
Eif (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
 
try {
    (function (w) {
        var perfNow;
        var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
        if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
            var n = perfNowNames[i];
            if (!!w['performance'][n]) {
                perfNow = function () { return w['performance'][n]() };
                break;
            }
        }
        if (!perfNow) perfNow = Date.now;
        //w.perfNow = perfNow;
        OIMO.now = perfNow;
    })(window);
} catch (e) { OIMO.now = function () { return 0; }; }
 
/**
 * The class of physical computing world. 
 * You must be added to the world physical all computing objects
 * @author saharan
 * @author lo-th
 */
 
OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
 
 
 
    // The time between each step
    this.timeStep = TimeStep || 0.01666; // 1/60;
    // The number of iterations for constraint solvers.
    this.numIterations = Iterations || 8;
    // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
    switch (BroadPhaseType || 2) {
        case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
        case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
        case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
    }
 
    // This is the detailed information of the performance. 
    this.performance = null;
    this.isNoStat = NoStat || false;
    if (!this.isNoStat) this.performance = new OIMO.Performance(this);
 
    // Whether the constraints randomizer is enabled or not.
    this.enableRandomizer = true;
 
 
 
 
    // The rigid body list
    this.rigidBodies = null;
    // number of rigid body
    this.numRigidBodies = 0;
    // The contact list
    this.contacts = null;
    this.unusedContacts = null;
    // The number of contact
    this.numContacts = 0;
    // The number of contact points
    this.numContactPoints = 0;
    //  The joint list
    this.joints = null;
    // The number of joints.
    this.numJoints = 0;
    // The number of simulation islands.
    this.numIslands = 0;
 
 
    // The gravity in the world.
    this.gravity = new OIMO.Vec3(0, -9.80665, 0);
 
 
 
    var numShapeTypes = 5;//4;//3;
    this.detectors = [];
    this.detectors.length = numShapeTypes;
    var i = numShapeTypes;
    while (i--) {
        this.detectors[i] = [];
        this.detectors[i].length = numShapeTypes;
    }
    this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
    this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
    this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
    this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
 
    // CYLINDER add
    this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
 
    this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
    this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
 
    this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
    this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
 
    // TETRA add
    this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
 
 
    this.randX = 65535;
    this.randA = 98765;
    this.randB = 123456789;
    //this.maxIslandRigidBodies = 64;
    this.islandRigidBodies = [];
    //this.islandRigidBodies.length = this.maxIslandRigidBodies;
    this.islandStack = [];
    //this.islandStack.length = this.maxIslandRigidBodies;
    //this.maxIslandConstraints = 128;
    this.islandConstraints = [];
    //this.islandConstraints.length = this.maxIslandConstraints;
 
};
 
OIMO.World.prototype = {
    constructor: OIMO.World,
    /**
    * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
	*/
    clear: function () {
        this.randX = 65535;
        while (this.joints !== null) {
            this.removeJoint(this.joints);
        }
        while (this.contacts !== null) {
            this.removeContact(this.contacts);
        }
        while (this.rigidBodies !== null) {
            this.removeRigidBody(this.rigidBodies);
        }
 
        OIMO.nextID = 0;
        OIMO.proxyID = 0;
    },
    /**
    * I'll add a rigid body to the world. 
    * Rigid body that has been added will be the operands of each step.
    * @param  rigidBody  Rigid body that you want to add
    */
    addRigidBody: function (rigidBody) {
        if (rigidBody.parent) {
            OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
        }
        rigidBody.parent = this;
        rigidBody.awake();
        for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
            this.addShape(shape);
        }
        if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
        this.rigidBodies = rigidBody;
        this.numRigidBodies++;
    },
    /**
    * I will remove the rigid body from the world. 
    * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
    * @param  rigidBody  Rigid body to be removed
    */
    removeRigidBody: function (rigidBody) {
        var remove = rigidBody;
        if (remove.parent !== this) return;
        remove.awake();
        var js = remove.jointLink;
        while (js != null) {
            var joint = js.joint;
            js = js.next;
            this.removeJoint(joint);
        }
        for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
            this.removeShape(shape);
        }
        var prev = remove.prev;
        var next = remove.next;
        if (prev !== null) prev.next = next;
        if (next !== null) next.prev = prev;
        if (this.rigidBodies == remove) this.rigidBodies = next;
        remove.prev = null;
        remove.next = null;
        remove.parent = null;
        this.numRigidBodies--;
    },
    getByName: function (name) {
        var result = null;
        var body = this.rigidBodies;
        while (body !== null) {
            if (body.name !== " " && body.name === name) result = body;
            body = body.next;
        }
        var joint = this.joints;
        while (joint !== null) {
            if (joint.name !== "" && joint.name === name) result = joint;
            joint = joint.next;
        }
        return result;
    },
 
    /**
    * I'll add a shape to the world..
    * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world, 
    * Shape will be added to the world automatically, please do not call from outside this method.
    * @param  shape  Shape you want to add
    */
    addShape: function (shape) {
        if (!shape.parent || !shape.parent.parent) {
            OIMO.Error("World", "It is not possible to be added alone to shape world");
        }
        shape.proxy = this.broadPhase.createProxy(shape);
        shape.updateProxy();
        this.broadPhase.addProxy(shape.proxy);
    },
 
    /**
    * I will remove the shape from the world.
    * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world, 
    * Shape will be added to the world automatically, please do not call from outside this method.
    * @param  shape  Shape you want to delete
    */
    removeShape: function (shape) {
        this.broadPhase.removeProxy(shape.proxy);
        shape.proxy = null;
    },
 
    /**
    * I'll add a joint to the world. 
    * Joint that has been added will be the operands of each step.
    * @param  shape Joint to be added
    */
    addJoint: function (joint) {
        if (joint.parent) {
            OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
        }
        if (this.joints != null) (this.joints.prev = joint).next = this.joints;
        this.joints = joint;
        joint.parent = this;
        this.numJoints++;
        joint.awake();
        joint.attach();
    },
 
    /**
    * I will remove the joint from the world. 
    * Joint that has been added will be the operands of each step.
    * @param  shape Joint to be deleted
    */
    removeJoint: function (joint) {
        var remove = joint;
        var prev = remove.prev;
        var next = remove.next;
        if (prev !== null) prev.next = next;
        if (next !== null) next.prev = prev;
        if (this.joints == remove) this.joints = next;
        remove.prev = null;
        remove.next = null;
        this.numJoints--;
        remove.awake();
        remove.detach();
        remove.parent = null;
    },
 
    worldscale: function (scale) {
        OIMO.WORLD_SCALE = scale || 100;
        OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
    },
 
    addContact: function (s1, s2) {
 
        var newContact;
        if (this.unusedContacts !== null) {
            newContact = this.unusedContacts;
            this.unusedContacts = this.unusedContacts.next;
        } else {
            newContact = new OIMO.Contact();
        }
        newContact.attach(s1, s2);
        newContact.detector = this.detectors[s1.type][s2.type];
        if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
        this.contacts = newContact;
        this.numContacts++;
 
    },
 
    removeContact: function (contact) {
 
        var prev = contact.prev;
        var next = contact.next;
        if (next) next.prev = prev;
        if (prev) prev.next = next;
        if (this.contacts == contact) this.contacts = next;
        contact.prev = null;
        contact.next = null;
        contact.detach();
        contact.next = this.unusedContacts;
        this.unusedContacts = contact;
        this.numContacts--;
 
    },
 
    checkContact: function (name1, name2) {
 
        var n1, n2;
        var contact = this.contacts;
        while (contact !== null) {
            n1 = contact.body1.name || ' ';
            n2 = contact.body2.name || ' ';
            if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
            else contact = contact.next;
        }
        return false;
 
    },
 
    callSleep: function (body) {
 
        if (!body.allowSleep) return false;
        if (body.linearVelocity.lengthSq() > 0.04) return false;
        if (body.angularVelocity.lengthSq() > 0.25) return false;
        return true;
 
    },
 
    /**
    * I will proceed only time step seconds time of World.
    */
    step: function () {
        var time0, time1, time2, time3;
 
        var stat = !this.isNoStat ? true : false;
 
        if (stat) time0 = OIMO.now();
 
        var body = this.rigidBodies;
 
        while (body !== null) {
            body.addedToIsland = false;
            if (body.sleeping) {
                if (
                    body.linearVelocity.testZero() ||
                    body.angularVelocity.testZero() ||
                    body.position.testDiff(body.sleepPosition) ||
                    body.orientation.testDiff(body.sleepOrientation)
                ) body.awake(); // awake the body
            }
            body = body.next;
        }
 
 
 
        //------------------------------------------------------
        //   UPDATE CONTACT
        //------------------------------------------------------
 
        // broad phase
        if (stat) time1 = OIMO.now();
 
 
        this.broadPhase.detectPairs();
 
 
        var pairs = this.broadPhase.pairs;
 
        var i = this.broadPhase.numPairs;
        //do{
        while (i--) {
            //for(var i=0, l=numPairs; i<l; i++){
            var pair = pairs[i];
            var s1;
            var s2;
            if (pair.shape1.id < pair.shape2.id) {
                s1 = pair.shape1;
                s2 = pair.shape2;
            } else {
                s1 = pair.shape2;
                s2 = pair.shape1;
            }
 
            var link;
            if (s1.numContacts < s2.numContacts) link = s1.contactLink;
            else link = s2.contactLink;
 
            var exists = false;
            while (link) {
                var contact = link.contact;
                if (contact.shape1 == s1 && contact.shape2 == s2) {
                    contact.persisting = true;
                    exists = true;// contact already exists
                    break;
                }
                link = link.next;
            }
            if (!exists) {
                this.addContact(s1, s2);
            }
        }// while(i-- >0);
 
        if (stat) {
            time2 = OIMO.now();
            this.performance.broadPhaseTime = time2 - time1;
        }
 
        // update & narrow phase
        this.numContactPoints = 0;
        contact = this.contacts;
        while (contact !== null) {
            if (!contact.persisting) {
                if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
                    /*var aabb1=contact.shape1.aabb;
                    var aabb2=contact.shape2.aabb;
                    if(
                        aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
                        aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
                        aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
                    ){*/
                    var next = contact.next;
                    this.removeContact(contact);
                    contact = next;
                    continue;
                }
            }
            var b1 = contact.body1;
            var b2 = contact.body2;
            if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
                contact.updateManifold();
            }
            this.numContactPoints += contact.manifold.numPoints;
            contact.persisting = false;
            contact.constraint.addedToIsland = false;
            contact = contact.next;
        }
 
        if (stat) {
            time3 = OIMO.now();
            this.performance.narrowPhaseTime = time3 - time2;
        }
 
        //------------------------------------------------------
        //   SOLVE ISLANDS
        //------------------------------------------------------
 
        var invTimeStep = 1 / this.timeStep;
        //var body;
        var joint;
        var constraint;
        //var num;
 
        for (joint = this.joints; joint !== null; joint = joint.next) {
            joint.addedToIsland = false;
        }
 
 
        // clear old island array
        this.islandRigidBodies = [];
        this.islandConstraints = [];
        this.islandStack = [];
 
        // expand island buffers
        /*if(this.maxIslandRigidBodies<this.numRigidBodies){
            this.maxIslandRigidBodies=this.numRigidBodies<<1;
            //this.maxIslandRigidBodies=this.numRigidBodies*2;
 
            this.islandRigidBodies=[];
            this.islandStack=[];
            this.islandRigidBodies.length = this.maxIslandRigidBodies;
            this.islandStack.length = this.maxIslandRigidBodies;
        }
        var numConstraints=this.numJoints+this.numContacts;
        if(this.maxIslandConstraints<numConstraints){
            this.maxIslandConstraints=numConstraints<<1;
            //this.maxIslandConstraints=numConstraints*2;
            this.islandConstraints=[];
            this.islandConstraints.length = this.maxIslandConstraints;
        }*/
 
        time1 = OIMO.now();
        this.numIslands = 0;
 
        // build and solve simulation islands
 
        for (var base = this.rigidBodies; base !== null; base = base.next) {
 
            if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
 
            if (base.isLonely()) {// update single body
                if (base.isDynamic) {
                    base.linearVelocity.addTime(this.gravity, this.timeStep);
                    /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
                    base.linearVelocity.y+=this.gravity.y*this.timeStep;
                    base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
                }
                if (this.callSleep(base)) {
                    base.sleepTime += this.timeStep;
                    if (base.sleepTime > 0.5) base.sleep();
                    else base.updatePosition(this.timeStep);
                } else {
                    base.sleepTime = 0;
                    base.updatePosition(this.timeStep);
                }
                this.numIslands++;
                continue;
            }
 
            var islandNumRigidBodies = 0;
            var islandNumConstraints = 0;
            var stackCount = 1;
            // add rigid body to stack
            this.islandStack[0] = base;
            base.addedToIsland = true;
 
            // build an island
            do {
                // get rigid body from stack
                body = this.islandStack[--stackCount];
                this.islandStack[stackCount] = null;
                body.sleeping = false;
                // add rigid body to the island
                this.islandRigidBodies[islandNumRigidBodies++] = body;
                if (body.isStatic) continue;
 
                // search connections
                for (var cs = body.contactLink; cs !== null; cs = cs.next) {
                    var contact = cs.contact;
                    constraint = contact.constraint;
                    if (constraint.addedToIsland || !contact.touching) continue;// ignore
 
                    // add constraint to the island
                    this.islandConstraints[islandNumConstraints++] = constraint;
                    constraint.addedToIsland = true;
                    var next = cs.body;
 
                    if (next.addedToIsland) continue;
 
                    // add rigid body to stack
                    this.islandStack[stackCount++] = next;
                    next.addedToIsland = true;
                }
                for (var js = body.jointLink; js !== null; js = js.next) {
                    constraint = js.joint;
 
                    if (constraint.addedToIsland) continue;// ignore
 
                    // add constraint to the island
                    this.islandConstraints[islandNumConstraints++] = constraint;
                    constraint.addedToIsland = true;
                    next = js.body;
                    if (next.addedToIsland || !next.isDynamic) continue;
 
                    // add rigid body to stack
                    this.islandStack[stackCount++] = next;
                    next.addedToIsland = true;
                }
            } while (stackCount != 0);
 
            // update velocities
            var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
            /*var gx=this.gravity.x*this.timeStep;
            var gy=this.gravity.y*this.timeStep;
            var gz=this.gravity.z*this.timeStep;*/
            var j = islandNumRigidBodies;
            while (j--) {
                //or(var j=0, l=islandNumRigidBodies; j<l; j++){
                body = this.islandRigidBodies[j];
                if (body.isDynamic) {
                    body.linearVelocity.addEqual(gVel);
                    /*body.linearVelocity.x+=gx;
                    body.linearVelocity.y+=gy;
                    body.linearVelocity.z+=gz;*/
                }
            }
 
            // randomizing order
            if (this.enableRandomizer) {
                //for(var j=1, l=islandNumConstraints; j<l; j++){
                j = islandNumConstraints;
                while (j--) {
                    if (j !== 0) {
                        var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
                        constraint = this.islandConstraints[j];
                        this.islandConstraints[j] = this.islandConstraints[swap];
                        this.islandConstraints[swap] = constraint;
                    }
                }
            }
 
            // solve contraints
 
            j = islandNumConstraints;
            while (j--) {
                //for(j=0, l=islandNumConstraints; j<l; j++){
                this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
            }
            var k = this.numIterations;
            while (k--) {
                //for(var k=0, l=this.numIterations; k<l; k++){
                j = islandNumConstraints;
                while (j--) {
                    //for(j=0, m=islandNumConstraints; j<m; j++){
                    this.islandConstraints[j].solve();// main-solve
                }
            }
            j = islandNumConstraints;
            while (j--) {
                //for(j=0, l=islandNumConstraints; j<l; j++){
                this.islandConstraints[j].postSolve();// post-solve
                this.islandConstraints[j] = null;// gc
            }
 
            // sleeping check
 
            var sleepTime = 10;
            j = islandNumRigidBodies;
            while (j--) {
                //for(j=0, l=islandNumRigidBodies;j<l;j++){
                body = this.islandRigidBodies[j];
                if (this.callSleep(body)) {
                    body.sleepTime += this.timeStep;
                    if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
                } else {
                    body.sleepTime = 0;
                    sleepTime = 0;
                    continue;
                }
            }
            if (sleepTime > 0.5) {
                // sleep the island
                j = islandNumRigidBodies;
                while (j--) {
                    //for(j=0, l=islandNumRigidBodies;j<l;j++){
                    this.islandRigidBodies[j].sleep();
                    this.islandRigidBodies[j] = null;// gc
                }
            } else {
                // update positions
                j = islandNumRigidBodies;
                while (j--) {
                    //for(j=0, l=islandNumRigidBodies;j<l;j++){
                    this.islandRigidBodies[j].updatePosition(this.timeStep);
                    this.islandRigidBodies[j] = null;// gc
                }
            }
            this.numIslands++;
        }
 
        if (stat) {
            time2 = OIMO.now();
            this.performance.solvingTime = time2 - time1;
 
            //------------------------------------------------------
            //   END SIMULATION
            //------------------------------------------------------
 
            time2 = OIMO.now();
            // fps update
            this.performance.upfps();
            this.performance.totalTime = time2 - time0;
        }
    }
 
}
/**
* The class of rigid body. 
* Rigid body has the shape of a single or multiple collision processing, 
* I can set the parameters individually.
* @author saharan
*/
OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
 
    this.name = " ";
    // The maximum number of shapes that can be added to a one rigid.
    this.MAX_SHAPES = 64;//64;
 
    this.prev = null;
    this.next = null;
 
    // I represent the kind of rigid body.
    // Please do not change from the outside this variable. 
    // If you want to change the type of rigid body, always 
    // Please specify the type you want to set the arguments of setupMass method.
    this.type = OIMO.BODY_NULL;
 
    this.massInfo = new OIMO.MassInfo();
 
    // It is the world coordinate of the center of gravity.
    this.position = new OIMO.Vec3(x, y, z);
 
    this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
 
 
    this.newPosition = new OIMO.Vec3();
    this.controlPos = false;
    this.newOrientation = new OIMO.Quat();
    this.newRotation = new OIMO.Vec3();
    this.currentRotation = new OIMO.Vec3();
    this.controlRot = false;
    this.controlRotInTime = false;
 
 
 
    // Is the translational velocity.
    this.linearVelocity = new OIMO.Vec3();
    // Is the angular velocity.
    this.angularVelocity = new OIMO.Vec3();
 
    // return matrix for three.js
    this.matrix = new OIMO.Mat44();
 
    //--------------------------------------------
    //  Please do not change from the outside this variables.
    //--------------------------------------------
 
    // It is a world that rigid body has been added.
    this.parent = null;
    this.contactLink = null;
    this.numContacts = 0;
 
    // An array of shapes that are included in the rigid body.
    this.shapes = null;
    // The number of shapes that are included in the rigid body.
    this.numShapes = 0;
 
    // It is the link array of joint that is connected to the rigid body.
    this.jointLink = null;
    // The number of joints that are connected to the rigid body.
    this.numJoints = 0;
 
    // It is the world coordinate of the center of gravity in the sleep just before.
    this.sleepPosition = new OIMO.Vec3();
    // It is a quaternion that represents the attitude of sleep just before.
    this.sleepOrientation = new OIMO.Quat();
    // I will show this rigid body to determine whether it is a rigid body static.
    this.isStatic = false;
    // I indicates that this rigid body to determine whether it is a rigid body dynamic. 
    this.isDynamic = false;
    // It is a rotation matrix representing the orientation.
    this.rotation = new OIMO.Mat33();
 
    //--------------------------------------------
    // It will be recalculated automatically from the shape, which is included.
    //--------------------------------------------
 
    // This is the weight. 
    this.mass = NaN;
    // It is the reciprocal of the mass.
    this.inverseMass = NaN;
    // It is the inverse of the inertia tensor in the world system.
    this.inverseInertia = new OIMO.Mat33();
    // It is the inertia tensor in the initial state.
    this.localInertia = new OIMO.Mat33();
    // It is the inverse of the inertia tensor in the initial state.
    this.inverseLocalInertia = new OIMO.Mat33();
 
 
    // I indicates rigid body whether it has been added to the simulation Island.
    this.addedToIsland = false;
    // It shows how to sleep rigid body.
    this.allowSleep = true;
    // This is the time from when the rigid body at rest.
    this.sleepTime = 0;
    // I shows rigid body to determine whether it is a sleep state.
    this.sleeping = false;
 
};
 
OIMO.RigidBody.prototype = {
 
    constructor: OIMO.RigidBody,
    /**
    * I'll add a shape to rigid body.  
    * If you add a shape, please call the setupMass method to step up to the start of the next.
    * @param   shape shape to Add 
    */
    addShape: function (shape) {
 
        if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
 
        if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
        this.shapes = shape;
        shape.parent = this;
        if (this.parent) this.parent.addShape(shape);
        this.numShapes++;
 
    },
    /**
    * I will delete the shape from the rigid body. 
    * If you delete a shape, please call the setupMass method to step up to the start of the next. 
    * @param   shape shape to Delete 
    */
    removeShape: function (shape) {
 
        var remove = shape;
        if (remove.parent != this) return;
        var prev = remove.prev;
        var next = remove.next;
        if (prev != null) prev.next = next;
        if (next != null) next.prev = prev;
        if (this.shapes == remove) this.shapes = next;
        remove.prev = null;
        remove.next = null;
        remove.parent = null;
        if (this.parent) this.parent.removeShape(remove);
        this.numShapes--;
 
    },
 
    remove: function () {
 
        this.dispose();
 
    },
 
    dispose: function () {
 
        this.parent.removeRigidBody(this);
 
    },
 
    checkContact: function (name) {
 
        this.parent.checkContact(this.name, name);
 
    },
 
    /**
    * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
    * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
    * If the parameter adjustPosition is set to true, the shapes' relative positions and
    * the rigid body's position will be adjusted to the center of gravity.
    * @param   type
    * @param   adjustPosition
    */
    setupMass: function (type, AdjustPosition) {
 
        var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
 
        this.type = type || OIMO.BODY_DYNAMIC;
        this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
        this.isStatic = this.type == OIMO.BODY_STATIC;
 
        this.mass = 0;
        this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
        var te = this.localInertia.elements;
        //
        var tmpM = new OIMO.Mat33();
        var tmpV = new OIMO.Vec3();
        for (var shape = this.shapes; shape != null; shape = shape.next) {
            shape.calculateMassInfo(this.massInfo);
            var shapeMass = this.massInfo.mass;
            var relX = shape.relativePosition.x;
            var relY = shape.relativePosition.y;
            var relZ = shape.relativePosition.z;
            /*tmpV.x+=relX*shapeMass;
            tmpV.y+=relY*shapeMass;
            tmpV.z+=relZ*shapeMass;*/
            tmpV.addScale(shape.relativePosition, shapeMass);
            this.mass += shapeMass;
            this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
            this.localInertia.addEqual(tmpM);
 
            // add offset inertia
            te[0] += shapeMass * (relY * relY + relZ * relZ);
            te[4] += shapeMass * (relX * relX + relZ * relZ);
            te[8] += shapeMass * (relX * relX + relY * relY);
            var xy = shapeMass * relX * relY;
            var yz = shapeMass * relY * relZ;
            var zx = shapeMass * relZ * relX;
            te[1] -= xy;
            te[3] -= xy;
            te[2] -= yz;
            te[6] -= yz;
            te[5] -= zx;
            te[7] -= zx;
        }
        this.inverseMass = 1 / this.mass;
        tmpV.scaleEqual(this.inverseMass);
        if (adjustPosition) {
            this.position.addEqual(tmpV);
            for (shape = this.shapes; shape != null; shape = shape.next) {
                shape.relativePosition.subEqual(tmpV);
            }
            // subtract offset inertia
            relX = tmpV.x;
            relY = tmpV.y;
            relZ = tmpV.z;
            //var te = this.localInertia.elements;
            te[0] -= this.mass * (relY * relY + relZ * relZ);
            te[4] -= this.mass * (relX * relX + relZ * relZ);
            te[8] -= this.mass * (relX * relX + relY * relY);
            xy = this.mass * relX * relY;
            yz = this.mass * relY * relZ;
            zx = this.mass * relZ * relX;
            te[1] += xy;
            te[3] += xy;
            te[2] += yz;
            te[6] += yz;
            te[5] += zx;
            te[7] += zx;
        }
 
        this.inverseLocalInertia.invert(this.localInertia);
 
        if (this.type == OIMO.BODY_STATIC) {
            this.inverseMass = 0;
            this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
        }
 
        this.syncShapes();
        this.awake();
 
    },
    /**
    * Awake the rigid body.
    */
    awake: function () {
 
        if (!this.allowSleep || !this.sleeping) return;
        this.sleeping = false;
        this.sleepTime = 0;
        // awake connected constraints
        var cs = this.contactLink;
        while (cs != null) {
            cs.body.sleepTime = 0;
            cs.body.sleeping = false;
            cs = cs.next;
        }
        var js = this.jointLink;
        while (js != null) {
            js.body.sleepTime = 0;
            js.body.sleeping = false;
            js = js.next;
        }
        for (var shape = this.shapes; shape != null; shape = shape.next) {
            shape.updateProxy();
        }
 
    },
    /**
    * Sleep the rigid body.
    */
    sleep: function () {
 
        if (!this.allowSleep || this.sleeping) return;
        this.linearVelocity.set(0, 0, 0);
        this.angularVelocity.set(0, 0, 0);
        this.sleepPosition.copy(this.position);
        this.sleepOrientation.copy(this.orientation);
        /*this.linearVelocity.x=0;
        this.linearVelocity.y=0;
        this.linearVelocity.z=0;
        this.angularVelocity.x=0;
        this.angularVelocity.y=0;
        this.angularVelocity.z=0;
        this.sleepPosition.x=this.position.x;
        this.sleepPosition.y=this.position.y;
        this.sleepPosition.z=this.position.z;*/
        /*this.sleepOrientation.s=this.orientation.s;
        this.sleepOrientation.x=this.orientation.x;
        this.sleepOrientation.y=this.orientation.y;
        this.sleepOrientation.z=this.orientation.z;*/
 
        this.sleepTime = 0;
        this.sleeping = true;
        for (var shape = this.shapes; shape != null; shape = shape.next) {
            shape.updateProxy();
        }
    },
    /**
    * Get whether the rigid body has not any connection with others.
    * @return
    */
    isLonely: function () {
        return this.numJoints == 0 && this.numContacts == 0;
    },
 
    /** 
    * The time integration of the motion of a rigid body, you can update the information such as the shape. 
    * This method is invoked automatically when calling the step of the World, 
    * There is no need to call from outside usually. 
    * @param  timeStep time 
    */
 
    updatePosition: function (timeStep) {
        switch (this.type) {
            case OIMO.BODY_STATIC:
                this.linearVelocity.set(0, 0, 0);
                this.angularVelocity.set(0, 0, 0);
 
                // ONLY FOR TEST
                if (this.controlPos) {
                    this.position.copy(this.newPosition);
                    this.controlPos = false;
                }
                if (this.controlRot) {
                    this.orientation.copy(this.newOrientation);
                    this.controlRot = false;
                }
                /*this.linearVelocity.x=0;
                this.linearVelocity.y=0;
                this.linearVelocity.z=0;
                this.angularVelocity.x=0;
                this.angularVelocity.y=0;
                this.angularVelocity.z=0;*/
                break;
            case OIMO.BODY_DYNAMIC:
 
                if (this.controlPos) {
                    this.angularVelocity.set(0, 0, 0);
                    this.linearVelocity.set(0, 0, 0);
                    this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
                    this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
                    this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
                    this.controlPos = false;
                }
                if (this.controlRot) {
                    this.angularVelocity.set(0, 0, 0);
                    this.orientation.copy(this.newOrientation);
 
                    //var t=timeStep//*0.5;
                    //var q = new OIMO.Quat();
                    //q.sub(this.newOrientation, this.orientation);
                    //q.normalize(q);
                    /*q.s = (this.newOrientation.s - this.orientation.s)/t;
                    q.x = (this.newOrientation.x - this.orientation.x)/t;
                    q.y = (this.newOrientation.y - this.orientation.y)/t;
                    q.z = (this.newOrientation.z - this.orientation.z)/t;*/
 
                    //this.angularVelocity.applyQuaternion(q);
                    //this.angularVelocity.x = this.angularVelocity.x/t;
                    //this.angularVelocity.y = this.angularVelocity.y/t;
                    //this.angularVelocity.z = this.angularVelocity.z/t;
 
                    this.controlRot = false;
                }
 
                this.position.addTime(this.linearVelocity, timeStep);
                this.orientation.addTime(this.angularVelocity, timeStep);
 
                break;
            default: OIMO.Error("RigidBody", "Invalid type.");
        }
 
        this.syncShapes();
 
    },
 
    rotateInertia: function (rot, inertia, out) {
 
        var tm1 = rot.elements;
        var tm2 = inertia.elements;
 
        var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
        var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
        var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
 
        var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
        var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
        var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
 
        var e00 = a0 * b0 + a1 * b3 + a2 * b6;
        var e01 = a0 * b1 + a1 * b4 + a2 * b7;
        var e02 = a0 * b2 + a1 * b5 + a2 * b8;
        var e10 = a3 * b0 + a4 * b3 + a5 * b6;
        var e11 = a3 * b1 + a4 * b4 + a5 * b7;
        var e12 = a3 * b2 + a4 * b5 + a5 * b8;
        var e20 = a6 * b0 + a7 * b3 + a8 * b6;
        var e21 = a6 * b1 + a7 * b4 + a8 * b7;
        var e22 = a6 * b2 + a7 * b5 + a8 * b8;
 
        var oe = out.elements;
        oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
        oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
        oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
        oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
        oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
        oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
        oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
        oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
        oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
 
    },
 
    syncShapes: function () {
 
        var s = this.orientation.s;
        var x = this.orientation.x;
        var y = this.orientation.y;
        var z = this.orientation.z;
        var x2 = 2 * x;
        var y2 = 2 * y;
        var z2 = 2 * z;
        var xx = x * x2;
        var yy = y * y2;
        var zz = z * z2;
        var xy = x * y2;
        var yz = y * z2;
        var xz = x * z2;
        var sx = s * x2;
        var sy = s * y2;
        var sz = s * z2;
 
        var tr = this.rotation.elements;
        tr[0] = 1 - yy - zz;
        tr[1] = xy - sz;
        tr[2] = xz + sy;
        tr[3] = xy + sz;
        tr[4] = 1 - xx - zz;
        tr[5] = yz - sx;
        tr[6] = xz - sy;
        tr[7] = yz + sx;
        tr[8] = 1 - xx - yy;
 
        this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
        for (var shape = this.shapes; shape != null; shape = shape.next) {
            //var relPos=shape.relativePosition;
            //var relRot=shape.relativeRotation;
            //var rot=shape.rotation;
            /*var lx=relPos.x;
            var ly=relPos.y;
            var lz=relPos.z;
            shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
            shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
            shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
 
            shape.position.mul(this.position, shape.relativePosition, this.rotation);
            //shape.rotation.mul(shape.relativeRotation,this.rotation);
            // add by QuaziKb
            shape.rotation.mul(this.rotation, shape.relativeRotation);
            shape.updateProxy();
        }
    },
 
    applyImpulse: function (position, force) {
 
        this.linearVelocity.addScale(force, this.inverseMass);
        /*this.linearVelocity.x+=force.x*this.inverseMass;
        this.linearVelocity.y+=force.y*this.inverseMass;
        this.linearVelocity.z+=force.z*this.inverseMass;*/
        var rel = new OIMO.Vec3();
        rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
        this.angularVelocity.addEqual(rel);
        /*this.angularVelocity.x+=rel.x;
        this.angularVelocity.y+=rel.y;
        this.angularVelocity.z+=rel.z;*/
    },
 
    //---------------------------------------------
    //
    // FOR THREE JS
    //
    //---------------------------------------------
 
    rotationVectToQuad: function (rot) {
 
        var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
        return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
 
    },
 
    rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
 
        var len = ax * ax + ay * ay + az * az;
        if (len > 0) {
            len = 1 / OIMO.sqrt(len);
            ax *= len;
            ay *= len;
            az *= len;
        }
        var sin = OIMO.sin(rad * 0.5);
        var cos = OIMO.cos(rad * 0.5);
        return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
 
    },
 
    //---------------------------------------------
    // SET DYNAMIQUE POSITION AND ROTATION
    //---------------------------------------------
 
    setPosition: function (pos) {
 
        this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
        //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
        this.controlPos = true;
 
    },
 
    setQuaternion: function (q) {
        //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
 
        this.newOrientation.set(q.x, q.y, q.z, q.w);
        this.controlRot = true;
 
    },
 
    setRotation: function (rot) {
 
        this.newOrientation = this.rotationVectToQuad(rot);
        this.controlRot = true;
 
    },
 
    //---------------------------------------------
    // RESET DYNAMIQUE POSITION AND ROTATION
    //---------------------------------------------
 
    resetPosition: function (x, y, z) {
        this.linearVelocity.set(0, 0, 0);
        this.angularVelocity.set(0, 0, 0);
        this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
        //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
        this.awake();
    },
    resetQuaternion: function (q) {
        this.angularVelocity.set(0, 0, 0);
        this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
        this.awake();
    },
 
    resetRotation: function (x, y, z) {
        this.angularVelocity.set(0, 0, 0);
        this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
        this.awake();
    },
 
    //---------------------------------------------
    // GET POSITION AND ROTATION
    //---------------------------------------------
 
    getPosition: function () {
        return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
    },
 
    getRotation: function () {
 
        return new OIMO.Euler().setFromRotationMatrix(this.rotation);
 
    },
    getQuaternion: function () {
 
        return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
 
    },
 
    getMatrix: function () {
        var m = this.matrix.elements;
        var r, p;
        if (!this.sleeping) {
            // rotation matrix
            r = this.rotation.elements;
            m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
            m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
            m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
 
            // position matrix
            p = this.position;
            m[12] = p.x * OIMO.WORLD_SCALE;
            m[13] = p.y * OIMO.WORLD_SCALE;
            m[14] = p.z * OIMO.WORLD_SCALE;
 
            // sleep or not ?
            m[15] = 0;
        } else {
            m[15] = 1;
        }
 
        return m;
    }
};
/**
* The main class of body.
* is for simplify creation process and data access of rigidRody
* Rigid body has the shape of a single or multiple collision processing, 
* all setting in object
* 
* @author loth
*/
OIMO.Body = function (Obj) {
    var obj = Obj || {};
    if (!obj.world) return;
 
    if (obj.type === undefined) obj.type = "box";
    this.name = obj.name || '';
 
    // obsolete use world.add(obj)
 
    this.body = obj.world.add(obj);
 
 
    /*
        // the world where i am
        this.parent = obj.world;
    
        // Yep my name 
        this.name = obj.name || '';
    
        // I'm dynamique or not
        var move = obj.move || false;
    
        // I can sleep or not
        var noSleep  = obj.noSleep || false;
        
        // My start position
        var p = obj.pos || [0,0,0];
        p = p.map(function(x) { return x * OIMO.INV_SCALE; });
    
        // My size 
        var s = obj.size || [1,1,1];
        s = s.map(function(x) { return x * OIMO.INV_SCALE; });
    
        // My rotation in degre
        var rot = obj.rot || [0,0,0];
        rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
        var r = [];
        for (var i=0; i<rot.length/3; i++){
            var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
            r.push(tmp[0]);  r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
        }
    
        // My physics setting
        var sc = obj.sc || new OIMO.ShapeConfig();
        if(obj.config){
            // The density of the shape.
            sc.density = obj.config[0] || 1;
            // The coefficient of friction of the shape.
            sc.friction = obj.config[1] || 0.4;
            // The coefficient of restitution of the shape.
            sc.restitution = obj.config[2] || 0.2;
            // The bits of the collision groups to which the shape belongs.
            sc.belongsTo = obj.config[3] || 1;
            // The bits of the collision groups with which the shape collides.
            sc.collidesWith = obj.config[4] || 0xffffffff;
        }
    
        if(obj.massPos){
            obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
            sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
        }
        if(obj.massRot){
            obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
            sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
        }
        
        // My rigidbody
        this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
    
        // My shapes
        var shapes = [];
        var type = obj.type || "box";
        if( typeof type === 'string' ) type = [type];// single shape
    
        var n, n2;
        for(var i=0; i<type.length; i++){
            n = i*3;
            n2 = i*4;
            switch(type[i]){
                case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
                case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
                case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
            }
            this.body.addShape(shapes[i]);
            if(i>0){
                //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
                shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
                if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
            }
        } 
        
        // I'm static or i move
        if(move){
            if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
            else this.body.setupMass(0x1, true);
            if(noSleep) this.body.allowSleep = false;
            else this.body.allowSleep = true;
        } else {
            this.body.setupMass(0x2);
        }
        
        this.body.name = this.name;
        this.sleeping = this.body.sleeping;
    
        // finaly add to physics world
        this.parent.addRigidBody(this.body);*/
}
 
OIMO.Body.prototype = {
    constructor: OIMO.Body,
    // SET
    setPosition: function (pos) {
        this.body.setPosition(pos);
    },
    setQuaternion: function (q) {
        this.body.setQuaternion(q);
    },
    setRotation: function (rot) {
        this.body.setRotation(rot);
    },
    // GET
    getPosition: function () {
        return this.body.getPosition();
    },
    getRotation: function () {
        return this.body.getRotation();
    },
    getQuaternion: function () {
        return this.body.getQuaternion();
    },
    getMatrix: function () {
        return this.body.getMatrix();
    },
    getSleep: function () {
        return this.body.sleeping;
    },
    // RESET
    resetPosition: function (x, y, z) {
        this.body.resetPosition(x, y, z);
    },
    resetRotation: function (x, y, z) {
        this.body.resetRotation(x, y, z);
    },
    // force wakeup
    awake: function () {
        this.body.awake();
    },
    // remove rigidbody
    remove: function () {
        this.body.dispose();
        //this.parent.removeRigidBody(this.body);
    },
    // test if this object hit another
    checkContact: function (name) {
        this.body.checkContact(name);
        //this.parent.checkContact(this.name, name);
    }
}
/**
* The main class of link.
* is for simplify creation process and data access of Joint
* all setting in object
* 
* @author loth
*/
OIMO.Link = function (Obj) {
    var obj = Obj || {};
    if (!obj.world) return;
 
    if (obj.type === undefined) obj.type = "jointHinge";
    this.name = obj.name || '';
 
    // obsolete use world.add(obj)
 
    this.joint = obj.world.add(obj);
 
    // the world where i am
    /*this.parent = obj.world;
 
    this.name = obj.name || '';
    var type = obj.type || "jointHinge";
    var axe1 = obj.axe1 || [1,0,0];
    var axe2 = obj.axe2 || [1,0,0];
    var pos1 = obj.pos1 || [0,0,0];
    var pos2 = obj.pos2 || [0,0,0];
 
    pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
    pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
 
    var min, max;
    if(type==="jointDistance"){
        min = obj.min || 0;
        max = obj.max || 10;
        min = min*OIMO.INV_SCALE;
        max = max*OIMO.INV_SCALE;
    }else{
        min = obj.min || 57.29578;
        max = obj.max || 0;
        min = min*OIMO.TO_RAD;
        max = max*OIMO.TO_RAD;
    }
 
    var limit = obj.limit || null;
    var spring = obj.spring || null;
    var motor = obj.motor || null;
 
    // joint setting
    var jc = new OIMO.JointConfig();
    jc.allowCollision = obj.collision || false;;
    jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
    jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
    jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
    jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
    if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
    if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
    jc.body1 = obj.body1;
    jc.body2 = obj.body2;
 
    
    switch(type){
        case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max); 
            if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
            if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
        break;
        case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
            if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
            if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
        break;
        case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
        case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
        case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
        case "jointWheel": this.joint = new OIMO.WheelJoint(jc);  
            if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
            if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
            if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
        break;
    }
 
    this.joint.name = this.name;
    
    // finaly add to physics world
    this.parent.addJoint(this.joint);*/
}
 
OIMO.Link.prototype = {
    constructor: OIMO.Link,
    getPosition: function () {
        // array of two vect3 [point1, point2]
        return this.joint.getPosition();
    },
    getMatrix: function () {
        return this.joint.getMatrix();
    },
    // remove joint
    remove: function () {
        this.joint.dispose();
        //this.parent.removeJoint(this.joint);
    },
    // force wakeup linked body
    awake: function () {
        this.joint.awake();
    }
}
/**
* The Dictionary class for testing
* @author lo-th
*/
OIMO.Dictionary = function () {
 
    this.data = {};
    this.keys = [];
 
};
 
OIMO.Dictionary.prototype = {
 
    constructor: OIMO.Dictionary,
 
    set: function (value) {
 
        var key = value.id;
        if (!this.get[key]) this.keys.push(key);
 
        this.data[key] = value;
 
    },
 
    get: function (id) {
 
        return this.data[id];
 
    },
 
    del: function (value) {
        var k = this.keys;
 
        var n = k.indexOf(value.id);
        if (n > -1) {
            delete this.data[k[n]];
            k.splice(n, 1);
        }
 
    },
 
    reset: function () {
 
        var data = this.data, keys = this.keys, key;
        while (keys.length > 0) {
            key = keys.pop();
            delete data[key];
        }
 
    }
};
OIMO.Performance = function (world) {
    this.parent = world;
    this.infos = new OIMO_ARRAY_TYPE(13);
    this.f = [0, 0, 0];
 
    this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
    this.broadPhase = this.types[this.parent.broadPhase.types];
 
    this.version = OIMO.REVISION;
 
    this.fps = 0;
    this.broadPhaseTime = 0;
    this.narrowPhaseTime = 0;
    this.solvingTime = 0;
    //this.updatingTime = 0;
    this.totalTime = 0;
};
 
OIMO.Performance.prototype = {
    upfps: function () {
        this.f[1] = Date.now();
        if (this.f[1] - 1000 > this.f[0]) { this.f[0] = this.f[1]; this.fps = this.f[2]; this.f[2] = 0; } this.f[2]++;
    },
    updatingTime: function () {
        return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
    },
    show: function () {
        var info = [
            "Oimo.js " + this.version + "<br>",
            this.broadPhase + "<br><br>",
            "FPS: " + this.fps + " fps<br><br>",
            "rigidbody " + this.parent.numRigidBodies + "<br>",
            "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
            "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
            "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
            "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
            "Time in milliseconde<br><br>",
            "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
            "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
            "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
            "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
            "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
        ].join("\n");
        return info;
    },
    toArray: function () {
        this.infos[0] = this.parent.broadPhase.types;
        this.infos[1] = this.parent.numRigidBodies;
        this.infos[2] = this.parent.numContacts;
        this.infos[3] = this.parent.broadPhase.numPairChecks;
        this.infos[4] = this.parent.numContactPoints;
        this.infos[5] = this.parent.numIslands;
        this.infos[6] = this.broadPhaseTime;
        this.infos[7] = this.narrowPhaseTime;
        this.infos[8] = this.solvingTime;
        this.infos[9] = this.updatingTime();
        this.infos[10] = this.totalTime;
        this.infos[11] = this.fps;
        return this.infos;
    }
};
 
OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
    this.elements = new OIMO_ARRAY_TYPE(16);
    var te = this.elements;
    te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
    te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
    te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
    te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
};
 
OIMO.Mat44.prototype = {
    constructor: OIMO.Mat44,
 
    set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
 
        var te = this.elements;
 
        te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
        te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
        te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
        te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
 
        return this;
    }/*,
    extractRotation: function () {
 
        var v1 = new THREE.Vector3();
 
        return function ( m ) {
 
            var te = this.elements;
            var me = m.elements;
 
            var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
            var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
            var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
 
            te[ 0 ] = me[ 0 ] * scaleX;
            te[ 1 ] = me[ 1 ] * scaleX;
            te[ 2 ] = me[ 2 ] * scaleX;
 
            te[ 4 ] = me[ 4 ] * scaleY;
            te[ 5 ] = me[ 5 ] * scaleY;
            te[ 6 ] = me[ 6 ] * scaleY;
 
            te[ 8 ] = me[ 8 ] * scaleZ;
            te[ 9 ] = me[ 9 ] * scaleZ;
            te[ 10 ] = me[ 10 ] * scaleZ;
 
            return this;
 
        };
 
    }() */
}
OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
    this.elements = new OIMO_ARRAY_TYPE(9);
    var te = this.elements;
 
    this.init(
        (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
        e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
        e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
    );
};
 
OIMO.Mat33.prototype = {
    constructor: OIMO.Mat33,
 
    set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
 
        var te = this.elements;
 
        te[0] = e00; te[1] = e01; te[2] = e02;
        te[3] = e10; te[4] = e11; te[5] = e12;
        te[6] = e20; te[7] = e21; te[8] = e22;
 
        return this;
 
    },
 
    init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
        var te = this.elements;
        te[0] = e00; te[1] = e01; te[2] = e02;
        te[3] = e10; te[4] = e11; te[5] = e12;
        te[6] = e20; te[7] = e21; te[8] = e22;
        return this;
    },
 
 
 
    multiply: function (s) {
        var te = this.elements;
        te[0] *= s; te[1] *= s; te[2] *= s;
        te[3] *= s; te[4] *= s; te[5] *= s;
        te[6] *= s; te[7] *= s; te[8] *= s;
        return this;
    },
 
 
    add: function (m1, m2) {
        var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
        te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
        te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
        te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
        return this;
    },
    addEqual: function (m) {
        var te = this.elements, tem = m.elements;
        te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
        te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
        te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
        return this;
    },
    sub: function (m1, m2) {
        var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
        te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
        te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
        te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
        return this;
    },
    subEqual: function (m) {
        var te = this.elements, tem = m.elements;
        te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
        te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
        te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
        return this;
    },
    scale: function (m, s) {
        var te = this.elements, tm = m.elements;
        te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
        te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
        te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
        return this;
    },
    scaleEqual: function (s) {
        var te = this.elements;
        te[0] *= s; te[1] *= s; te[2] *= s;
        te[3] *= s; te[4] *= s; te[5] *= s;
        te[6] *= s; te[7] *= s; te[8] *= s;
        return this;
    },
    mul: function (m1, m2) {
        var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
        a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
        a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
        a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
        b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
        b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
        b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
        te[0] = a0 * b0 + a1 * b3 + a2 * b6;
        te[1] = a0 * b1 + a1 * b4 + a2 * b7;
        te[2] = a0 * b2 + a1 * b5 + a2 * b8;
        te[3] = a3 * b0 + a4 * b3 + a5 * b6;
        te[4] = a3 * b1 + a4 * b4 + a5 * b7;
        te[5] = a3 * b2 + a4 * b5 + a5 * b8;
        te[6] = a6 * b0 + a7 * b3 + a8 * b6;
        te[7] = a6 * b1 + a7 * b4 + a8 * b7;
        te[8] = a6 * b2 + a7 * b5 + a8 * b8;
        return this;
    },
    mulScale: function (m, sx, sy, sz, Prepend) {
        var prepend = Prepend || false;
        var te = this.elements, tm = m.elements;
        if (prepend) {
            te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
            te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
            te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
        } else {
            te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
            te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
            te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
        }
        return this;
    },
    mulRotate: function (m, rad, ax, ay, az, Prepend) {
        var prepend = Prepend || false;
        var s = OIMO.sin(rad);
        var c = OIMO.cos(rad);
        var c1 = 1 - c;
        var r00 = ax * ax * c1 + c;
        var r01 = ax * ay * c1 - az * s;
        var r02 = ax * az * c1 + ay * s;
        var r10 = ay * ax * c1 + az * s;
        var r11 = ay * ay * c1 + c;
        var r12 = ay * az * c1 - ax * s;
        var r20 = az * ax * c1 - ay * s;
        var r21 = az * ay * c1 + ax * s;
        var r22 = az * az * c1 + c;
 
        var tm = m.elements;
 
        var a0 = tm[0], a3 = tm[3], a6 = tm[6];
        var a1 = tm[1], a4 = tm[4], a7 = tm[7];
        var a2 = tm[2], a5 = tm[5], a8 = tm[8];
 
        var te = this.elements;
 
        if (prepend) {
            te[0] = r00 * a0 + r01 * a3 + r02 * a6;
            te[1] = r00 * a1 + r01 * a4 + r02 * a7;
            te[2] = r00 * a2 + r01 * a5 + r02 * a8;
            te[3] = r10 * a0 + r11 * a3 + r12 * a6;
            te[4] = r10 * a1 + r11 * a4 + r12 * a7;
            te[5] = r10 * a2 + r11 * a5 + r12 * a8;
            te[6] = r20 * a0 + r21 * a3 + r22 * a6;
            te[7] = r20 * a1 + r21 * a4 + r22 * a7;
            te[8] = r20 * a2 + r21 * a5 + r22 * a8;
        } else {
            te[0] = a0 * r00 + a1 * r10 + a2 * r20;
            te[1] = a0 * r01 + a1 * r11 + a2 * r21;
            te[2] = a0 * r02 + a1 * r12 + a2 * r22;
            te[3] = a3 * r00 + a4 * r10 + a5 * r20;
            te[4] = a3 * r01 + a4 * r11 + a5 * r21;
            te[5] = a3 * r02 + a4 * r12 + a5 * r22;
            te[6] = a6 * r00 + a7 * r10 + a8 * r20;
            te[7] = a6 * r01 + a7 * r11 + a8 * r21;
            te[8] = a6 * r02 + a7 * r12 + a8 * r22;
        }
        return this;
    },
    transpose: function (m) {
        var te = this.elements, tm = m.elements;
        te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
        te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
        te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
        return this;
    },
    setQuat: function (q) {
        var te = this.elements,
        x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
        xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
        xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
        sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
 
        te[0] = 1 - yy - zz;
        te[1] = xy - sz;
        te[2] = xz + sy;
        te[3] = xy + sz;
        te[4] = 1 - xx - zz;
        te[5] = yz - sx;
        te[6] = xz - sy;
        te[7] = yz + sx;
        te[8] = 1 - xx - yy;
        return this;
    },
    invert: function (m) {
        var te = this.elements, tm = m.elements,
        a0 = tm[0], a3 = tm[3], a6 = tm[6],
        a1 = tm[1], a4 = tm[4], a7 = tm[7],
        a2 = tm[2], a5 = tm[5], a8 = tm[8],
        b01 = a4 * a8 - a7 * a5,
        b11 = a7 * a2 - a1 * a8,
        b21 = a1 * a5 - a4 * a2,
        dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
 
        if (dt != 0) { dt = 1.0 / dt; }
        te[0] = dt * b01;//(a4*a8 - a5*a7);
        te[1] = dt * b11;//(a2*a7 - a1*a8);
        te[2] = dt * b21;//(a1*a5 - a2*a4);
        te[3] = dt * (a5 * a6 - a3 * a8);
        te[4] = dt * (a0 * a8 - a2 * a6);
        te[5] = dt * (a2 * a3 - a0 * a5);
        te[6] = dt * (a3 * a7 - a4 * a6);
        te[7] = dt * (a1 * a6 - a0 * a7);
        te[8] = dt * (a0 * a4 - a1 * a3);
        return this;
    },
    /*copy: function(m){
        var te = this.elements, tem = m.elements;
        te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
        te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
        te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
        return this;
    },*/
    toEuler: function () { // not work !!
        function clamp(x) {
            return OIMO.min(OIMO.max(x, -1), 1);
        }
        var te = this.elements;
        var m11 = te[0], m12 = te[3], m13 = te[6];
        var m21 = te[1], m22 = te[4], m23 = te[7];
        var m31 = te[2], m32 = te[5], m33 = te[8];
 
        var p = new OIMO.Vec3();
        var d = new OIMO.Quat();
        var s;
 
        p.y = OIMO.asin(clamp(m13));
 
        if (OIMO.abs(m13) < 0.99999) {
            p.x = OIMO.atan2(-m23, m33);
            p.z = OIMO.atan2(-m12, m11);
        } else {
            p.x = OIMO.atan2(m32, m22);
            p.z = 0;
        }
 
        return p;
    },
    /*clone: function(){
        var te = this.elements;
 
        return new OIMO.Mat33(
            te[0], te[1], te[2],
            te[3], te[4], te[5],
            te[6], te[7], te[8]
        );
    },*/
 
    toString: function () {
        var te = this.elements;
        var text =
        "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
        "     |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
        "     |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
        return text;
    },
 
    // OK 
 
    multiplyScalar: function (s) {
 
        var te = this.elements;
 
        te[0] *= s; te[3] *= s; te[6] *= s;
        te[1] *= s; te[4] *= s; te[7] *= s;
        te[2] *= s; te[5] *= s; te[8] *= s;
 
        return this;
 
    },
 
 
 
    identity: function () {
 
        this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
 
        return this;
 
    },
 
 
    clone: function () {
 
        return new this.constructor().fromArray(this.elements);
 
    },
 
    copy: function (m) {
 
        var me = m.elements;
 
        this.set(
 
            me[0], me[3], me[6],
            me[1], me[4], me[7],
            me[2], me[5], me[8]
 
        );
 
        return this;
 
    },
 
    fromArray: function (array) {
 
        this.elements.set(array);
 
        return this;
 
    },
 
    toArray: function () {
 
        var te = this.elements;
 
        return [
            te[0], te[1], te[2],
            te[3], te[4], te[5],
            te[6], te[7], te[8]
        ];
 
    }
 
 
};
OIMO.Quat = function (s, x, y, z) {
    this.s = (s !== undefined) ? s : 1;
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
};
 
OIMO.Quat.prototype = {
 
    constructor: OIMO.Quat,
 
    set: function (x, y, z, w) {
 
 
        this.x = x;
        this.y = y;
        this.z = z;
        this.s = w;
 
        return this;
 
    },
 
    init: function (s, x, y, z) {
        this.s = (s !== undefined) ? s : 1;
        this.x = x || 0;
        this.y = y || 0;
        this.z = z || 0;
        return this;
    },
    add: function (q1, q2) {
        this.s = q1.s + q2.s;
        this.x = q1.x + q2.x;
        this.y = q1.y + q2.y;
        this.z = q1.z + q2.z;
        return this;
    },
    addTime: function (v, t) {
        var x = v.x;
        var y = v.y;
        var z = v.z;
        var qs = this.s;
        var qx = this.x;
        var qy = this.y;
        var qz = this.z;
        t *= 0.5;
        var ns = (-x * qx - y * qy - z * qz) * t;
        var nx = (x * qs + y * qz - z * qy) * t;
        var ny = (-x * qz + y * qs + z * qx) * t;
        var nz = (x * qy - y * qx + z * qs) * t;
        qs += ns;
        qx += nx;
        qy += ny;
        qz += nz;
        var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
        this.s = qs * s;
        this.x = qx * s;
        this.y = qy * s;
        this.z = qz * s;
        return this;
    },
    sub: function (q1, q2) {
        this.s = q1.s - q2.s;
        this.x = q1.x - q2.x;
        this.y = q1.y - q2.y;
        this.z = q1.z - q2.z;
        return this;
    },
    scale: function (q, s) {
        this.s = q.s * s;
        this.x = q.x * s;
        this.y = q.y * s;
        this.z = q.z * s;
        return this;
    },
    mul: function (q1, q2) {
        var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
        bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
        this.x = ax * bs + as * bx + ay * bz - az * by;
        this.y = ay * bs + as * by + az * bx - ax * bz;
        this.z = az * bs + as * bz + ax * by - ay * bx;
        this.s = as * bs - ax * bx - ay * by - az * bz;
        return this;
    },
    arc: function (v1, v2) {
        var x1 = v1.x;
        var y1 = v1.y;
        var z1 = v1.z;
        var x2 = v2.x;
        var y2 = v2.y;
        var z2 = v2.z;
        var d = x1 * x2 + y1 * y2 + z1 * z2;
        if (d == -1) {
            x2 = y1 * x1 - z1 * z1;
            y2 = -z1 * y1 - x1 * x1;
            z2 = x1 * z1 + y1 * y1;
            d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
            this.s = 0;
            this.x = x2 * d;
            this.y = y2 * d;
            this.z = z2 * d;
            return this;
        }
        var cx = y1 * z2 - z1 * y2;
        var cy = z1 * x2 - x1 * z2;
        var cz = x1 * y2 - y1 * x2;
        this.s = OIMO.sqrt((1 + d) * 0.5);
        d = 0.5 / this.s;
        this.x = cx * d;
        this.y = cy * d;
        this.z = cz * d;
        return this;
    },
    normalize: function (q) {
        var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
        if (len > 0) { len = 1 / len; }
        this.s = q.s * len;
        this.x = q.x * len;
        this.y = q.y * len;
        this.z = q.z * len;
        return this;
    },
    invert: function (q) {
        this.s = q.s;
        this.x = -q.x;
        this.y = -q.y;
        this.z = -q.z;
        return this;
    },
    length: function () {
        return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
    },
 
    copy: function (q) {
        this.s = q.s;
        this.x = q.x;
        this.y = q.y;
        this.z = q.z;
        return this;
    },
    testDiff: function (q) {
        if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
        else return false;
    },
    clone: function (q) {
        return new OIMO.Quat(this.s, this.x, this.y, this.z);
    },
    toString: function () {
        return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
    }
}
 
 
// for three easy export
OIMO.Quaternion = function (x, y, z, w) {
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
    this.w = (w !== undefined) ? w : 1;
};
 
OIMO.Quaternion.prototype = {
 
    constructor: OIMO.Quaternion,
    setFromRotationMatrix: function (m) {
 
        // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
 
        // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
 
        var te = m.elements,
 
            m11 = te[0], m12 = te[1], m13 = te[2],
            m21 = te[3], m22 = te[4], m23 = te[5],
            m31 = te[6], m32 = te[7], m33 = te[8],
 
            trace = m11 + m22 + m33,
            s;
 
        if (trace > 0) {
 
            s = 0.5 / OIMO.sqrt(trace + 1.0);
 
            this.w = 0.25 / s;
            this.x = (m32 - m23) * s;
            this.y = (m13 - m31) * s;
            this.z = (m21 - m12) * s;
 
        } else if (m11 > m22 && m11 > m33) {
 
            s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
 
            this.w = (m32 - m23) / s;
            this.x = 0.25 * s;
            this.y = (m12 + m21) / s;
            this.z = (m13 + m31) / s;
 
        } else if (m22 > m33) {
 
            s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
 
            this.w = (m13 - m31) / s;
            this.x = (m12 + m21) / s;
            this.y = 0.25 * s;
            this.z = (m23 + m32) / s;
 
        } else {
 
            s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
 
            this.w = (m21 - m12) / s;
            this.x = (m13 + m31) / s;
            this.y = (m23 + m32) / s;
            this.z = 0.25 * s;
 
        }
 
        //this.onChangeCallback();
 
        return this;
 
    }
}
OIMO.Vec3 = function (x, y, z) {
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
};
 
OIMO.Vec3.prototype = {
 
    constructor: OIMO.Vec3,
 
    init: function (x, y, z) {
        this.x = x || 0;
        this.y = y || 0;
        this.z = z || 0;
        return this;
    },
    set: function (x, y, z) {
        this.x = x;
        this.y = y;
        this.z = z;
        return this;
    },
    add: function (v1, v2) {
        this.x = v1.x + v2.x;
        this.y = v1.y + v2.y;
        this.z = v1.z + v2.z;
        return this;
    },
    addEqual: function (v) {
        this.x += v.x;
        this.y += v.y;
        this.z += v.z;
        return this;
    },
    addTime: function (v, t) {
        this.x += v.x * t;
        this.y += v.y * t;
        this.z += v.z * t;
        return this;
    },
    sub: function (v1, v2) {
        this.x = v1.x - v2.x;
        this.y = v1.y - v2.y;
        this.z = v1.z - v2.z;
        return this;
    },
    subEqual: function (v) {
        this.x -= v.x;
        this.y -= v.y;
        this.z -= v.z;
        return this;
    },
    addScale: function (v, s) {
        this.x += v.x * s;
        this.y += v.y * s;
        this.z += v.z * s;
        return this;
    },
    scale: function (v, s) {
        this.x = v.x * s;
        this.y = v.y * s;
        this.z = v.z * s;
        return this;
    },
    scaleEqual: function (s) {
        this.x *= s;
        this.y *= s;
        this.z *= s;
        return this;
    },
    /*dot: function(v){
        return this.x*v.x+this.y*v.y+this.z*v.z;
    },*/
    cross: function (v1, v2) {
        var ax = v1.x, ay = v1.y, az = v1.z,
        bx = v2.x, by = v2.y, bz = v2.z;
        this.x = ay * bz - az * by;
        this.y = az * bx - ax * bz;
        this.z = ax * by - ay * bx;
        return this;
    },
    mul: function (o, v, m) {
        var te = m.elements;
        this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
        this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
        this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
        return this;
    },
    mulMat: function (m, v) {
        var te = m.elements;
        this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
        this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
        this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
        return this;
    },
    normalize: function (v) {
        var x = v.x, y = v.y, z = v.z;
        var l = x * x + y * y + z * z;
        if (l > 0) {
            l = 1 / OIMO.sqrt(l);
            this.x = x * l;
            this.y = y * l;
            this.z = z * l;
        }
        return this;
    },
    /*norm: function(){
        var x = this.x, y = this.y, z = this.z;
        var l = x*x + y*y + z*z;
        if (l > 0) {
            l = 1 / OIMO.sqrt(l);
            this.x = x*l;
            this.y = y*l;
            this.z = z*l;
        }
        return this;
    },*/
    invert: function (v) {
        this.x = -v.x;
        this.y = -v.y;
        this.z = -v.z;
        return this;
    },
    /*length: function(){
        var x = this.x, y = this.y, z = this.z;
        return OIMO.sqrt(x*x + y*y + z*z);
    },*/
 
    negate: function () {
 
        this.x = -this.x;
        this.y = -this.y;
        this.z = -this.z;
 
        return this;
 
    },
 
    dot: function (v) {
 
        return this.x * v.x + this.y * v.y + this.z * v.z;
 
    },
 
    lengthSq: function () {
 
        return this.x * this.x + this.y * this.y + this.z * this.z;
 
    },
 
    length: function () {
 
        return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
 
    },
 
    /*len: function(){
        var x = this.x, y = this.y, z = this.z;
        return x*x + y*y + z*z;
    },*/
 
    copy: function (v) {
        this.x = v.x;
        this.y = v.y;
        this.z = v.z;
        return this;
    },
 
    applyQuaternion: function (q) {
 
        var x = this.x;
        var y = this.y;
        var z = this.z;
 
        var qx = q.x;
        var qy = q.y;
        var qz = q.z;
        var qs = q.s;
 
        // calculate quat * vector
 
        var ix = qs * x + qy * z - qz * y;
        var iy = qs * y + qz * x - qx * z;
        var iz = qs * z + qx * y - qy * x;
        var iw = -qx * x - qy * y - qz * z;
 
        // calculate result * inverse quat
 
        this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
        this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
        this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
 
        return this;
 
    },
    testZero: function () {
        if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
        else return false;
    },
    testDiff: function (v) {
 
        return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
        //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
        //else return false;
    },
 
    equals: function (v) {
 
        return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
 
    },
 
    clone: function () {
 
        return new this.constructor(this.x, this.y, this.z);
 
    },
 
    toString: function () {
        return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
    },
 
    multiplyScalar: function (scalar) {
 
        if (isFinite(scalar)) {
            this.x *= scalar;
            this.y *= scalar;
            this.z *= scalar;
        } else {
            this.x = 0;
            this.y = 0;
            this.z = 0;
        }
 
        return this;
 
    },
 
    divideScalar: function (scalar) {
 
        return this.multiplyScalar(1 / scalar);
 
    },
    // TODO rename to normalize
    norm: function () {
 
        return this.divideScalar(this.length());
 
    },
 
 
}
OIMO.Euler = function (x, y, z, order) {
 
    this._x = x || 0;
    this._y = y || 0;
    this._z = z || 0;
    this._order = order || OIMO.Euler.DefaultOrder;
 
};
 
OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
 
OIMO.Euler.DefaultOrder = 'XYZ';
 
OIMO.clamp = function (x, a, b) {
    return (x < a) ? a : ((x > b) ? b : x);
}
 
OIMO.Euler.prototype = {
 
    constructor: OIMO.Euler,
 
    _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
 
    get x() {
 
        return this._x;
 
    },
 
    set x(value) {
 
        this._x = value;
        this.onChangeCallback();
 
    },
 
    get y() {
 
        return this._y;
 
    },
 
    set y(value) {
 
        this._y = value;
        this.onChangeCallback();
 
    },
 
    get z() {
 
        return this._z;
 
    },
 
    set z(value) {
 
        this._z = value;
        this.onChangeCallback();
 
    },
 
    get order() {
 
        return this._order;
 
    },
 
    set order(value) {
 
        this._order = value;
        this.onChangeCallback();
 
    },
 
    set: function (x, y, z, order) {
 
        this._x = x;
        this._y = y;
        this._z = z;
        this._order = order || this._order;
 
        this.onChangeCallback();
 
        return this;
 
    },
 
    copy: function (euler) {
 
        this._x = euler._x;
        this._y = euler._y;
        this._z = euler._z;
        this._order = euler._order;
 
        this.onChangeCallback();
 
        return this;
 
    },
 
    setFromRotationMatrix: function (m, order) {
 
        var clamp = OIMO.clamp;
 
        // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
 
        var te = m.elements;
        /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
		var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
		var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
 
        var m11 = te[0], m12 = te[1], m13 = te[2],
            m21 = te[3], m22 = te[4], m23 = te[5],
            m31 = te[6], m32 = te[7], m33 = te[8];
 
        order = order || this._order;
 
        if (order === 'XYZ') {
 
            this._y = OIMO.asin(clamp(m13, -1, 1));
 
            if (OIMO.abs(m13) < 0.99999) {
 
                this._x = OIMO.atan2(-m23, m33);
                this._z = OIMO.atan2(-m12, m11);
 
            } else {
 
                this._x = OIMO.atan2(m32, m22);
                this._z = 0;
 
            }
 
        } else if (order === 'YXZ') {
 
            this._x = OIMO.asin(-clamp(m23, -1, 1));
 
            if (OIMO.abs(m23) < 0.99999) {
 
                this._y = OIMO.atan2(m13, m33);
                this._z = OIMO.atan2(m21, m22);
 
            } else {
 
                this._y = OIMO.atan2(-m31, m11);
                this._z = 0;
 
            }
 
        } else if (order === 'ZXY') {
 
            this._x = OIMO.asin(clamp(m32, -1, 1));
 
            if (OIMO.abs(m32) < 0.99999) {
 
                this._y = OIMO.atan2(-m31, m33);
                this._z = OIMO.atan2(-m12, m22);
 
            } else {
 
                this._y = 0;
                this._z = OIMO.atan2(m21, m11);
 
            }
 
        } else if (order === 'ZYX') {
 
            this._y = OIMO.asin(-clamp(m31, -1, 1));
 
            if (OIMO.abs(m31) < 0.99999) {
 
                this._x = OIMO.atan2(m32, m33);
                this._z = OIMO.atan2(m21, m11);
 
            } else {
 
                this._x = 0;
                this._z = OIMO.atan2(-m12, m22);
 
            }
 
        } else if (order === 'YZX') {
 
            this._z = OIMO.asin(clamp(m21, -1, 1));
 
            if (OIMO.abs(m21) < 0.99999) {
 
                this._x = OIMO.atan2(-m23, m22);
                this._y = OIMO.atan2(-m31, m11);
 
            } else {
 
                this._x = 0;
                this._y = OIMO.atan2(m13, m33);
 
            }
 
        } else if (order === 'XZY') {
 
            this._z = OIMO.asin(-clamp(m12, -1, 1));
 
            if (OIMO.abs(m12) < 0.99999) {
 
                this._x = OIMO.atan2(m32, m22);
                this._y = OIMO.atan2(m13, m11);
 
            } else {
 
                this._x = OIMO.atan2(-m23, m33);
                this._y = 0;
 
            }
 
        } else {
 
            console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
 
        }
 
        this._order = order;
 
        this.onChangeCallback();
 
        return this;
 
    },
 
    setFromQuaternion: function (q, order, update) {
 
        var clamp = OIMO.clamp;
 
        // q is assumed to be normalized
 
        // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
 
        var sqx = q.x * q.x;
        var sqy = q.y * q.y;
        var sqz = q.z * q.z;
        var sqw = q.s * q.s;
 
        order = order || this._order;
 
        if (order === 'XYZ') {
 
            this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
            this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
            this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
 
        } else if (order === 'YXZ') {
 
            this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
            this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
            this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
 
        } else if (order === 'ZXY') {
 
            this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
            this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
            this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
 
        } else if (order === 'ZYX') {
 
            this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
            this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
            this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
 
        } else if (order === 'YZX') {
 
            this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
            this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
            this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
 
        } else if (order === 'XZY') {
 
            this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
            this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
            this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
 
        } else {
 
            console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
 
        }
 
        this._order = order;
 
        if (update !== false) this.onChangeCallback();
 
        return this;
 
    },
 
    reorder: function () {
 
        // WARNING: this discards revolution information -bhouston
 
        var q = new OIMO.Quat();
 
        return function (newOrder) {
 
            q.setFromEuler(this);
            this.setFromQuaternion(q, newOrder);
 
        };
 
 
    }(),
 
    equals: function (euler) {
 
        return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
 
    },
 
    fromArray: function (array) {
 
        this._x = array[0];
        this._y = array[1];
        this._z = array[2];
        if (array[3] !== undefined) this._order = array[3];
 
        this.onChangeCallback();
 
        return this;
 
    },
 
    toArray: function () {
 
        return [this._x, this._y, this._z, this._order];
 
    },
 
    onChange: function (callback) {
 
        this.onChangeCallback = callback;
 
        return this;
 
    },
 
    onChangeCallback: function () { },
 
    clone: function () {
 
        return new OIMO.Euler(this._x, this._y, this._z, this._order);
 
    }
 
};
 
OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
    var c1 = OIMO.cos(oy * 0.5);//heading
    var s1 = OIMO.sin(oy * 0.5);
    var c2 = OIMO.cos(oz * 0.5);//altitude
    var s2 = OIMO.sin(oz * 0.5);
    var c3 = OIMO.cos(ox * 0.5);//bank
    var s3 = OIMO.sin(ox * 0.5);
    var c1c2 = c1 * c2;
    var s1s2 = s1 * s2;
    var w = c1c2 * c3 - s1s2 * s3;
    var x = c1c2 * s3 + s1s2 * c3;
    var y = s1 * c2 * c3 + c1 * s2 * s3;
    var z = c1 * s2 * c3 - s1 * c2 * s3;
    var angle = 2 * OIMO.acos(w);
    var norm = x * x + y * y + z * z;
    if (norm < 0.001) {
        x = 1;
        y = z = 0;
    } else {
        norm = OIMO.sqrt(norm);
        x /= norm;
        y /= norm;
        z /= norm;
    }
    return [angle, x, y, z];
}
 
OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
    var ch = OIMO.cos(oy);//heading
    var sh = OIMO.sin(oy);
    var ca = OIMO.cos(oz);//altitude
    var sa = OIMO.sin(oz);
    var cb = OIMO.cos(ox);//bank
    var sb = OIMO.sin(ox);
    var mtx = new OIMO.Mat33();
 
    var te = mtx.elements;
    te[0] = ch * ca;
    te[1] = sh * sb - ch * sa * cb;
    te[2] = ch * sa * sb + sh * cb;
    te[3] = sa;
    te[4] = ca * cb;
    te[5] = -ca * sb;
    te[6] = -sh * ca;
    te[7] = sh * sa * cb + ch * sb;
    te[8] = -sh * sa * sb + ch * cb;
    return mtx;
}
 
OIMO.MatrixToEuler = function (mtx) {// angles in radians
    var te = mtx.elements;
    var x, y, z;
    if (te[3] > 0.998) { // singularity at north pole
        y = OIMO.atan2(te[2], te[8]);
        z = OIMO.PI / 2;
        x = 0;
    } else if (te[3] < -0.998) { // singularity at south pole
        y = OIMO.atan2(te[2], te[8]);
        z = -OIMO.PI / 2;
        x = 0;
    } else {
        y = OIMO.atan2(-te[6], te[0]);
        x = OIMO.atan2(-te[5], te[4]);
        z = OIMO.asin(te[3]);
    }
    return [x, y, z];
}
 
OIMO.unwrapDegrees = function (r) {
    r = r % 360;
    if (r > 180) r -= 360;
    if (r < -180) r += 360;
    return r;
}
 
OIMO.unwrapRadian = function (r) {
    r = r % OIMO.TwoPI;
    if (r > OIMO.PI) r -= OIMO.TwoPI;
    if (r < -OIMO.PI) r += OIMO.TwoPI;
    return r;
}
OIMO.Distance3d = function (p1, p2) {
    var xd = p2[0] - p1[0];
    var yd = p2[1] - p1[1];
    var zd = p2[2] - p1[2];
    return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
}
/**
* The base class of all type of the constraints.
* @author saharan
*/
OIMO.Constraint = function () {
    // The parent world of the constraint.
    this.parent = null;
    // The first body of the constraint.
    this.body1 = null;
    // The second body of the constraint.
    this.body2 = null;
    // Internal
    this.addedToIsland = false;
}
 
OIMO.Constraint.prototype = {
    constructor: OIMO.Constraint,
    /**
    * Prepare for solving the constraint.
    * @param   timeStep
    * @param   invTimeStep
    */
    preSolve: function (timeStep, invTimeStep) {
        OIMO.Error("Constraint", "Inheritance error.");
    },
    /**
    * Solve the constraint.
    * This is usually called iteratively.
    */
    solve: function () {
        OIMO.Error("Constraint", "Inheritance error.");
    },
    /**
    * Do the post-processing.
    */
    postSolve: function () {
        OIMO.Error("Constraint", "Inheritance error.");
    }
}
/**
 * Joints are used to constrain the motion between two rigid bodies.
 * @author saharan
 * @author lo-th
 */
 
OIMO.Joint = function (config) {
 
    OIMO.Constraint.call(this);
 
    // joint name
    this.name = "";
 
    // The type of the joint.
    this.type = OIMO.JOINT_NULL;
    //  The previous joint in the world.
    this.prev = null;
    // The next joint in the world.
    this.next = null;
 
    this.body1 = config.body1;
    this.body2 = config.body2;
 
    // The anchor point on the first rigid body in local coordinate system.
    this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
    // The anchor point on the second rigid body in local coordinate system.
    this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
    // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
    this.relativeAnchorPoint1 = new OIMO.Vec3();
    // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
    this.relativeAnchorPoint2 = new OIMO.Vec3();
    //  The anchor point on the first rigid body in world coordinate system.
    this.anchorPoint1 = new OIMO.Vec3();
    // The anchor point on the second rigid body in world coordinate system.
    this.anchorPoint2 = new OIMO.Vec3();
    //  Whether allow collision between connected rigid bodies or not.
    this.allowCollision = config.allowCollision;
 
    this.b1Link = new OIMO.JointLink(this);
    this.b2Link = new OIMO.JointLink(this);
 
    this.matrix = new OIMO.Mat44();
 
};
 
OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
OIMO.Joint.prototype.constructor = OIMO.Joint;
 
// Update all the anchor points.
 
OIMO.Joint.prototype.updateAnchorPoints = function () {
 
    this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
    this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
 
    this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
    this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
 
};
 
// Attach the joint from the bodies.
 
OIMO.Joint.prototype.attach = function () {
 
    this.b1Link.body = this.body2;
    this.b2Link.body = this.body1;
    if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
    else this.b1Link.next = null;
    this.body1.jointLink = this.b1Link;
    this.body1.numJoints++;
    if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
    else this.b2Link.next = null;
    this.body2.jointLink = this.b2Link;
    this.body2.numJoints++;
 
};
 
// Detach the joint from the bodies.
 
OIMO.Joint.prototype.detach = function () {
 
    var prev = this.b1Link.prev;
    var next = this.b1Link.next;
    if (prev != null) prev.next = next;
    if (next != null) next.prev = prev;
    if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
    this.b1Link.prev = null;
    this.b1Link.next = null;
    this.b1Link.body = null;
    this.body1.numJoints--;
 
    prev = this.b2Link.prev;
    next = this.b2Link.next;
    if (prev != null) prev.next = next;
    if (next != null) next.prev = prev;
    if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
    this.b2Link.prev = null;
    this.b2Link.next = null;
    this.b2Link.body = null;
    this.body2.numJoints--;
 
    this.b1Link.body = null;
    this.b2Link.body = null;
 
};
 
 
// Awake the bodies.
 
OIMO.Joint.prototype.awake = function () {
 
    this.body1.awake();
    this.body2.awake();
 
};
 
// calculation function
 
OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
};
 
OIMO.Joint.prototype.solve = function () {
};
 
OIMO.Joint.prototype.postSolve = function () {
};
 
// Delete process
 
OIMO.Joint.prototype.remove = function () {
 
    this.dispose();
 
};
 
OIMO.Joint.prototype.dispose = function () {
 
    this.parent.removeJoint(this);
 
};
 
 
// Three js add
 
OIMO.Joint.prototype.getPosition = function () {
 
    var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
    var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
    return [p1, p2];
 
};
 
OIMO.Joint.prototype.getMatrix = function () {
 
    var m = this.matrix.elements;
    var p1 = this.anchorPoint1;
    var p2 = this.anchorPoint2;
    m[0] = p1.x * OIMO.WORLD_SCALE;
    m[1] = p1.y * OIMO.WORLD_SCALE;
    m[2] = p1.z * OIMO.WORLD_SCALE;
    m[3] = 0;
 
    m[4] = p2.x * OIMO.WORLD_SCALE;
    m[5] = p2.y * OIMO.WORLD_SCALE;
    m[6] = p2.z * OIMO.WORLD_SCALE;
    m[7] = 0;
 
    return m;
 
};
/**
* A joint configuration holds all configuration data for constructing a joint.
* Joint configurations can be reused safely.
* @author saharan
*/
OIMO.JointConfig = function () {
    // The first rigid body of the joint.
    this.body1 = null;
    // The second rigid body of the joint.
    this.body2 = null;
    // The anchor point on the first rigid body in local coordinate system.
    this.localAnchorPoint1 = new OIMO.Vec3();
    //  The anchor point on the second rigid body in local coordinate system.
    this.localAnchorPoint2 = new OIMO.Vec3();
    // The axis in the first body's coordinate system.
    // his property is available in some joints.
    this.localAxis1 = new OIMO.Vec3();
    // The axis in the second body's coordinate system.
    // This property is available in some joints.
    this.localAxis2 = new OIMO.Vec3();
    //  Whether allow collision between connected rigid bodies or not.
    this.allowCollision = false;
 
};
/**
* A link list of joints.
* @author saharan
*/
OIMO.JointLink = function (joint) {
    // The previous joint link.
    this.prev = null;
    // The next joint link.
    this.next = null;
    // The other rigid body connected to the joint.
    this.body = null;
    // The joint of the link.
    this.joint = joint;
 
};
/**
* An information of limit and motor.
* @author saharan
*/
OIMO.LimitMotor = function (axis, fixed) {
 
    fixed = fixed || false;
    // The axis of the constraint.
    this.axis = axis;
    // The current angle for rotational constraints.
    this.angle = 0;
    // The lower limit. Set lower > upper to disable
    this.lowerLimit = fixed ? 0 : 1;
 
    //if(fixed)this.lowerLimit = 0;
    //else this.lowerLimit = 1;
    //  The upper limit. Set lower > upper to disable.
    this.upperLimit = 0;
    // The target motor speed.
    this.motorSpeed = 0;
    // The maximum motor force or torque. Set 0 to disable.
    this.maxMotorForce = 0;
    // The frequency of the spring. Set 0 to disable.
    this.frequency = 0;
    // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
    this.dampingRatio = 0;
 
};
 
OIMO.LimitMotor.prototype = {
    constructor: OIMO.LimitMotor,
    /**
    * Set limit data into this constraint.
    * @param   lowerLimit
    * @param   upperLimit
    */
    setLimit: function (lowerLimit, upperLimit) {
 
        this.lowerLimit = lowerLimit;
        this.upperLimit = upperLimit;
 
    },
    /**
    * Set motor data into this constraint.
    * @param   motorSpeed
    * @param   maxMotorForce
    */
    setMotor: function (motorSpeed, maxMotorForce) {
 
        this.motorSpeed = motorSpeed;
        this.maxMotorForce = maxMotorForce;
 
    },
    /**
    * Set spring data into this constraint.
    * @param   frequency
    * @param   dampingRatio
    */
    setSpring: function (frequency, dampingRatio) {
 
        this.frequency = frequency;
        this.dampingRatio = dampingRatio;
 
    }
};
/**
 * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
 * @author saharan
 * @author lo-th
 */
 
OIMO.BallAndSocketJoint = function (config) {
 
    OIMO.Joint.call(this, config);
 
    this.type = OIMO.JOINT_BALL_AND_SOCKET;
 
    this.lc = new OIMO.LinearConstraint(this);
 
};
 
OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
 
OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
 
    this.updateAnchorPoints();
    this.lc.preSolve(timeStep, invTimeStep);
 
};
 
OIMO.BallAndSocketJoint.prototype.solve = function () {
 
    this.lc.solve();
 
};
 
OIMO.BallAndSocketJoint.prototype.postSolve = function () {
};
/**
 * A distance joint limits the distance between two anchor points on rigid bodies.
 * @author saharan
 * @author lo-th
 */
 
OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
 
    OIMO.Joint.call(this, config);
 
    this.type = OIMO.JOINT_DISTANCE;
 
    this.normal = new OIMO.Vec3();
    this.nr = new OIMO.Vec3();
 
    // The limit and motor information of the joint.
    this.limitMotor = new OIMO.LimitMotor(this.normal, true);
    this.limitMotor.lowerLimit = minDistance;
    this.limitMotor.upperLimit = maxDistance;
    this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
 
};
 
OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
 
 
OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
 
    this.updateAnchorPoints();
 
    //var nr = this.nr;
 
    this.nr.sub(this.anchorPoint2, this.anchorPoint1);
    //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
    //if(len>0) len = 1/len;
    //this.normal.scale( nr, len );
 
    this.normal.normalize(this.nr);
 
    this.t.preSolve(timeStep, invTimeStep);
 
};
 
OIMO.DistanceJoint.prototype.solve = function () {
 
    this.t.solve();
 
};
 
OIMO.DistanceJoint.prototype.postSolve = function () {
};
/**
 * A hinge joint allows only for relative rotation of rigid bodies along the axis.
 * @author saharan
 * @author lo-th
 */
 
OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
 
    OIMO.Joint.call(this, config);
 
    this.type = OIMO.JOINT_HINGE;
 
    // The axis in the first body's coordinate system.
    this.localAxis1 = config.localAxis1.clone().norm();
    // The axis in the second body's coordinate system.
    this.localAxis2 = config.localAxis2.clone().norm();
 
    // make angle axis 1
    this.localAngle1 = new OIMO.Vec3(
        this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
        -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
        this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
    ).norm();
 
    // make angle axis 2
    var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
    this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
 
    this.nor = new OIMO.Vec3();
    this.tan = new OIMO.Vec3();
    this.bin = new OIMO.Vec3();
 
    this.ax1 = new OIMO.Vec3();
    this.ax2 = new OIMO.Vec3();
    this.an1 = new OIMO.Vec3();
    this.an2 = new OIMO.Vec3();
 
    // The rotational limit and motor information of the joint.
    this.limitMotor = new OIMO.LimitMotor(this.nor, false);
    this.limitMotor.lowerLimit = lowerAngleLimit;
    this.limitMotor.upperLimit = upperAngleLimit;
 
    this.lc = new OIMO.LinearConstraint(this);
    this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
};
 
OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
 
 
OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
 
    var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
 
    this.updateAnchorPoints();
 
    this.ax1.mulMat(this.body1.rotation, this.localAxis1);
    this.ax2.mulMat(this.body2.rotation, this.localAxis2);
 
    this.an1.mulMat(this.body1.rotation, this.localAngle1);
    this.an2.mulMat(this.body2.rotation, this.localAngle2);
 
    this.nor.set(
        this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
        this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
        this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
    ).norm();
 
    this.tan.set(
        this.nor.y * this.nor.x - this.nor.z * this.nor.z,
        -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
        this.nor.x * this.nor.z + this.nor.y * this.nor.y
    ).norm();
 
    this.bin.set(
        this.nor.y * this.tan.z - this.nor.z * this.tan.y,
        this.nor.z * this.tan.x - this.nor.x * this.tan.z,
        this.nor.x * this.tan.y - this.nor.y * this.tan.x
    );
 
    // calculate hinge angle
 
    limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
 
    if (
        this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
        this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
        this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
    ) {
        this.limitMotor.angle = -limite;
    } else {
        this.limitMotor.angle = limite;
    }
 
    tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
    tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
    tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
 
    this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
    this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
 
    this.r3.preSolve(timeStep, invTimeStep);
    this.lc.preSolve(timeStep, invTimeStep);
 
};
 
OIMO.HingeJoint.prototype.solve = function () {
 
    this.r3.solve();
    this.lc.solve();
 
};
 
OIMO.HingeJoint.prototype.postSolve = function () {
};
 
OIMO.HingeJoint.prototype.acosClamp = function (cos) {
 
    if (cos > 1) return 0;
    else if (cos < -1) return OIMO.PI;
    else return OIMO.acos(cos);
 
};
/**
 * A prismatic joint allows only for relative translation of rigid bodies along the axis.
 * @author saharan
 * @author lo-th
 */
 
OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
 
    OIMO.Joint.call(this, config);
 
    this.type = OIMO.JOINT_PRISMATIC;
 
    // The axis in the first body's coordinate system.
    this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
    // The axis in the second body's coordinate system.
    this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
    this.localAxis1X = this.localAxis1.x;
    this.localAxis1Y = this.localAxis1.y;
    this.localAxis1Z = this.localAxis1.z;
    this.localAxis2X = this.localAxis2.x;
    this.localAxis2Y = this.localAxis2.y;
    this.localAxis2Z = this.localAxis2.z;
 
    this.nor = new OIMO.Vec3();
    this.tan = new OIMO.Vec3();
    this.bin = new OIMO.Vec3();
    this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
    // The translational limit and motor information of the joint.
    this.limitMotor = new OIMO.LimitMotor(this.nor, true);
    this.limitMotor.lowerLimit = lowerTranslation;
    this.limitMotor.upperLimit = upperTranslation;
    this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
 
};
 
OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
 
OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
 
    var tmpM;
    var tmp1X;
    var tmp1Y;
    var tmp1Z;
    this.updateAnchorPoints();
 
    tmpM = this.body1.rotation.elements;
    var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
    var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
    var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
    tmpM = this.body2.rotation.elements;
    var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
    var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
    var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
 
    var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
    var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
    var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
    tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
    if (tmp1X > 0) tmp1X = 1 / tmp1X;
    nx *= tmp1X;
    ny *= tmp1X;
    nz *= tmp1X;
    var tx = ny * nx - nz * nz;
    var ty = -nz * ny - nx * nx;
    var tz = nx * nz + ny * ny;
    tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
    tx *= tmp1X;
    ty *= tmp1X;
    tz *= tmp1X;
    var bx = ny * tz - nz * ty;
    var by = nz * tx - nx * tz;
    var bz = nx * ty - ny * tx;
 
    this.nor.init(nx, ny, nz);
    this.tan.init(tx, ty, tz);
    this.bin.init(bx, by, bz);
 
    this.ac.preSolve(timeStep, invTimeStep);
    this.t3.preSolve(timeStep, invTimeStep);
 
};
 
OIMO.PrismaticJoint.prototype.solve = function () {
 
    this.ac.solve();
    this.t3.solve();
 
};
 
OIMO.PrismaticJoint.prototype.postSolve = function () {
};
/**
 * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
 * @author saharan
 * @author lo-th
 */
 
OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
 
    OIMO.Joint.call(this, config);
 
    this.type = OIMO.JOINT_SLIDER;
 
    // The first axis in local coordinate system.
    this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
    // The second axis in local coordinate system.
    this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
 
    var len;
    this.localAxis1X = this.localAxis1.x;
    this.localAxis1Y = this.localAxis1.y;
    this.localAxis1Z = this.localAxis1.z;
 
    this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
    this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
    this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
 
    len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
    this.localAngAxis1X *= len;
    this.localAngAxis1Y *= len;
    this.localAngAxis1Z *= len;
 
    this.localAxis2X = this.localAxis2.x;
    this.localAxis2Y = this.localAxis2.y;
    this.localAxis2Z = this.localAxis2.z;
 
    // make angle axis 2
    var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
    var tarc = arc.elements;
    this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
    this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
    this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
 
    this.nor = new OIMO.Vec3();
    this.tan = new OIMO.Vec3();
    this.bin = new OIMO.Vec3();
    // The limit and motor for the rotation
    this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
    this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
    // The limit and motor for the translation.
    this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
    this.translationalLimitMotor.lowerLimit = lowerTranslation;
    this.translationalLimitMotor.upperLimit = upperTranslation;
    this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
 
};
 
OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
 
OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
 
    var tmpM;
    var tmp1X;
    var tmp1Y;
    var tmp1Z;
    this.updateAnchorPoints();
 
    tmpM = this.body1.rotation.elements;
    var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
    var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
    var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
    var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
    var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
    var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
    tmpM = this.body2.rotation.elements;
    var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
    var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
    var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
    var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
    var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
    var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
 
    var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
    var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
    var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
    tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
    if (tmp1X > 0) tmp1X = 1 / tmp1X;
    nx *= tmp1X;
    ny *= tmp1X;
    nz *= tmp1X;
    var tx = ny * nx - nz * nz;
    var ty = -nz * ny - nx * nx;
    var tz = nx * nz + ny * ny;
    tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
    tx *= tmp1X;
    ty *= tmp1X;
    tz *= tmp1X;
    var bx = ny * tz - nz * ty;
    var by = nz * tx - nx * tz;
    var bz = nx * ty - ny * tx;
    this.nor.init(nx, ny, nz);
    this.tan.init(tx, ty, tz);
    this.bin.init(bx, by, bz);
 
    // ----------------------------------------------
    //            calculate hinge angle
    // ----------------------------------------------
 
    if (
        nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
        ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
        nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
        ) {
        this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
    } else {
        this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
    }
 
    // angular error
    tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
    tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
    tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
 
    this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
    this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
 
    this.r3.preSolve(timeStep, invTimeStep);
    this.t3.preSolve(timeStep, invTimeStep);
};
 
OIMO.SliderJoint.prototype.solve = function () {
 
    this.r3.solve();
    this.t3.solve();
 
};
 
OIMO.SliderJoint.prototype.postSolve = function () {
};
 
OIMO.SliderJoint.prototype.acosClamp = function (cos) {
 
    if (cos > 1) return 0;
    else if (cos < -1) return OIMO.PI;
    else return OIMO.acos(cos);
 
};
/**
 * A wheel joint allows for relative rotation between two rigid bodies along two axes.
 * The wheel joint also allows for relative translation for the suspension.
 * @author saharan
 * @author lo-th
 */
 
OIMO.WheelJoint = function (config) {
 
    OIMO.Joint.call(this, config);
 
    this.type = OIMO.JOINT_WHEEL;
 
    // The first axis in local coordinate system.
    this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
    // The second axis in local coordinate system.
    this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
 
    var len;
    this.localAxis1X = this.localAxis1.x;
    this.localAxis1Y = this.localAxis1.y;
    this.localAxis1Z = this.localAxis1.z;
    this.localAxis2X = this.localAxis2.x;
    this.localAxis2Y = this.localAxis2.y;
    this.localAxis2Z = this.localAxis2.z;
    var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
    if (dot > -1 && dot < 1) {
        this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
        this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
        this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
        this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
        this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
        this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
        len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
        this.localAngAxis1X *= len;
        this.localAngAxis1Y *= len;
        this.localAngAxis1Z *= len;
        len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
        this.localAngAxis2X *= len;
        this.localAngAxis2Y *= len;
        this.localAngAxis2Z *= len;
    } else {
        this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
        this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
        this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
        len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
        this.localAngAxis1X *= len;
        this.localAngAxis1Y *= len;
        this.localAngAxis1Z *= len;
        var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
        var tarc = arc.elements;
        this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
        this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
        this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
    }
 
    this.nor = new OIMO.Vec3();
    this.tan = new OIMO.Vec3();
    this.bin = new OIMO.Vec3();
 
    // The translational limit and motor information of the joint.
    this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
    this.translationalLimitMotor.frequency = 8;
    this.translationalLimitMotor.dampingRatio = 1;
    // The first rotational limit and motor information of the joint.
    this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
    // The second rotational limit and motor information of the joint.
    this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
 
    this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
    this.t3.weight = 1;
    this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
 
};
 
OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
 
OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
 
    var tmpM;
    var tmp1X;
    var tmp1Y;
    var tmp1Z;
    this.updateAnchorPoints();
    tmpM = this.body1.rotation.elements;
    var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
    var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
    var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
    var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
    var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
    var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
    tmpM = this.body2.rotation.elements;
    var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
    var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
    var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
    var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
    var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
    var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
 
    this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
    if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
        this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
    } else {
        this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
    }
    if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
        this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
    } else {
        this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
    }
 
    var nx = y2 * z1 - z2 * y1;
    var ny = z2 * x1 - x2 * z1;
    var nz = x2 * y1 - y2 * x1;
 
    tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
    if (tmp1X > 0) tmp1X = 1 / tmp1X;
    nx *= tmp1X;
    ny *= tmp1X;
    nz *= tmp1X;
 
    var tx = ny * z2 - nz * y2;
    var ty = nz * x2 - nx * z2;
    var tz = nx * y2 - ny * x2;
 
    tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
    if (tmp1X > 0) tmp1X = 1 / tmp1X;
    tx *= tmp1X;
    ty *= tmp1X;
    tz *= tmp1X;
 
    var bx = y1 * nz - z1 * ny;
    var by = z1 * nx - x1 * nz;
    var bz = x1 * ny - y1 * nx;
 
    tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
    if (tmp1X > 0) tmp1X = 1 / tmp1X;
    bx *= tmp1X;
    by *= tmp1X;
    bz *= tmp1X;
 
    this.nor.init(nx, ny, nz);
    this.tan.init(tx, ty, tz);
    this.bin.init(bx, by, bz);
 
    this.r3.preSolve(timeStep, invTimeStep);
    this.t3.preSolve(timeStep, invTimeStep);
 
};
 
OIMO.WheelJoint.prototype.solve = function () {
 
    this.r3.solve();
    this.t3.solve();
 
};
 
OIMO.WheelJoint.prototype.postSolve = function () {
};
 
OIMO.WheelJoint.prototype.acosClamp = function (cos) {
 
    if (cos > 1) return 0;
    else if (cos < -1) return OIMO.PI;
    else return OIMO.acos(cos);
 
};
/**
* An angular constraint for all axes for various joints.
* @author saharan
*/
 
OIMO.AngularConstraint = function (joint, targetOrientation) {
 
    this.joint = joint;
 
    this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
 
    this.relativeOrientation = new OIMO.Quat();
 
    this.ii1 = null;
    this.ii2 = null;
    this.dd = null;
 
    this.vel = new OIMO.Vec3();
    this.imp = new OIMO.Vec3();
 
    this.rn0 = new OIMO.Vec3();
    this.rn1 = new OIMO.Vec3();
    this.rn2 = new OIMO.Vec3();
 
    this.b1 = joint.body1;
    this.b2 = joint.body2;
    this.a1 = this.b1.angularVelocity;
    this.a2 = this.b2.angularVelocity;
    this.i1 = this.b1.inverseInertia;
    this.i2 = this.b2.inverseInertia;
 
};
 
OIMO.AngularConstraint.prototype = {
 
    constructor: OIMO.AngularConstraint,
 
    preSolve: function (timeStep, invTimeStep) {
 
        var inv, len, v, vv;
 
        this.ii1 = this.i1.clone();
        this.ii2 = this.i2.clone();
 
        v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
        inv = 1 / (v[0] * (v[4] * v[8] - v[7] * v[5]) + v[3] * (v[7] * v[2] - v[1] * v[8]) + v[6] * (v[1] * v[5] - v[4] * v[2]));
        this.dd = new OIMO.Mat33(
            v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
            v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
            v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
        ).multiply(inv);
 
        this.relativeOrientation.invert(this.b1.orientation);
        this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
        this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
        inv = this.relativeOrientation.s * 2;
 
        this.vel.scale(this.relativeOrientation, inv);
 
        len = this.vel.length();
 
        if (len > 0.02) {
            len = (0.02 - len) / len * invTimeStep * 0.05;
            this.vel.scaleEqual(len);
        } else {
            this.vel.init();
        }
 
        this.rn1.mulMat(this.ii1, this.imp);
        this.rn2.mulMat(this.ii2, this.imp);
 
        this.a1.addEqual(this.rn1);
        this.a2.subEqual(this.rn2);
 
    },
 
    solve: function () {
 
        var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
        this.rn0.mulMat(this.dd, r);
        this.rn1.mulMat(this.ii1, this.rn0);
        this.rn2.mulMat(this.ii2, this.rn0);
        this.imp.addEqual(this.rn0);
        this.a1.addEqual(this.rn1);
        this.a2.subEqual(this.rn2);
 
    }
 
};
/**
* A linear constraint for all axes for various joints.
* @author saharan
*/
OIMO.LinearConstraint = function (joint) {
    this.m1 = NaN;
    this.m2 = NaN;
 
    this.ii1 = null;
    this.ii2 = null;
    this.dd = null;
 
    this.r1x = NaN;
    this.r1y = NaN;
    this.r1z = NaN;
 
    this.r2x = NaN;
    this.r2y = NaN;
    this.r2z = NaN;
 
    this.ax1x = NaN;
    this.ax1y = NaN;
    this.ax1z = NaN;
    this.ay1x = NaN;
    this.ay1y = NaN;
    this.ay1z = NaN;
    this.az1x = NaN;
    this.az1y = NaN;
    this.az1z = NaN;
 
    this.ax2x = NaN;
    this.ax2y = NaN;
    this.ax2z = NaN;
    this.ay2x = NaN;
    this.ay2y = NaN;
    this.ay2z = NaN;
    this.az2x = NaN;
    this.az2y = NaN;
    this.az2z = NaN;
 
    this.vel = NaN;
    this.velx = NaN;
    this.vely = NaN;
    this.velz = NaN;
 
 
    this.joint = joint;
    this.r1 = joint.relativeAnchorPoint1;
    this.r2 = joint.relativeAnchorPoint2;
    this.p1 = joint.anchorPoint1;
    this.p2 = joint.anchorPoint2;
    this.b1 = joint.body1;
    this.b2 = joint.body2;
    this.l1 = this.b1.linearVelocity;
    this.l2 = this.b2.linearVelocity;
    this.a1 = this.b1.angularVelocity;
    this.a2 = this.b2.angularVelocity;
    this.i1 = this.b1.inverseInertia;
    this.i2 = this.b2.inverseInertia;
    this.impx = 0;
    this.impy = 0;
    this.impz = 0;
}
 
OIMO.LinearConstraint.prototype = {
    constructor: OIMO.LinearConstraint,
 
    preSolve: function (timeStep, invTimeStep) {
        this.r1x = this.r1.x;
        this.r1y = this.r1.y;
        this.r1z = this.r1.z;
 
        this.r2x = this.r2.x;
        this.r2y = this.r2.y;
        this.r2z = this.r2.z;
 
        this.m1 = this.b1.inverseMass;
        this.m2 = this.b2.inverseMass;
 
        this.ii1 = this.i1.clone();
        this.ii2 = this.i2.clone();
 
        var ii1 = this.ii1.elements;
        var ii2 = this.ii2.elements;
 
        this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
        this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
        this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
        this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
        this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
        this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
        this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
        this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
        this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
        this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
        this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
        this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
        this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
        this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
        this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
        this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
        this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
        this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
 
        // calculate point-to-point mass matrix
        // from impulse equation
        // 
        // M = ([/m] - [r^][/I][r^]) ^ -1
        // 
        // where
        // 
        // [/m] = |1/m, 0, 0|
        //        |0, 1/m, 0|
        //        |0, 0, 1/m|
        // 
        // [r^] = |0, -rz, ry|
        //        |rz, 0, -rx|
        //        |-ry, rx, 0|
        // 
        // [/I] = Inverted moment inertia
 
        var rxx = this.m1 + this.m2;
 
        var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
        var k = kk.elements;
 
        k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
        k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
        k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
        k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
        k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
        k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
        k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
        k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
        k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
 
        k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
        k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
        k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
        k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
        k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
        k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
        k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
        k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
        k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
 
        var inv = 1 / (k[0] * (k[4] * k[8] - k[7] * k[5]) + k[3] * (k[7] * k[2] - k[1] * k[8]) + k[6] * (k[1] * k[5] - k[4] * k[2]));
        this.dd = new OIMO.Mat33(
            k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
            k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
            k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
        ).multiply(inv);
 
        this.velx = this.p2.x - this.p1.x;
        this.vely = this.p2.y - this.p1.y;
        this.velz = this.p2.z - this.p1.z;
        var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
        if (len > 0.005) {
            len = (0.005 - len) / len * invTimeStep * 0.05;
            this.velx *= len;
            this.vely *= len;
            this.velz *= len;
        } else {
            this.velx = 0;
            this.vely = 0;
            this.velz = 0;
        }
 
        this.impx *= 0.95;
        this.impy *= 0.95;
        this.impz *= 0.95;
 
        this.l1.x += this.impx * this.m1;
        this.l1.y += this.impy * this.m1;
        this.l1.z += this.impz * this.m1;
        this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
        this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
        this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
        this.l2.x -= this.impx * this.m2;
        this.l2.y -= this.impy * this.m2;
        this.l2.z -= this.impz * this.m2;
        this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
        this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
        this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
    },
    solve: function () {
        var d = this.dd.elements;
        var rvx = this.l2.x - this.l1.x + this.a2.y * this.r2z - this.a2.z * this.r2y - this.a1.y * this.r1z + this.a1.z * this.r1y - this.velx;
        var rvy = this.l2.y - this.l1.y + this.a2.z * this.r2x - this.a2.x * this.r2z - this.a1.z * this.r1x + this.a1.x * this.r1z - this.vely;
        var rvz = this.l2.z - this.l1.z + this.a2.x * this.r2y - this.a2.y * this.r2x - this.a1.x * this.r1y + this.a1.y * this.r1x - this.velz;
        var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
        var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
        var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
        this.impx += nimpx;
        this.impy += nimpy;
        this.impz += nimpz;
        this.l1.x += nimpx * this.m1;
        this.l1.y += nimpy * this.m1;
        this.l1.z += nimpz * this.m1;
        this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
        this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
        this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
        this.l2.x -= nimpx * this.m2;
        this.l2.y -= nimpy * this.m2;
        this.l2.z -= nimpz * this.m2;
        this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
        this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
        this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
    }
}
/**
* A three-axis rotational constraint for various joints.
* @author saharan
*/
OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
    this.cfm1 = NaN;
    this.cfm2 = NaN;
    this.cfm3 = NaN;
    this.i1e00 = NaN;
    this.i1e01 = NaN;
    this.i1e02 = NaN;
    this.i1e10 = NaN;
    this.i1e11 = NaN;
    this.i1e12 = NaN;
    this.i1e20 = NaN;
    this.i1e21 = NaN;
    this.i1e22 = NaN;
    this.i2e00 = NaN;
    this.i2e01 = NaN;
    this.i2e02 = NaN;
    this.i2e10 = NaN;
    this.i2e11 = NaN;
    this.i2e12 = NaN;
    this.i2e20 = NaN;
    this.i2e21 = NaN;
    this.i2e22 = NaN;
    this.ax1 = NaN;
    this.ay1 = NaN;
    this.az1 = NaN;
    this.ax2 = NaN;
    this.ay2 = NaN;
    this.az2 = NaN;
    this.ax3 = NaN;
    this.ay3 = NaN;
    this.az3 = NaN;
 
    this.a1x1 = NaN; // jacoians
    this.a1y1 = NaN;
    this.a1z1 = NaN;
    this.a2x1 = NaN;
    this.a2y1 = NaN;
    this.a2z1 = NaN;
    this.a1x2 = NaN;
    this.a1y2 = NaN;
    this.a1z2 = NaN;
    this.a2x2 = NaN;
    this.a2y2 = NaN;
    this.a2z2 = NaN;
    this.a1x3 = NaN;
    this.a1y3 = NaN;
    this.a1z3 = NaN;
    this.a2x3 = NaN;
    this.a2y3 = NaN;
    this.a2z3 = NaN;
 
    this.lowerLimit1 = NaN;
    this.upperLimit1 = NaN;
    this.limitVelocity1 = NaN;
    this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
    this.enableMotor1 = false;
    this.motorSpeed1 = NaN;
    this.maxMotorForce1 = NaN;
    this.maxMotorImpulse1 = NaN;
    this.lowerLimit2 = NaN;
    this.upperLimit2 = NaN;
    this.limitVelocity2 = NaN;
    this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
    this.enableMotor2 = false;
    this.motorSpeed2 = NaN;
    this.maxMotorForce2 = NaN;
    this.maxMotorImpulse2 = NaN;
    this.lowerLimit3 = NaN;
    this.upperLimit3 = NaN;
    this.limitVelocity3 = NaN;
    this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
    this.enableMotor3 = false;
    this.motorSpeed3 = NaN;
    this.maxMotorForce3 = NaN;
    this.maxMotorImpulse3 = NaN;
 
    this.k00 = NaN; // K = J*M*JT
    this.k01 = NaN;
    this.k02 = NaN;
    this.k10 = NaN;
    this.k11 = NaN;
    this.k12 = NaN;
    this.k20 = NaN;
    this.k21 = NaN;
    this.k22 = NaN;
 
    this.kv00 = NaN; // diagonals without CFMs
    this.kv11 = NaN;
    this.kv22 = NaN;
 
    this.dv00 = NaN; // ...inverted
    this.dv11 = NaN;
    this.dv22 = NaN;
 
    this.d00 = NaN;  // K^-1
    this.d01 = NaN;
    this.d02 = NaN;
    this.d10 = NaN;
    this.d11 = NaN;
    this.d12 = NaN;
    this.d20 = NaN;
    this.d21 = NaN;
    this.d22 = NaN;
 
    this.limitMotor1 = limitMotor1;
    this.limitMotor2 = limitMotor2;
    this.limitMotor3 = limitMotor3;
    this.b1 = joint.body1;
    this.b2 = joint.body2;
    this.a1 = this.b1.angularVelocity;
    this.a2 = this.b2.angularVelocity;
    this.i1 = this.b1.inverseInertia;
    this.i2 = this.b2.inverseInertia;
    this.limitImpulse1 = 0;
    this.motorImpulse1 = 0;
    this.limitImpulse2 = 0;
    this.motorImpulse2 = 0;
    this.limitImpulse3 = 0;
    this.motorImpulse3 = 0;
}
OIMO.Rotational3Constraint.prototype = {
    constructor: OIMO.Rotational3Constraint,
 
    preSolve: function (timeStep, invTimeStep) {
        this.ax1 = this.limitMotor1.axis.x;
        this.ay1 = this.limitMotor1.axis.y;
        this.az1 = this.limitMotor1.axis.z;
        this.ax2 = this.limitMotor2.axis.x;
        this.ay2 = this.limitMotor2.axis.y;
        this.az2 = this.limitMotor2.axis.z;
        this.ax3 = this.limitMotor3.axis.x;
        this.ay3 = this.limitMotor3.axis.y;
        this.az3 = this.limitMotor3.axis.z;
        this.lowerLimit1 = this.limitMotor1.lowerLimit;
        this.upperLimit1 = this.limitMotor1.upperLimit;
        this.motorSpeed1 = this.limitMotor1.motorSpeed;
        this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
        this.enableMotor1 = this.maxMotorForce1 > 0;
        this.lowerLimit2 = this.limitMotor2.lowerLimit;
        this.upperLimit2 = this.limitMotor2.upperLimit;
        this.motorSpeed2 = this.limitMotor2.motorSpeed;
        this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
        this.enableMotor2 = this.maxMotorForce2 > 0;
        this.lowerLimit3 = this.limitMotor3.lowerLimit;
        this.upperLimit3 = this.limitMotor3.upperLimit;
        this.motorSpeed3 = this.limitMotor3.motorSpeed;
        this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
        this.enableMotor3 = this.maxMotorForce3 > 0;
 
        var ti1 = this.i1.elements;
        var ti2 = this.i2.elements;
        this.i1e00 = ti1[0];
        this.i1e01 = ti1[1];
        this.i1e02 = ti1[2];
        this.i1e10 = ti1[3];
        this.i1e11 = ti1[4];
        this.i1e12 = ti1[5];
        this.i1e20 = ti1[6];
        this.i1e21 = ti1[7];
        this.i1e22 = ti1[8];
 
        this.i2e00 = ti2[0];
        this.i2e01 = ti2[1];
        this.i2e02 = ti2[2];
        this.i2e10 = ti2[3];
        this.i2e11 = ti2[4];
        this.i2e12 = ti2[5];
        this.i2e20 = ti2[6];
        this.i2e21 = ti2[7];
        this.i2e22 = ti2[8];
 
        var frequency1 = this.limitMotor1.frequency;
        var frequency2 = this.limitMotor2.frequency;
        var frequency3 = this.limitMotor3.frequency;
        var enableSpring1 = frequency1 > 0;
        var enableSpring2 = frequency2 > 0;
        var enableSpring3 = frequency3 > 0;
        var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
        var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
        var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
        var angle1 = this.limitMotor1.angle;
        if (enableLimit1) {
            if (this.lowerLimit1 == this.upperLimit1) {
                if (this.limitState1 != 0) {
                    this.limitState1 = 0;
                    this.limitImpulse1 = 0;
                }
                this.limitVelocity1 = this.lowerLimit1 - angle1;
            } else if (angle1 < this.lowerLimit1) {
                if (this.limitState1 != -1) {
                    this.limitState1 = -1;
                    this.limitImpulse1 = 0;
                }
                this.limitVelocity1 = this.lowerLimit1 - angle1;
            } else if (angle1 > this.upperLimit1) {
                if (this.limitState1 != 1) {
                    this.limitState1 = 1;
                    this.limitImpulse1 = 0;
                }
                this.limitVelocity1 = this.upperLimit1 - angle1;
            } else {
                this.limitState1 = 2;
                this.limitImpulse1 = 0;
                this.limitVelocity1 = 0;
            }
            if (!enableSpring1) {
                if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
                else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
                else this.limitVelocity1 = 0;
            }
        } else {
            this.limitState1 = 2;
            this.limitImpulse1 = 0;
        }
 
        var angle2 = this.limitMotor2.angle;
        if (enableLimit2) {
            if (this.lowerLimit2 == this.upperLimit2) {
                if (this.limitState2 != 0) {
                    this.limitState2 = 0;
                    this.limitImpulse2 = 0;
                }
                this.limitVelocity2 = this.lowerLimit2 - angle2;
            } else if (angle2 < this.lowerLimit2) {
                if (this.limitState2 != -1) {
                    this.limitState2 = -1;
                    this.limitImpulse2 = 0;
                }
                this.limitVelocity2 = this.lowerLimit2 - angle2;
            } else if (angle2 > this.upperLimit2) {
                if (this.limitState2 != 1) {
                    this.limitState2 = 1;
                    this.limitImpulse2 = 0;
                }
                this.limitVelocity2 = this.upperLimit2 - angle2;
            } else {
                this.limitState2 = 2;
                this.limitImpulse2 = 0;
                this.limitVelocity2 = 0;
            }
            if (!enableSpring2) {
                if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
                else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
                else this.limitVelocity2 = 0;
            }
        } else {
            this.limitState2 = 2;
            this.limitImpulse2 = 0;
        }
 
        var angle3 = this.limitMotor3.angle;
        if (enableLimit3) {
            if (this.lowerLimit3 == this.upperLimit3) {
                if (this.limitState3 != 0) {
                    this.limitState3 = 0;
                    this.limitImpulse3 = 0;
                }
                this.limitVelocity3 = this.lowerLimit3 - angle3;
            } else if (angle3 < this.lowerLimit3) {
                if (this.limitState3 != -1) {
                    this.limitState3 = -1;
                    this.limitImpulse3 = 0;
                }
                this.limitVelocity3 = this.lowerLimit3 - angle3;
            } else if (angle3 > this.upperLimit3) {
                if (this.limitState3 != 1) {
                    this.limitState3 = 1;
                    this.limitImpulse3 = 0;
                }
                this.limitVelocity3 = this.upperLimit3 - angle3;
            } else {
                this.limitState3 = 2;
                this.limitImpulse3 = 0;
                this.limitVelocity3 = 0;
            }
            if (!enableSpring3) {
                if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
                else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
                else this.limitVelocity3 = 0;
            }
        } else {
            this.limitState3 = 2;
            this.limitImpulse3 = 0;
        }
 
        if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
            this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
        } else {
            this.motorImpulse1 = 0;
            this.maxMotorImpulse1 = 0;
        }
        if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
            this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
        } else {
            this.motorImpulse2 = 0;
            this.maxMotorImpulse2 = 0;
        }
        if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
            this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
        } else {
            this.motorImpulse3 = 0;
            this.maxMotorImpulse3 = 0;
        }
 
        // build jacobians
        this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
        this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
        this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
        this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
        this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
        this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
 
        this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
        this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
        this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
        this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
        this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
        this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
 
        this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
        this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
        this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
        this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
        this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
        this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
 
        // build an impulse matrix
        this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
        this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
        this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
        this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
        this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
        this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
        this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
        this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
        this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
 
        this.kv00 = this.k00;
        this.kv11 = this.k11;
        this.kv22 = this.k22;
        this.dv00 = 1 / this.kv00;
        this.dv11 = 1 / this.kv11;
        this.dv22 = 1 / this.kv22;
 
        if (enableSpring1 && this.limitState1 != 2) {
            var omega = 6.2831853 * frequency1;
            var k = omega * omega * timeStep;
            var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
            this.cfm1 = this.kv00 * dmp;
            this.limitVelocity1 *= k * dmp;
        } else {
            this.cfm1 = 0;
            this.limitVelocity1 *= invTimeStep * 0.05;
        }
 
        if (enableSpring2 && this.limitState2 != 2) {
            omega = 6.2831853 * frequency2;
            k = omega * omega * timeStep;
            dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
            this.cfm2 = this.kv11 * dmp;
            this.limitVelocity2 *= k * dmp;
        } else {
            this.cfm2 = 0;
            this.limitVelocity2 *= invTimeStep * 0.05;
        }
 
        if (enableSpring3 && this.limitState3 != 2) {
            omega = 6.2831853 * frequency3;
            k = omega * omega * timeStep;
            dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
            this.cfm3 = this.kv22 * dmp;
            this.limitVelocity3 *= k * dmp;
        } else {
            this.cfm3 = 0;
            this.limitVelocity3 *= invTimeStep * 0.05;
        }
 
        this.k00 += this.cfm1;
        this.k11 += this.cfm2;
        this.k22 += this.cfm3;
 
        var inv = 1 / (
        this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
        this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
        this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
        );
        this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
        this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
        this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
        this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
        this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
        this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
        this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
        this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
        this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
 
        this.limitImpulse1 *= 0.95;
        this.motorImpulse1 *= 0.95;
        this.limitImpulse2 *= 0.95;
        this.motorImpulse2 *= 0.95;
        this.limitImpulse3 *= 0.95;
        this.motorImpulse3 *= 0.95;
        var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
        var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
        var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
        this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
        this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
        this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
        this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
        this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
        this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
    },
    solve_: function () {
        var rvx = this.a2.x - this.a1.x;
        var rvy = this.a2.y - this.a1.y;
        var rvz = this.a2.z - this.a1.z;
 
        this.limitVelocity3 = 30;
        var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
        var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
        var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
 
        var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
        var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
        var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
 
        this.limitImpulse1 += dLimitImpulse1;
        this.limitImpulse2 += dLimitImpulse2;
        this.limitImpulse3 += dLimitImpulse3;
 
        this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
        this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
        this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
        this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
        this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
        this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
    },
    solve: function () {
        var rvx = this.a2.x - this.a1.x;
        var rvy = this.a2.y - this.a1.y;
        var rvz = this.a2.z - this.a1.z;
 
        var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
        var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
        var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
 
        var oldMotorImpulse1 = this.motorImpulse1;
        var oldMotorImpulse2 = this.motorImpulse2;
        var oldMotorImpulse3 = this.motorImpulse3;
 
        var dMotorImpulse1 = 0;
        var dMotorImpulse2 = 0;
        var dMotorImpulse3 = 0;
 
        if (this.enableMotor1) {
            dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
            this.motorImpulse1 += dMotorImpulse1;
            if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
                this.motorImpulse1 = this.maxMotorImpulse1;
            } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
                this.motorImpulse1 = -this.maxMotorImpulse1;
            }
            dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
        }
        if (this.enableMotor2) {
            dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
            this.motorImpulse2 += dMotorImpulse2;
            if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
                this.motorImpulse2 = this.maxMotorImpulse2;
            } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
                this.motorImpulse2 = -this.maxMotorImpulse2;
            }
            dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
        }
        if (this.enableMotor3) {
            dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
            this.motorImpulse3 += dMotorImpulse3;
            if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
                this.motorImpulse3 = this.maxMotorImpulse3;
            } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
                this.motorImpulse3 = -this.maxMotorImpulse3;
            }
            dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
        }
 
        // apply motor impulse to relative velocity
        rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
        rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
        rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
 
        // subtract target velocity and applied impulse
        rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
        rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
        rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
 
        var oldLimitImpulse1 = this.limitImpulse1;
        var oldLimitImpulse2 = this.limitImpulse2;
        var oldLimitImpulse3 = this.limitImpulse3;
 
        var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
        var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
        var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
 
        this.limitImpulse1 += dLimitImpulse1;
        this.limitImpulse2 += dLimitImpulse2;
        this.limitImpulse3 += dLimitImpulse3;
 
        // clamp
        var clampState = 0;
        if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
            dLimitImpulse1 = -oldLimitImpulse1;
            rvn2 += dLimitImpulse1 * this.k10;
            rvn3 += dLimitImpulse1 * this.k20;
            clampState |= 1;
        }
        if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
            dLimitImpulse2 = -oldLimitImpulse2;
            rvn1 += dLimitImpulse2 * this.k01;
            rvn3 += dLimitImpulse2 * this.k21;
            clampState |= 2;
        }
        if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
            dLimitImpulse3 = -oldLimitImpulse3;
            rvn1 += dLimitImpulse3 * this.k02;
            rvn2 += dLimitImpulse3 * this.k12;
            clampState |= 4;
        }
 
        // update un-clamped impulse
        // TODO: isolate division
        var det;
        switch (clampState) {
            case 1: // update 2 3
                det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
                dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
                dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
                break;
            case 2: // update 1 3
                det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
                dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
                dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
                break;
            case 3: // update 3
                dLimitImpulse3 = rvn3 / this.k22;
                break;
            case 4: // update 1 2
                det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
                dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
                dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
                break;
            case 5: // update 2
                dLimitImpulse2 = rvn2 / this.k11;
                break;
            case 6: // update 1
                dLimitImpulse1 = rvn1 / this.k00;
                break;
        }
 
        this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
        this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
        this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
 
        var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
        var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
        var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
 
        // apply impulse
        this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
        this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
        this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
        this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
        this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
        this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
        rvx = this.a2.x - this.a1.x;
        rvy = this.a2.y - this.a1.y;
        rvz = this.a2.z - this.a1.z;
 
        rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
    }
}
/**
* A rotational constraint for various joints.
* @author saharan
*/
OIMO.RotationalConstraint = function (joint, limitMotor) {
    this.cfm = NaN;
    this.i1e00 = NaN;
    this.i1e01 = NaN;
    this.i1e02 = NaN;
    this.i1e10 = NaN;
    this.i1e11 = NaN;
    this.i1e12 = NaN;
    this.i1e20 = NaN;
    this.i1e21 = NaN;
    this.i1e22 = NaN;
    this.i2e00 = NaN;
    this.i2e01 = NaN;
    this.i2e02 = NaN;
    this.i2e10 = NaN;
    this.i2e11 = NaN;
    this.i2e12 = NaN;
    this.i2e20 = NaN;
    this.i2e21 = NaN;
    this.i2e22 = NaN;
    this.motorDenom = NaN;
    this.invMotorDenom = NaN;
    this.invDenom = NaN;
    this.ax = NaN;
    this.ay = NaN;
    this.az = NaN;
    this.a1x = NaN;
    this.a1y = NaN;
    this.a1z = NaN;
    this.a2x = NaN;
    this.a2y = NaN;
    this.a2z = NaN;
    this.enableLimit = false;
    this.lowerLimit = NaN;
    this.upperLimit = NaN;
    this.limitVelocity = NaN;
    this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
    this.enableMotor = false;
    this.motorSpeed = NaN;
    this.maxMotorForce = NaN;
    this.maxMotorImpulse = NaN;
 
    this.limitMotor = limitMotor;
    this.b1 = joint.body1;
    this.b2 = joint.body2;
    this.a1 = this.b1.angularVelocity;
    this.a2 = this.b2.angularVelocity;
    this.i1 = this.b1.inverseInertia;
    this.i2 = this.b2.inverseInertia;
    this.limitImpulse = 0;
    this.motorImpulse = 0;
}
OIMO.RotationalConstraint.prototype = {
    constructor: OIMO.RotationalConstraint,
 
    preSolve: function (timeStep, invTimeStep) {
        this.ax = this.limitMotor.axis.x;
        this.ay = this.limitMotor.axis.y;
        this.az = this.limitMotor.axis.z;
        this.lowerLimit = this.limitMotor.lowerLimit;
        this.upperLimit = this.limitMotor.upperLimit;
        this.motorSpeed = this.limitMotor.motorSpeed;
        this.maxMotorForce = this.limitMotor.maxMotorForce;
        this.enableMotor = this.maxMotorForce > 0;
 
        var ti1 = this.i1.elements;
        var ti2 = this.i2.elements;
        this.i1e00 = ti1[0];
        this.i1e01 = ti1[1];
        this.i1e02 = ti1[2];
        this.i1e10 = ti1[3];
        this.i1e11 = ti1[4];
        this.i1e12 = ti1[5];
        this.i1e20 = ti1[6];
        this.i1e21 = ti1[7];
        this.i1e22 = ti1[8];
 
        this.i2e00 = ti2[0];
        this.i2e01 = ti2[1];
        this.i2e02 = ti2[2];
        this.i2e10 = ti2[3];
        this.i2e11 = ti2[4];
        this.i2e12 = ti2[5];
        this.i2e20 = ti2[6];
        this.i2e21 = ti2[7];
        this.i2e22 = ti2[8];
 
        var frequency = this.limitMotor.frequency;
        var enableSpring = frequency > 0;
        var enableLimit = this.lowerLimit <= this.upperLimit;
        var angle = this.limitMotor.angle;
        if (enableLimit) {
            if (this.lowerLimit == this.upperLimit) {
                if (this.limitState != 0) {
                    this.limitState = 0;
                    this.limitImpulse = 0;
                }
                this.limitVelocity = this.lowerLimit - angle;
            } else if (angle < this.lowerLimit) {
                if (this.limitState != -1) {
                    this.limitState = -1;
                    this.limitImpulse = 0;
                }
                this.limitVelocity = this.lowerLimit - angle;
            } else if (angle > this.upperLimit) {
                if (this.limitState != 1) {
                    this.limitState = 1;
                    this.limitImpulse = 0;
                }
                this.limitVelocity = this.upperLimit - angle;
            } else {
                this.limitState = 2;
                this.limitImpulse = 0;
                this.limitVelocity = 0;
            }
            if (!enableSpring) {
                if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
                else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
                else this.limitVelocity = 0;
            }
        } else {
            this.limitState = 2;
            this.limitImpulse = 0;
        }
        if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
            this.maxMotorImpulse = this.maxMotorForce * timeStep;
        } else {
            this.motorImpulse = 0;
            this.maxMotorImpulse = 0;
        }
 
        this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
        this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
        this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
        this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
        this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
        this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
        this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
        this.invMotorDenom = 1 / this.motorDenom;
 
        if (enableSpring && this.limitState != 2) {
            var omega = 6.2831853 * frequency;
            var k = omega * omega * timeStep;
            var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
            this.cfm = this.motorDenom * dmp;
            this.limitVelocity *= k * dmp;
        } else {
            this.cfm = 0;
            this.limitVelocity *= invTimeStep * 0.05;
        }
 
        this.invDenom = 1 / (this.motorDenom + this.cfm);
 
        this.limitImpulse *= 0.95;
        this.motorImpulse *= 0.95;
        var totalImpulse = this.limitImpulse + this.motorImpulse;
        this.a1.x += totalImpulse * this.a1x;
        this.a1.y += totalImpulse * this.a1y;
        this.a1.z += totalImpulse * this.a1z;
        this.a2.x -= totalImpulse * this.a2x;
        this.a2.y -= totalImpulse * this.a2y;
        this.a2.z -= totalImpulse * this.a2z;
    },
    solve: function () {
        var rvn = this.ax * (this.a2.x - this.a1.x) + this.ay * (this.a2.y - this.a1.y) + this.az * (this.a2.z - this.a1.z);
 
        // motor part
        var newMotorImpulse;
        if (this.enableMotor) {
            newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
            var oldMotorImpulse = this.motorImpulse;
            this.motorImpulse += newMotorImpulse;
            if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
            else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
            newMotorImpulse = this.motorImpulse - oldMotorImpulse;
            rvn -= newMotorImpulse * this.motorDenom;
        } else newMotorImpulse = 0;
 
        // limit part
        var newLimitImpulse;
        if (this.limitState != 2) {
            newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
            var oldLimitImpulse = this.limitImpulse;
            this.limitImpulse += newLimitImpulse;
            if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
            newLimitImpulse = this.limitImpulse - oldLimitImpulse;
        } else newLimitImpulse = 0;
 
        var totalImpulse = newLimitImpulse + newMotorImpulse;
        this.a1.x += totalImpulse * this.a1x;
        this.a1.y += totalImpulse * this.a1y;
        this.a1.z += totalImpulse * this.a1z;
        this.a2.x -= totalImpulse * this.a2x;
        this.a2.y -= totalImpulse * this.a2y;
        this.a2.z -= totalImpulse * this.a2z;
    }
}
/**
* A three-axis translational constraint for various joints.
* @author saharan
*/
OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
    this.m1 = NaN;
    this.m2 = NaN;
    this.i1e00 = NaN;
    this.i1e01 = NaN;
    this.i1e02 = NaN;
    this.i1e10 = NaN;
    this.i1e11 = NaN;
    this.i1e12 = NaN;
    this.i1e20 = NaN;
    this.i1e21 = NaN;
    this.i1e22 = NaN;
    this.i2e00 = NaN;
    this.i2e01 = NaN;
    this.i2e02 = NaN;
    this.i2e10 = NaN;
    this.i2e11 = NaN;
    this.i2e12 = NaN;
    this.i2e20 = NaN;
    this.i2e21 = NaN;
    this.i2e22 = NaN;
    this.ax1 = NaN;
    this.ay1 = NaN;
    this.az1 = NaN;
    this.ax2 = NaN;
    this.ay2 = NaN;
    this.az2 = NaN;
    this.ax3 = NaN;
    this.ay3 = NaN;
    this.az3 = NaN;
    this.r1x = NaN;
    this.r1y = NaN;
    this.r1z = NaN;
    this.r2x = NaN;
    this.r2y = NaN;
    this.r2z = NaN;
    this.t1x1 = NaN;// jacobians
    this.t1y1 = NaN;
    this.t1z1 = NaN;
    this.t2x1 = NaN;
    this.t2y1 = NaN;
    this.t2z1 = NaN;
    this.l1x1 = NaN;
    this.l1y1 = NaN;
    this.l1z1 = NaN;
    this.l2x1 = NaN;
    this.l2y1 = NaN;
    this.l2z1 = NaN;
    this.a1x1 = NaN;
    this.a1y1 = NaN;
    this.a1z1 = NaN;
    this.a2x1 = NaN;
    this.a2y1 = NaN;
    this.a2z1 = NaN;
    this.t1x2 = NaN;
    this.t1y2 = NaN;
    this.t1z2 = NaN;
    this.t2x2 = NaN;
    this.t2y2 = NaN;
    this.t2z2 = NaN;
    this.l1x2 = NaN;
    this.l1y2 = NaN;
    this.l1z2 = NaN;
    this.l2x2 = NaN;
    this.l2y2 = NaN;
    this.l2z2 = NaN;
    this.a1x2 = NaN;
    this.a1y2 = NaN;
    this.a1z2 = NaN;
    this.a2x2 = NaN;
    this.a2y2 = NaN;
    this.a2z2 = NaN;
    this.t1x3 = NaN;
    this.t1y3 = NaN;
    this.t1z3 = NaN;
    this.t2x3 = NaN;
    this.t2y3 = NaN;
    this.t2z3 = NaN;
    this.l1x3 = NaN;
    this.l1y3 = NaN;
    this.l1z3 = NaN;
    this.l2x3 = NaN;
    this.l2y3 = NaN;
    this.l2z3 = NaN;
    this.a1x3 = NaN;
    this.a1y3 = NaN;
    this.a1z3 = NaN;
    this.a2x3 = NaN;
    this.a2y3 = NaN;
    this.a2z3 = NaN;
    this.lowerLimit1 = NaN;
    this.upperLimit1 = NaN;
    this.limitVelocity1 = NaN;
    this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
    this.enableMotor1 = false;
    this.motorSpeed1 = NaN;
    this.maxMotorForce1 = NaN;
    this.maxMotorImpulse1 = NaN;
    this.lowerLimit2 = NaN;
    this.upperLimit2 = NaN;
    this.limitVelocity2 = NaN;
    this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
    this.enableMotor2 = false;
    this.motorSpeed2 = NaN;
    this.maxMotorForce2 = NaN;
    this.maxMotorImpulse2 = NaN;
    this.lowerLimit3 = NaN;
    this.upperLimit3 = NaN;
    this.limitVelocity3 = NaN;
    this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
    this.enableMotor3 = false;
    this.motorSpeed3 = NaN;
    this.maxMotorForce3 = NaN;
    this.maxMotorImpulse3 = NaN;
    this.k00 = NaN; // K = J*M*JT
    this.k01 = NaN;
    this.k02 = NaN;
    this.k10 = NaN;
    this.k11 = NaN;
    this.k12 = NaN;
    this.k20 = NaN;
    this.k21 = NaN;
    this.k22 = NaN;
    this.kv00 = NaN; // diagonals without CFMs
    this.kv11 = NaN;
    this.kv22 = NaN;
    this.dv00 = NaN; // ...inverted
    this.dv11 = NaN;
    this.dv22 = NaN;
    this.d00 = NaN; // K^-1
    this.d01 = NaN;
    this.d02 = NaN;
    this.d10 = NaN;
    this.d11 = NaN;
    this.d12 = NaN;
    this.d20 = NaN;
    this.d21 = NaN;
    this.d22 = NaN;
 
    this.limitMotor1 = limitMotor1;
    this.limitMotor2 = limitMotor2;
    this.limitMotor3 = limitMotor3;
    this.b1 = joint.body1;
    this.b2 = joint.body2;
    this.p1 = joint.anchorPoint1;
    this.p2 = joint.anchorPoint2;
    this.r1 = joint.relativeAnchorPoint1;
    this.r2 = joint.relativeAnchorPoint2;
    this.l1 = this.b1.linearVelocity;
    this.l2 = this.b2.linearVelocity;
    this.a1 = this.b1.angularVelocity;
    this.a2 = this.b2.angularVelocity;
    this.i1 = this.b1.inverseInertia;
    this.i2 = this.b2.inverseInertia;
    this.limitImpulse1 = 0;
    this.motorImpulse1 = 0;
    this.limitImpulse2 = 0;
    this.motorImpulse2 = 0;
    this.limitImpulse3 = 0;
    this.motorImpulse3 = 0;
    this.cfm1 = 0;// Constraint Force Mixing
    this.cfm2 = 0;
    this.cfm3 = 0;
    this.weight = -1;
}
OIMO.Translational3Constraint.prototype = {
    constructor: OIMO.Translational3Constraint,
 
    preSolve: function (timeStep, invTimeStep) {
        this.ax1 = this.limitMotor1.axis.x;
        this.ay1 = this.limitMotor1.axis.y;
        this.az1 = this.limitMotor1.axis.z;
        this.ax2 = this.limitMotor2.axis.x;
        this.ay2 = this.limitMotor2.axis.y;
        this.az2 = this.limitMotor2.axis.z;
        this.ax3 = this.limitMotor3.axis.x;
        this.ay3 = this.limitMotor3.axis.y;
        this.az3 = this.limitMotor3.axis.z;
        this.lowerLimit1 = this.limitMotor1.lowerLimit;
        this.upperLimit1 = this.limitMotor1.upperLimit;
        this.motorSpeed1 = this.limitMotor1.motorSpeed;
        this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
        this.enableMotor1 = this.maxMotorForce1 > 0;
        this.lowerLimit2 = this.limitMotor2.lowerLimit;
        this.upperLimit2 = this.limitMotor2.upperLimit;
        this.motorSpeed2 = this.limitMotor2.motorSpeed;
        this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
        this.enableMotor2 = this.maxMotorForce2 > 0;
        this.lowerLimit3 = this.limitMotor3.lowerLimit;
        this.upperLimit3 = this.limitMotor3.upperLimit;
        this.motorSpeed3 = this.limitMotor3.motorSpeed;
        this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
        this.enableMotor3 = this.maxMotorForce3 > 0;
        this.m1 = this.b1.inverseMass;
        this.m2 = this.b2.inverseMass;
 
        var ti1 = this.i1.elements;
        var ti2 = this.i2.elements;
        this.i1e00 = ti1[0];
        this.i1e01 = ti1[1];
        this.i1e02 = ti1[2];
        this.i1e10 = ti1[3];
        this.i1e11 = ti1[4];
        this.i1e12 = ti1[5];
        this.i1e20 = ti1[6];
        this.i1e21 = ti1[7];
        this.i1e22 = ti1[8];
 
        this.i2e00 = ti2[0];
        this.i2e01 = ti2[1];
        this.i2e02 = ti2[2];
        this.i2e10 = ti2[3];
        this.i2e11 = ti2[4];
        this.i2e12 = ti2[5];
        this.i2e20 = ti2[6];
        this.i2e21 = ti2[7];
        this.i2e22 = ti2[8];
 
        var dx = this.p2.x - this.p1.x;
        var dy = this.p2.y - this.p1.y;
        var dz = this.p2.z - this.p1.z;
        var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
        var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
        var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
        var frequency1 = this.limitMotor1.frequency;
        var frequency2 = this.limitMotor2.frequency;
        var frequency3 = this.limitMotor3.frequency;
        var enableSpring1 = frequency1 > 0;
        var enableSpring2 = frequency2 > 0;
        var enableSpring3 = frequency3 > 0;
        var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
        var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
        var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
 
        // for stability
        if (enableSpring1 && d1 > 20 || d1 < -20) {
            enableSpring1 = false;
        }
        if (enableSpring2 && d2 > 20 || d2 < -20) {
            enableSpring2 = false;
        }
        if (enableSpring3 && d3 > 20 || d3 < -20) {
            enableSpring3 = false;
        }
 
        if (enableLimit1) {
            if (this.lowerLimit1 == this.upperLimit1) {
                if (this.limitState1 != 0) {
                    this.limitState1 = 0;
                    this.limitImpulse1 = 0;
                }
                this.limitVelocity1 = this.lowerLimit1 - d1;
                if (!enableSpring1) d1 = this.lowerLimit1;
            } else if (d1 < this.lowerLimit1) {
                if (this.limitState1 != -1) {
                    this.limitState1 = -1;
                    this.limitImpulse1 = 0;
                }
                this.limitVelocity1 = this.lowerLimit1 - d1;
                if (!enableSpring1) d1 = this.lowerLimit1;
            } else if (d1 > this.upperLimit1) {
                if (this.limitState1 != 1) {
                    this.limitState1 = 1;
                    this.limitImpulse1 = 0;
                }
                this.limitVelocity1 = this.upperLimit1 - d1;
                if (!enableSpring1) d1 = this.upperLimit1;
            } else {
                this.limitState1 = 2;
                this.limitImpulse1 = 0;
                this.limitVelocity1 = 0;
            }
            if (!enableSpring1) {
                if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
                else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
                else this.limitVelocity1 = 0;
            }
        } else {
            this.limitState1 = 2;
            this.limitImpulse1 = 0;
        }
 
        if (enableLimit2) {
            if (this.lowerLimit2 == this.upperLimit2) {
                if (this.limitState2 != 0) {
                    this.limitState2 = 0;
                    this.limitImpulse2 = 0;
                }
                this.limitVelocity2 = this.lowerLimit2 - d2;
                if (!enableSpring2) d2 = this.lowerLimit2;
            } else if (d2 < this.lowerLimit2) {
                if (this.limitState2 != -1) {
                    this.limitState2 = -1;
                    this.limitImpulse2 = 0;
                }
                this.limitVelocity2 = this.lowerLimit2 - d2;
                if (!enableSpring2) d2 = this.lowerLimit2;
            } else if (d2 > this.upperLimit2) {
                if (this.limitState2 != 1) {
                    this.limitState2 = 1;
                    this.limitImpulse2 = 0;
                }
                this.limitVelocity2 = this.upperLimit2 - d2;
                if (!enableSpring2) d2 = this.upperLimit2;
            } else {
                this.limitState2 = 2;
                this.limitImpulse2 = 0;
                this.limitVelocity2 = 0;
            }
            if (!enableSpring2) {
                if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
                else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
                else this.limitVelocity2 = 0;
            }
        } else {
            this.limitState2 = 2;
            this.limitImpulse2 = 0;
        }
 
        if (enableLimit3) {
            if (this.lowerLimit3 == this.upperLimit3) {
                if (this.limitState3 != 0) {
                    this.limitState3 = 0;
                    this.limitImpulse3 = 0;
                }
                this.limitVelocity3 = this.lowerLimit3 - d3;
                if (!enableSpring3) d3 = this.lowerLimit3;
            } else if (d3 < this.lowerLimit3) {
                if (this.limitState3 != -1) {
                    this.limitState3 = -1;
                    this.limitImpulse3 = 0;
                }
                this.limitVelocity3 = this.lowerLimit3 - d3;
                if (!enableSpring3) d3 = this.lowerLimit3;
            } else if (d3 > this.upperLimit3) {
                if (this.limitState3 != 1) {
                    this.limitState3 = 1;
                    this.limitImpulse3 = 0;
                }
                this.limitVelocity3 = this.upperLimit3 - d3;
                if (!enableSpring3) d3 = this.upperLimit3;
            } else {
                this.limitState3 = 2;
                this.limitImpulse3 = 0;
                this.limitVelocity3 = 0;
            }
            if (!enableSpring3) {
                if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
                else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
                else this.limitVelocity3 = 0;
            }
        } else {
            this.limitState3 = 2;
            this.limitImpulse3 = 0;
        }
 
        if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
            this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
        } else {
            this.motorImpulse1 = 0;
            this.maxMotorImpulse1 = 0;
        }
 
        if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
            this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
        } else {
            this.motorImpulse2 = 0;
            this.maxMotorImpulse2 = 0;
        }
 
        if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
            this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
        } else {
            this.motorImpulse3 = 0;
            this.maxMotorImpulse3 = 0;
        }
 
        var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
        var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
        var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
        var w1 = this.m2 / (this.m1 + this.m2);
        if (this.weight >= 0) w1 = this.weight; // use given weight
        var w2 = 1 - w1;
        this.r1x = this.r1.x + rdx * w1;
        this.r1y = this.r1.y + rdy * w1;
        this.r1z = this.r1.z + rdz * w1;
        this.r2x = this.r2.x - rdx * w2;
        this.r2y = this.r2.y - rdy * w2;
        this.r2z = this.r2.z - rdz * w2;
 
        // build jacobians
        this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
        this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
        this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
        this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
        this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
        this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
        this.l1x1 = this.ax1 * this.m1;
        this.l1y1 = this.ay1 * this.m1;
        this.l1z1 = this.az1 * this.m1;
        this.l2x1 = this.ax1 * this.m2;
        this.l2y1 = this.ay1 * this.m2;
        this.l2z1 = this.az1 * this.m2;
        this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
        this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
        this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
        this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
        this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
        this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
 
        this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
        this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
        this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
        this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
        this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
        this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
        this.l1x2 = this.ax2 * this.m1;
        this.l1y2 = this.ay2 * this.m1;
        this.l1z2 = this.az2 * this.m1;
        this.l2x2 = this.ax2 * this.m2;
        this.l2y2 = this.ay2 * this.m2;
        this.l2z2 = this.az2 * this.m2;
        this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
        this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
        this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
        this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
        this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
        this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
 
        this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
        this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
        this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
        this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
        this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
        this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
        this.l1x3 = this.ax3 * this.m1;
        this.l1y3 = this.ay3 * this.m1;
        this.l1z3 = this.az3 * this.m1;
        this.l2x3 = this.ax3 * this.m2;
        this.l2y3 = this.ay3 * this.m2;
        this.l2z3 = this.az3 * this.m2;
        this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
        this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
        this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
        this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
        this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
        this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
 
        // build an impulse matrix
        var m12 = this.m1 + this.m2;
        this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
        this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
        this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
        this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
        this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
        this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
        this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
        this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
        this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
 
        this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
        this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
        this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
        this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
        this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
        this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
        this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
        this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
        this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
 
        this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
        this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
        this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
        this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
        this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
        this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
        this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
        this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
        this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
 
        this.kv00 = this.k00;
        this.kv11 = this.k11;
        this.kv22 = this.k22;
 
        this.dv00 = 1 / this.kv00;
        this.dv11 = 1 / this.kv11;
        this.dv22 = 1 / this.kv22;
 
        if (enableSpring1 && this.limitState1 != 2) {
            var omega = 6.2831853 * frequency1;
            var k = omega * omega * timeStep;
            var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
            this.cfm1 = this.kv00 * dmp;
            this.limitVelocity1 *= k * dmp;
        } else {
            this.cfm1 = 0;
            this.limitVelocity1 *= invTimeStep * 0.05;
        }
        if (enableSpring2 && this.limitState2 != 2) {
            omega = 6.2831853 * frequency2;
            k = omega * omega * timeStep;
            dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
            this.cfm2 = this.kv11 * dmp;
            this.limitVelocity2 *= k * dmp;
        } else {
            this.cfm2 = 0;
            this.limitVelocity2 *= invTimeStep * 0.05;
        }
        if (enableSpring3 && this.limitState3 != 2) {
            omega = 6.2831853 * frequency3;
            k = omega * omega * timeStep;
            dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
            this.cfm3 = this.kv22 * dmp;
            this.limitVelocity3 *= k * dmp;
        } else {
            this.cfm3 = 0;
            this.limitVelocity3 *= invTimeStep * 0.05;
        }
        this.k00 += this.cfm1;
        this.k11 += this.cfm2;
        this.k22 += this.cfm3;
 
        var inv = 1 / (
        this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
        this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
        this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
        );
        this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
        this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
        this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
        this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
        this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
        this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
        this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
        this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
        this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
 
        // warm starting
        var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
        var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
        var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
        this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
        this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
        this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
        this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
        this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
        this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
        this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
        this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
        this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
        this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
        this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
        this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
    },
 
    solve: function () {
        var rvx = this.l2.x - this.l1.x + this.a2.y * this.r2z - this.a2.z * this.r2y - this.a1.y * this.r1z + this.a1.z * this.r1y;
        var rvy = this.l2.y - this.l1.y + this.a2.z * this.r2x - this.a2.x * this.r2z - this.a1.z * this.r1x + this.a1.x * this.r1z;
        var rvz = this.l2.z - this.l1.z + this.a2.x * this.r2y - this.a2.y * this.r2x - this.a1.x * this.r1y + this.a1.y * this.r1x;
        var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
        var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
        var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
        var oldMotorImpulse1 = this.motorImpulse1;
        var oldMotorImpulse2 = this.motorImpulse2;
        var oldMotorImpulse3 = this.motorImpulse3;
        var dMotorImpulse1 = 0;
        var dMotorImpulse2 = 0;
        var dMotorImpulse3 = 0;
        if (this.enableMotor1) {
            dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
            this.motorImpulse1 += dMotorImpulse1;
            if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
                this.motorImpulse1 = this.maxMotorImpulse1;
            } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
                this.motorImpulse1 = -this.maxMotorImpulse1;
            }
            dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
        }
        if (this.enableMotor2) {
            dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
            this.motorImpulse2 += dMotorImpulse2;
            if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
                this.motorImpulse2 = this.maxMotorImpulse2;
            } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
                this.motorImpulse2 = -this.maxMotorImpulse2;
            }
            dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
        }
        if (this.enableMotor3) {
            dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
            this.motorImpulse3 += dMotorImpulse3;
            if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
                this.motorImpulse3 = this.maxMotorImpulse3;
            } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
                this.motorImpulse3 = -this.maxMotorImpulse3;
            }
            dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
        }
 
        // apply motor impulse to relative velocity
        rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
        rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
        rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
 
        // subtract target velocity and applied impulse
        rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
        rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
        rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
 
        var oldLimitImpulse1 = this.limitImpulse1;
        var oldLimitImpulse2 = this.limitImpulse2;
        var oldLimitImpulse3 = this.limitImpulse3;
 
        var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
        var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
        var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
 
        this.limitImpulse1 += dLimitImpulse1;
        this.limitImpulse2 += dLimitImpulse2;
        this.limitImpulse3 += dLimitImpulse3;
 
        // clamp
        var clampState = 0;
        if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
            dLimitImpulse1 = -oldLimitImpulse1;
            rvn2 += dLimitImpulse1 * this.k10;
            rvn3 += dLimitImpulse1 * this.k20;
            clampState |= 1;
        }
        if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
            dLimitImpulse2 = -oldLimitImpulse2;
            rvn1 += dLimitImpulse2 * this.k01;
            rvn3 += dLimitImpulse2 * this.k21;
            clampState |= 2;
        }
        if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
            dLimitImpulse3 = -oldLimitImpulse3;
            rvn1 += dLimitImpulse3 * this.k02;
            rvn2 += dLimitImpulse3 * this.k12;
            clampState |= 4;
        }
 
        // update un-clamped impulse
        // TODO: isolate division
        var det;
        switch (clampState) {
            case 1:// update 2 3
                det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
                dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
                dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
                break;
            case 2:// update 1 3
                det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
                dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
                dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
                break;
            case 3:// update 3
                dLimitImpulse3 = rvn3 / this.k22;
                break;
            case 4:// update 1 2
                det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
                dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
                dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
                break;
            case 5:// update 2
                dLimitImpulse2 = rvn2 / this.k11;
                break;
            case 6:// update 1
                dLimitImpulse1 = rvn1 / this.k00;
                break;
        }
 
        this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
        this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
        this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
 
        var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
        var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
        var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
 
        // apply impulse
        this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
        this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
        this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
        this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
        this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
        this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
        this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
        this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
        this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
        this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
        this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
        this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
    }
}
/**
* A translational constraint for various joints.
* @author saharan
*/
OIMO.TranslationalConstraint = function (joint, limitMotor) {
    this.cfm = NaN;
    this.m1 = NaN;
    this.m2 = NaN;
    this.i1e00 = NaN;
    this.i1e01 = NaN;
    this.i1e02 = NaN;
    this.i1e10 = NaN;
    this.i1e11 = NaN;
    this.i1e12 = NaN;
    this.i1e20 = NaN;
    this.i1e21 = NaN;
    this.i1e22 = NaN;
    this.i2e00 = NaN;
    this.i2e01 = NaN;
    this.i2e02 = NaN;
    this.i2e10 = NaN;
    this.i2e11 = NaN;
    this.i2e12 = NaN;
    this.i2e20 = NaN;
    this.i2e21 = NaN;
    this.i2e22 = NaN;
    this.motorDenom = NaN;
    this.invMotorDenom = NaN;
    this.invDenom = NaN;
    this.ax = NaN;
    this.ay = NaN;
    this.az = NaN;
    this.r1x = NaN;
    this.r1y = NaN;
    this.r1z = NaN;
    this.r2x = NaN;
    this.r2y = NaN;
    this.r2z = NaN;
    this.t1x = NaN;
    this.t1y = NaN;
    this.t1z = NaN;
    this.t2x = NaN;
    this.t2y = NaN;
    this.t2z = NaN;
    this.l1x = NaN;
    this.l1y = NaN;
    this.l1z = NaN;
    this.l2x = NaN;
    this.l2y = NaN;
    this.l2z = NaN;
    this.a1x = NaN;
    this.a1y = NaN;
    this.a1z = NaN;
    this.a2x = NaN;
    this.a2y = NaN;
    this.a2z = NaN;
    this.lowerLimit = NaN;
    this.upperLimit = NaN;
    this.limitVelocity = NaN;
    this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
    this.enableMotor = false;
    this.motorSpeed = NaN;
    this.maxMotorForce = NaN;
    this.maxMotorImpulse = NaN;
 
    this.limitMotor = limitMotor;
    this.b1 = joint.body1;
    this.b2 = joint.body2;
    this.p1 = joint.anchorPoint1;
    this.p2 = joint.anchorPoint2;
    this.r1 = joint.relativeAnchorPoint1;
    this.r2 = joint.relativeAnchorPoint2;
    this.l1 = this.b1.linearVelocity;
    this.l2 = this.b2.linearVelocity;
    this.a1 = this.b1.angularVelocity;
    this.a2 = this.b2.angularVelocity;
    this.i1 = this.b1.inverseInertia;
    this.i2 = this.b2.inverseInertia;
    this.limitImpulse = 0;
    this.motorImpulse = 0;
}
OIMO.TranslationalConstraint.prototype = {
    constructor: OIMO.TranslationalConstraint,
 
    preSolve: function (timeStep, invTimeStep) {
        this.ax = this.limitMotor.axis.x;
        this.ay = this.limitMotor.axis.y;
        this.az = this.limitMotor.axis.z;
        this.lowerLimit = this.limitMotor.lowerLimit;
        this.upperLimit = this.limitMotor.upperLimit;
        this.motorSpeed = this.limitMotor.motorSpeed;
        this.maxMotorForce = this.limitMotor.maxMotorForce;
        this.enableMotor = this.maxMotorForce > 0;
        this.m1 = this.b1.inverseMass;
        this.m2 = this.b2.inverseMass;
 
        var ti1 = this.i1.elements;
        var ti2 = this.i2.elements;
        this.i1e00 = ti1[0];
        this.i1e01 = ti1[1];
        this.i1e02 = ti1[2];
        this.i1e10 = ti1[3];
        this.i1e11 = ti1[4];
        this.i1e12 = ti1[5];
        this.i1e20 = ti1[6];
        this.i1e21 = ti1[7];
        this.i1e22 = ti1[8];
 
        this.i2e00 = ti2[0];
        this.i2e01 = ti2[1];
        this.i2e02 = ti2[2];
        this.i2e10 = ti2[3];
        this.i2e11 = ti2[4];
        this.i2e12 = ti2[5];
        this.i2e20 = ti2[6];
        this.i2e21 = ti2[7];
        this.i2e22 = ti2[8];
 
        var dx = this.p2.x - this.p1.x;
        var dy = this.p2.y - this.p1.y;
        var dz = this.p2.z - this.p1.z;
        var d = dx * this.ax + dy * this.ay + dz * this.az;
        var frequency = this.limitMotor.frequency;
        var enableSpring = frequency > 0;
        var enableLimit = this.lowerLimit <= this.upperLimit;
        if (enableSpring && d > 20 || d < -20) {
            enableSpring = false;
        }
 
        if (enableLimit) {
            if (this.lowerLimit == this.upperLimit) {
                if (this.limitState != 0) {
                    this.limitState = 0;
                    this.limitImpulse = 0;
                }
                this.limitVelocity = this.lowerLimit - d;
                if (!enableSpring) d = this.lowerLimit;
            } else if (d < this.lowerLimit) {
                if (this.limitState != -1) {
                    this.limitState = -1;
                    this.limitImpulse = 0;
                }
                this.limitVelocity = this.lowerLimit - d;
                if (!enableSpring) d = this.lowerLimit;
            } else if (d > this.upperLimit) {
                if (this.limitState != 1) {
                    this.limitState = 1;
                    this.limitImpulse = 0;
                }
                this.limitVelocity = this.upperLimit - d;
                if (!enableSpring) d = this.upperLimit;
            } else {
                this.limitState = 2;
                this.limitImpulse = 0;
                this.limitVelocity = 0;
            }
            if (!enableSpring) {
                if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
                else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
                else this.limitVelocity = 0;
            }
        } else {
            this.limitState = 2;
            this.limitImpulse = 0;
        }
 
        if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
            this.maxMotorImpulse = this.maxMotorForce * timeStep;
        } else {
            this.motorImpulse = 0;
            this.maxMotorImpulse = 0;
        }
 
        var rdx = d * this.ax;
        var rdy = d * this.ay;
        var rdz = d * this.az;
        var w1 = this.m1 / (this.m1 + this.m2);
        var w2 = 1 - w1;
        this.r1x = this.r1.x + rdx * w1;
        this.r1y = this.r1.y + rdy * w1;
        this.r1z = this.r1.z + rdz * w1;
        this.r2x = this.r2.x - rdx * w2;
        this.r2y = this.r2.y - rdy * w2;
        this.r2z = this.r2.z - rdz * w2;
 
        this.t1x = this.r1y * this.az - this.r1z * this.ay;
        this.t1y = this.r1z * this.ax - this.r1x * this.az;
        this.t1z = this.r1x * this.ay - this.r1y * this.ax;
        this.t2x = this.r2y * this.az - this.r2z * this.ay;
        this.t2y = this.r2z * this.ax - this.r2x * this.az;
        this.t2z = this.r2x * this.ay - this.r2y * this.ax;
        this.l1x = this.ax * this.m1;
        this.l1y = this.ay * this.m1;
        this.l1z = this.az * this.m1;
        this.l2x = this.ax * this.m2;
        this.l2y = this.ay * this.m2;
        this.l2z = this.az * this.m2;
        this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
        this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
        this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
        this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
        this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
        this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
        this.motorDenom =
        this.m1 + this.m2 +
            this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
            this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
            this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
 
        this.invMotorDenom = 1 / this.motorDenom;
 
        if (enableSpring && this.limitState != 2) {
            var omega = 6.2831853 * frequency;
            var k = omega * omega * timeStep;
            var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
            this.cfm = this.motorDenom * dmp;
            this.limitVelocity *= k * dmp;
        } else {
            this.cfm = 0;
            this.limitVelocity *= invTimeStep * 0.05;
        }
 
        this.invDenom = 1 / (this.motorDenom + this.cfm);
 
        var totalImpulse = this.limitImpulse + this.motorImpulse;
        this.l1.x += totalImpulse * this.l1x;
        this.l1.y += totalImpulse * this.l1y;
        this.l1.z += totalImpulse * this.l1z;
        this.a1.x += totalImpulse * this.a1x;
        this.a1.y += totalImpulse * this.a1y;
        this.a1.z += totalImpulse * this.a1z;
        this.l2.x -= totalImpulse * this.l2x;
        this.l2.y -= totalImpulse * this.l2y;
        this.l2.z -= totalImpulse * this.l2z;
        this.a2.x -= totalImpulse * this.a2x;
        this.a2.y -= totalImpulse * this.a2y;
        this.a2.z -= totalImpulse * this.a2z;
    },
    solve: function () {
        var rvn =
            this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
            this.t2x * this.a2.x - this.t1x * this.a1.x + this.t2y * this.a2.y - this.t1y * this.a1.y + this.t2z * this.a2.z - this.t1z * this.a1.z;
 
        // motor part
        var newMotorImpulse;
        if (this.enableMotor) {
            newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
            var oldMotorImpulse = this.motorImpulse;
            this.motorImpulse += newMotorImpulse;
            if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
            else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
            newMotorImpulse = this.motorImpulse - oldMotorImpulse;
            rvn -= newMotorImpulse * this.motorDenom;
        } else newMotorImpulse = 0;
 
        // limit part
        var newLimitImpulse;
        if (this.limitState != 2) {
            newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
            var oldLimitImpulse = this.limitImpulse;
            this.limitImpulse += newLimitImpulse;
            if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
            newLimitImpulse = this.limitImpulse - oldLimitImpulse;
        } else newLimitImpulse = 0;
 
        var totalImpulse = newLimitImpulse + newMotorImpulse;
        this.l1.x += totalImpulse * this.l1x;
        this.l1.y += totalImpulse * this.l1y;
        this.l1.z += totalImpulse * this.l1z;
        this.a1.x += totalImpulse * this.a1x;
        this.a1.y += totalImpulse * this.a1y;
        this.a1.z += totalImpulse * this.a1z;
        this.l2.x -= totalImpulse * this.l2x;
        this.l2.y -= totalImpulse * this.l2y;
        this.l2.z -= totalImpulse * this.l2z;
        this.a2.x -= totalImpulse * this.a2x;
        this.a2.y -= totalImpulse * this.a2y;
        this.a2.z -= totalImpulse * this.a2z;
    }
}
/**
* A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
* @author saharan
*/
OIMO.Contact = function () {
    // The first shape.
    this.shape1 = null;
    // The second shape.
    this.shape2 = null;
    // The first rigid body.
    this.body1 = null;
    // The second rigid body.
    this.body2 = null;
    // The previous contact in the world.
    this.prev = null;
    // The next contact in the world.
    this.next = null;
    // Internal
    this.persisting = false;
    // Whether both the rigid bodies are sleeping or not.
    this.sleeping = false;
    // The collision detector between two shapes.
    this.detector = null;
    // The contact constraint of the contact.
    this.constraint = null;
    // Whether the shapes are touching or not.
    this.touching = false;
 
    this.b1Link = new OIMO.ContactLink(this);
    this.b2Link = new OIMO.ContactLink(this);
    this.s1Link = new OIMO.ContactLink(this);
    this.s2Link = new OIMO.ContactLink(this);
    // The contact manifold of the contact.
    this.manifold = new OIMO.ContactManifold();
    this.buffer = [];// vector 4
    this.buffer.length = 4;
    this.buffer[0] = new OIMO.ImpulseDataBuffer();
    this.buffer[1] = new OIMO.ImpulseDataBuffer();
    this.buffer[2] = new OIMO.ImpulseDataBuffer();
    this.buffer[3] = new OIMO.ImpulseDataBuffer();
    this.points = this.manifold.points;
    this.constraint = new OIMO.ContactConstraint(this.manifold);
}
OIMO.Contact.prototype = {
    constructor: OIMO.Contact,
 
    mixRestitution: function (restitution1, restitution2) {
        return OIMO.sqrt(restitution1 * restitution2);
    },
    mixFriction: function (friction1, friction2) {
        return OIMO.sqrt(friction1 * friction2);
    },
    /**
    * Update the contact manifold.
    */
    updateManifold: function () {
        this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
        this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
        var numBuffers = this.manifold.numPoints;
        var i = numBuffers;
        while (i--) {
            //for(var i=0;i<numBuffers;i++){
            var b = this.buffer[i];
            var p = this.points[i];
            b.lp1X = p.localPoint1.x;
            b.lp1Y = p.localPoint1.y;
            b.lp1Z = p.localPoint1.z;
            b.lp2X = p.localPoint2.x;
            b.lp2Y = p.localPoint2.y;
            b.lp2Z = p.localPoint2.z;
            b.impulse = p.normalImpulse;
        }
        this.manifold.numPoints = 0;
        this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
        var num = this.manifold.numPoints;
        if (num == 0) {
            this.touching = false;
            return;
        }
        this.touching = true;
        i = num;
        while (i--) {
            //for(i=0; i<num; i++){
            p = this.points[i];
            var lp1x = p.localPoint1.x;
            var lp1y = p.localPoint1.y;
            var lp1z = p.localPoint1.z;
            var lp2x = p.localPoint2.x;
            var lp2y = p.localPoint2.y;
            var lp2z = p.localPoint2.z;
            var index = -1;
            var minDistance = 0.0004;
            var j = numBuffers;
            while (j--) {
                //for(var j=0;j<numBuffers;j++){
                b = this.buffer[j];
                var dx = b.lp1X - lp1x;
                var dy = b.lp1Y - lp1y;
                var dz = b.lp1Z - lp1z;
                var distance1 = dx * dx + dy * dy + dz * dz;
                dx = b.lp2X - lp2x;
                dy = b.lp2Y - lp2y;
                dz = b.lp2Z - lp2z;
                var distance2 = dx * dx + dy * dy + dz * dz;
                if (distance1 < distance2) {
                    if (distance1 < minDistance) {
                        minDistance = distance1;
                        index = j;
                    }
                } else {
                    if (distance2 < minDistance) {
                        minDistance = distance2;
                        index = j;
                    }
                }
            }
            if (index != -1) {
                var tmp = this.buffer[index];
                this.buffer[index] = this.buffer[--numBuffers];
                this.buffer[numBuffers] = tmp;
                p.normalImpulse = tmp.impulse;
                p.warmStarted = true;
            } else {
                p.normalImpulse = 0;
                p.warmStarted = false;
            }
        }
    },
    /**
    * Attach the contact to the shapes.
    * @param   shape1
    * @param   shape2
    */
    attach: function (shape1, shape2) {
        this.shape1 = shape1;
        this.shape2 = shape2;
        this.body1 = shape1.parent;
        this.body2 = shape2.parent;
 
        this.manifold.body1 = this.body1;
        this.manifold.body2 = this.body2;
        this.constraint.body1 = this.body1;
        this.constraint.body2 = this.body2;
        this.constraint.attach();
 
        this.s1Link.shape = shape2;
        this.s1Link.body = this.body2;
        this.s2Link.shape = shape1;
        this.s2Link.body = this.body1;
 
        if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
        else this.s1Link.next = null;
        shape1.contactLink = this.s1Link;
        shape1.numContacts++;
 
        if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
        else this.s2Link.next = null;
        shape2.contactLink = this.s2Link;
        shape2.numContacts++;
 
        this.b1Link.shape = shape2;
        this.b1Link.body = this.body2;
        this.b2Link.shape = shape1;
        this.b2Link.body = this.body1;
 
        if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
        else this.b1Link.next = null;
        this.body1.contactLink = this.b1Link;
        this.body1.numContacts++;
 
        if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
        else this.b2Link.next = null;
        this.body2.contactLink = this.b2Link;
        this.body2.numContacts++;
 
        this.prev = null;
        this.next = null;
 
        this.persisting = true;
        this.sleeping = this.body1.sleeping && this.body2.sleeping;
        this.manifold.numPoints = 0;
    },
    /**
    * Detach the contact from the shapes.
    */
    detach: function () {
        var prev = this.s1Link.prev;
        var next = this.s1Link.next;
        if (prev !== null) prev.next = next;
        if (next !== null) next.prev = prev;
        if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
        this.s1Link.prev = null;
        this.s1Link.next = null;
        this.s1Link.shape = null;
        this.s1Link.body = null;
        this.shape1.numContacts--;
 
        prev = this.s2Link.prev;
        next = this.s2Link.next;
        if (prev !== null) prev.next = next;
        if (next !== null) next.prev = prev;
        if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
        this.s2Link.prev = null;
        this.s2Link.next = null;
        this.s2Link.shape = null;
        this.s2Link.body = null;
        this.shape2.numContacts--;
 
        prev = this.b1Link.prev;
        next = this.b1Link.next;
        if (prev !== null) prev.next = next;
        if (next !== null) next.prev = prev;
        if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
        this.b1Link.prev = null;
        this.b1Link.next = null;
        this.b1Link.shape = null;
        this.b1Link.body = null;
        this.body1.numContacts--;
 
        prev = this.b2Link.prev;
        next = this.b2Link.next;
        if (prev !== null) prev.next = next;
        if (next !== null) next.prev = prev;
        if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
        this.b2Link.prev = null;
        this.b2Link.next = null;
        this.b2Link.shape = null;
        this.b2Link.body = null;
        this.body2.numContacts--;
 
        this.manifold.body1 = null;
        this.manifold.body2 = null;
        this.constraint.body1 = null;
        this.constraint.body2 = null;
        this.constraint.detach();
 
        this.shape1 = null;
        this.shape2 = null;
        this.body1 = null;
        this.body2 = null;
    }
}
/**
* ...
* @author saharan
*/
OIMO.ContactConstraint = function (manifold) {
    OIMO.Constraint.call(this);
    // The contact manifold of the constraint.
    this.manifold = manifold;
    // The coefficient of restitution of the constraint.
    this.restitution = NaN;
    // The coefficient of friction of the constraint.
    this.friction = NaN;
    this.p1 = null;
    this.p2 = null;
    this.lv1 = null;
    this.lv2 = null;
    this.av1 = null;
    this.av2 = null;
    this.i1 = null;
    this.i2 = null;
 
    this.ii1 = null;
    this.ii2 = null;
 
    this.m1 = NaN;
    this.m2 = NaN;
    this.num = 0;
 
    this.ps = manifold.points;
    this.cs = new OIMO.ContactPointDataBuffer();
    this.cs.next = new OIMO.ContactPointDataBuffer();
    this.cs.next.next = new OIMO.ContactPointDataBuffer();
    this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
}
OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
/**
* Attach the constraint to the bodies.
*/
OIMO.ContactConstraint.prototype.attach = function () {
    this.p1 = this.body1.position;
    this.p2 = this.body2.position;
    this.lv1 = this.body1.linearVelocity;
    this.av1 = this.body1.angularVelocity;
    this.lv2 = this.body2.linearVelocity;
    this.av2 = this.body2.angularVelocity;
    this.i1 = this.body1.inverseInertia;
    this.i2 = this.body2.inverseInertia;
}
/**
* Detach the constraint from the bodies.
*/
OIMO.ContactConstraint.prototype.detach = function () {
    this.p1 = null;
    this.p2 = null;
    this.lv1 = null;
    this.lv2 = null;
    this.av1 = null;
    this.av2 = null;
    this.i1 = null;
    this.i2 = null;
}
OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
    this.m1 = this.body1.inverseMass;
    this.m2 = this.body2.inverseMass;
 
    this.ii1 = this.i1.clone();
    this.ii2 = this.i2.clone();
 
    var ii1 = this.ii1.elements;
    var ii2 = this.ii2.elements;
 
    var p1x = this.p1.x;
    var p1y = this.p1.y;
    var p1z = this.p1.z;
    var p2x = this.p2.x;
    var p2y = this.p2.y;
    var p2z = this.p2.z;
 
    var m1m2 = this.m1 + this.m2;
 
    this.num = this.manifold.numPoints;
 
    var c = this.cs;
 
    for (var i = 0; i < this.num; i++) {
        var p = this.ps[i];
        var tmp1X;
        var tmp1Y;
        var tmp1Z;
        var tmp2X;
        var tmp2Y;
        var tmp2Z;
        tmp1X = p.position.x;
        tmp1Y = p.position.y;
        tmp1Z = p.position.z;
        var rp1X = tmp1X - p1x;
        var rp1Y = tmp1Y - p1y;
        var rp1Z = tmp1Z - p1z;
        var rp2X = tmp1X - p2x;
        var rp2Y = tmp1Y - p2y;
        var rp2Z = tmp1Z - p2z;
        c.rp1X = rp1X;
        c.rp1Y = rp1Y;
        c.rp1Z = rp1Z;
        c.rp2X = rp2X;
        c.rp2Y = rp2Y;
        c.rp2Z = rp2Z;
        c.norImp = p.normalImpulse;
        c.tanImp = p.tangentImpulse;
        c.binImp = p.binormalImpulse;
        var norX = p.normal.x;
        var norY = p.normal.y;
        var norZ = p.normal.z;
        var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
        var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
        var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
        var rvn = norX * rvX + norY * rvY + norZ * rvZ;
        var tanX = rvX - rvn * norX;
        var tanY = rvY - rvn * norY;
        var tanZ = rvZ - rvn * norZ;
        var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
        if (len > 0.04) {
            len = 1 / OIMO.sqrt(len);
        } else {
            tanX = norY * norX - norZ * norZ;
            tanY = -norZ * norY - norX * norX;
            tanZ = norX * norZ + norY * norY;
            len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
        }
        tanX *= len;
        tanY *= len;
        tanZ *= len;
        var binX = norY * tanZ - norZ * tanY;
        var binY = norZ * tanX - norX * tanZ;
        var binZ = norX * tanY - norY * tanX;
        c.norX = norX;
        c.norY = norY;
        c.norZ = norZ;
        c.tanX = tanX;
        c.tanY = tanY;
        c.tanZ = tanZ;
        c.binX = binX;
        c.binY = binY;
        c.binZ = binZ;
        c.norU1X = norX * this.m1;
        c.norU1Y = norY * this.m1;
        c.norU1Z = norZ * this.m1;
        c.norU2X = norX * this.m2;
        c.norU2Y = norY * this.m2;
        c.norU2Z = norZ * this.m2;
        c.tanU1X = tanX * this.m1;
        c.tanU1Y = tanY * this.m1;
        c.tanU1Z = tanZ * this.m1;
        c.tanU2X = tanX * this.m2;
        c.tanU2Y = tanY * this.m2;
        c.tanU2Z = tanZ * this.m2;
        c.binU1X = binX * this.m1;
        c.binU1Y = binY * this.m1;
        c.binU1Z = binZ * this.m1;
        c.binU2X = binX * this.m2;
        c.binU2Y = binY * this.m2;
        c.binU2Z = binZ * this.m2;
        var norT1X = rp1Y * norZ - rp1Z * norY;
        var norT1Y = rp1Z * norX - rp1X * norZ;
        var norT1Z = rp1X * norY - rp1Y * norX;
        var norT2X = rp2Y * norZ - rp2Z * norY;
        var norT2Y = rp2Z * norX - rp2X * norZ;
        var norT2Z = rp2X * norY - rp2Y * norX;
        var tanT1X = rp1Y * tanZ - rp1Z * tanY;
        var tanT1Y = rp1Z * tanX - rp1X * tanZ;
        var tanT1Z = rp1X * tanY - rp1Y * tanX;
        var tanT2X = rp2Y * tanZ - rp2Z * tanY;
        var tanT2Y = rp2Z * tanX - rp2X * tanZ;
        var tanT2Z = rp2X * tanY - rp2Y * tanX;
        var binT1X = rp1Y * binZ - rp1Z * binY;
        var binT1Y = rp1Z * binX - rp1X * binZ;
        var binT1Z = rp1X * binY - rp1Y * binX;
        var binT2X = rp2Y * binZ - rp2Z * binY;
        var binT2Y = rp2Z * binX - rp2X * binZ;
        var binT2Z = rp2X * binY - rp2Y * binX;
        var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
        var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
        var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
        var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
        var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
        var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
        var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
        var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
        var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
        var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
        var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
        var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
        var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
        var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
        var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
        var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
        var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
        var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
        c.norT1X = norT1X;
        c.norT1Y = norT1Y;
        c.norT1Z = norT1Z;
        c.tanT1X = tanT1X;
        c.tanT1Y = tanT1Y;
        c.tanT1Z = tanT1Z;
        c.binT1X = binT1X;
        c.binT1Y = binT1Y;
        c.binT1Z = binT1Z;
        c.norT2X = norT2X;
        c.norT2Y = norT2Y;
        c.norT2Z = norT2Z;
        c.tanT2X = tanT2X;
        c.tanT2Y = tanT2Y;
        c.tanT2Z = tanT2Z;
        c.binT2X = binT2X;
        c.binT2Y = binT2Y;
        c.binT2Z = binT2Z;
        c.norTU1X = norTU1X;
        c.norTU1Y = norTU1Y;
        c.norTU1Z = norTU1Z;
        c.tanTU1X = tanTU1X;
        c.tanTU1Y = tanTU1Y;
        c.tanTU1Z = tanTU1Z;
        c.binTU1X = binTU1X;
        c.binTU1Y = binTU1Y;
        c.binTU1Z = binTU1Z;
        c.norTU2X = norTU2X;
        c.norTU2Y = norTU2Y;
        c.norTU2Z = norTU2Z;
        c.tanTU2X = tanTU2X;
        c.tanTU2Y = tanTU2Y;
        c.tanTU2Z = tanTU2Z;
        c.binTU2X = binTU2X;
        c.binTU2Y = binTU2Y;
        c.binTU2Z = binTU2Z;
        tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
        tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
        tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
        tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
        tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
        tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
        tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
        tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
        tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
        tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
        tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
        tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
        var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
        tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
        tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
        tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
        tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
        tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
        tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
        tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
        tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
        tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
        tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
        tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
        tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
        var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
        tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
        tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
        tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
        tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
        tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
        tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
        tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
        tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
        tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
        tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
        tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
        tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
        var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
        c.norDen = norDen;
        c.tanDen = tanDen;
        c.binDen = binDen;
        if (p.warmStarted) {
            var norImp = p.normalImpulse;
            this.lv1.x += c.norU1X * norImp;
            this.lv1.y += c.norU1Y * norImp;
            this.lv1.z += c.norU1Z * norImp;
            this.av1.x += norTU1X * norImp;
            this.av1.y += norTU1Y * norImp;
            this.av1.z += norTU1Z * norImp;
            this.lv2.x -= c.norU2X * norImp;
            this.lv2.y -= c.norU2Y * norImp;
            this.lv2.z -= c.norU2Z * norImp;
            this.av2.x -= norTU2X * norImp;
            this.av2.y -= norTU2Y * norImp;
            this.av2.z -= norTU2Z * norImp;
            c.norImp = norImp;
            c.tanImp = 0;
            c.binImp = 0;
            rvn = 0; // disable bouncing
        } else {
            c.norImp = 0;
            c.tanImp = 0;
            c.binImp = 0;
        }
 
        if (rvn > -1) {
            rvn = 0; // disable bouncing
        }
        var norTar = this.restitution * -rvn;
        var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
        if (norTar < sepV) norTar = sepV;
        c.norTar = norTar;
        c.last = i == this.num - 1;
        c = c.next;
    }
}
OIMO.ContactConstraint.prototype.solve = function () {
    var lv1x = this.lv1.x;
    var lv1y = this.lv1.y;
    var lv1z = this.lv1.z;
    var lv2x = this.lv2.x;
    var lv2y = this.lv2.y;
    var lv2z = this.lv2.z;
    var av1x = this.av1.x;
    var av1y = this.av1.y;
    var av1z = this.av1.z;
    var av2x = this.av2.x;
    var av2y = this.av2.y;
    var av2z = this.av2.z;
    var c = this.cs;
    while (true) {
        var oldImp1;
        var newImp1;
        var oldImp2;
        var newImp2;
        var rvn;
        var norImp = c.norImp;
        var tanImp = c.tanImp;
        var binImp = c.binImp;
        var max = -norImp * this.friction;
        var rvX = lv2x - lv1x;
        var rvY = lv2y - lv1y;
        var rvZ = lv2z - lv1z;
        rvn =
        rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
        av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
        av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
        ;
        oldImp1 = tanImp;
        newImp1 = rvn * c.tanDen;
        tanImp += newImp1;
        rvn =
        rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
        av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
        av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
        ;
        oldImp2 = binImp;
        newImp2 = rvn * c.binDen;
        binImp += newImp2;
 
        // cone friction clamp
        var len = tanImp * tanImp + binImp * binImp;
        if (len > max * max) {
            len = max / OIMO.sqrt(len);
            tanImp *= len;
            binImp *= len;
        }
        newImp1 = tanImp - oldImp1;
        newImp2 = binImp - oldImp2;
 
        lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
        lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
        lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
        av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
        av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
        av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
        lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
        lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
        lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
        av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
        av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
        av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
 
        // restitution part
        rvn =
        (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
        av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
        av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
 
        oldImp1 = norImp;
        newImp1 = (rvn - c.norTar) * c.norDen;
        norImp += newImp1;
        if (norImp > 0) norImp = 0;
        newImp1 = norImp - oldImp1;
        lv1x += c.norU1X * newImp1;
        lv1y += c.norU1Y * newImp1;
        lv1z += c.norU1Z * newImp1;
        av1x += c.norTU1X * newImp1;
        av1y += c.norTU1Y * newImp1;
        av1z += c.norTU1Z * newImp1;
        lv2x -= c.norU2X * newImp1;
        lv2y -= c.norU2Y * newImp1;
        lv2z -= c.norU2Z * newImp1;
        av2x -= c.norTU2X * newImp1;
        av2y -= c.norTU2Y * newImp1;
        av2z -= c.norTU2Z * newImp1;
 
        c.norImp = norImp;
        c.tanImp = tanImp;
        c.binImp = binImp;
 
        if (c.last) break;
        c = c.next;
    }
    this.lv1.x = lv1x;
    this.lv1.y = lv1y;
    this.lv1.z = lv1z;
    this.lv2.x = lv2x;
    this.lv2.y = lv2y;
    this.lv2.z = lv2z;
    this.av1.x = av1x;
    this.av1.y = av1y;
    this.av1.z = av1z;
    this.av2.x = av2x;
    this.av2.y = av2y;
    this.av2.z = av2z;
}
OIMO.ContactConstraint.prototype.postSolve = function () {
    var c = this.cs;
    var i = this.num;
    while (i--) {
        //for(var i=0;i<this.num;i++){
        var p = this.ps[i];
        p.normal.x = c.norX;
        p.normal.y = c.norY;
        p.normal.z = c.norZ;
        p.tangent.x = c.tanX;
        p.tangent.y = c.tanY;
        p.tangent.z = c.tanZ;
        p.binormal.x = c.binX;
        p.binormal.y = c.binY;
        p.binormal.z = c.binZ;
        p.normalImpulse = c.norImp;
        p.tangentImpulse = c.tanImp;
        p.binormalImpulse = c.binImp;
        p.normalDenominator = c.norDen;
        p.tangentDenominator = c.tanDen;
        p.binormalDenominator = c.binDen;
        c = c.next;
    }
}
/**
* A link list of contacts.
* @author saharan
*/
OIMO.ContactLink = function (contact) {
    // The previous contact link.
    this.prev = null;
    // The next contact link.
    this.next = null;
    // The shape of the contact.
    this.shape = null;
    // The other rigid body.
    this.body = null;
    // The contact of the link.
    this.contact = contact;
}
/**
* A contact manifold between two shapes.
* @author saharan
*/
OIMO.ContactManifold = function () {
    // The first rigid body.
    this.body1 = null;
    // The second rigid body.
    this.body2 = null;
    // The number of manifold points.
    this.numPoints = 0;
    // The manifold points.
    this.points = [];
    this.points.length = 4;
    this.points[0] = new OIMO.ManifoldPoint();
    this.points[1] = new OIMO.ManifoldPoint();
    this.points[2] = new OIMO.ManifoldPoint();
    this.points[3] = new OIMO.ManifoldPoint();
}
OIMO.ContactManifold.prototype = {
    constructor: OIMO.ContactManifold,
    /**
    * Reset the manifold.
    * @param   shape1
    * @param   shape2
    */
    reset: function (shape1, shape2) {
        this.body1 = shape1.parent;
        this.body2 = shape2.parent;
        this.numPoints = 0;
    },
    /**
    * Add a point into this manifold.
    * @param   x
    * @param   y
    * @param   z
    * @param   normalX
    * @param   normalY
    * @param   normalZ
    * @param   penetration
    * @param   flip
    */
    addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
        var p = this.points[this.numPoints++];
        p.position.x = x;
        p.position.y = y;
        p.position.z = z;
        var r = this.body1.rotation;
        var rx = x - this.body1.position.x;
        var ry = y - this.body1.position.y;
        var rz = z - this.body1.position.z;
 
        var tr = r.elements;
        p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
        p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
        p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
        r = this.body2.rotation;
        rx = x - this.body2.position.x;
        ry = y - this.body2.position.y;
        rz = z - this.body2.position.z;
        p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
        p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
        p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
 
        p.normalImpulse = 0;
        if (flip) {
            p.normal.x = -normalX;
            p.normal.y = -normalY;
            p.normal.z = -normalZ;
        } else {
            p.normal.x = normalX;
            p.normal.y = normalY;
            p.normal.z = normalZ;
        }
        p.penetration = penetration;
        p.warmStarted = false;
    }
}
OIMO.ContactPointDataBuffer = function () {
    this.norX = NaN;
    this.norY = NaN;
    this.norZ = NaN;
    this.tanX = NaN;
    this.tanY = NaN;
    this.tanZ = NaN;
    this.binX = NaN;
    this.binY = NaN;
    this.binZ = NaN;
 
    this.rp1X = NaN;
    this.rp1Y = NaN;
    this.rp1Z = NaN;
    this.rp2X = NaN;
    this.rp2Y = NaN;
    this.rp2Z = NaN;
 
    this.norU1X = NaN;
    this.norU1Y = NaN;
    this.norU1Z = NaN;
    this.norU2X = NaN;
    this.norU2Y = NaN;
    this.norU2Z = NaN;
    this.tanU1X = NaN;
    this.tanU1Y = NaN;
    this.tanU1Z = NaN;
    this.tanU2X = NaN;
    this.tanU2Y = NaN;
    this.tanU2Z = NaN;
    this.binU1X = NaN;
    this.binU1Y = NaN;
    this.binU1Z = NaN;
    this.binU2X = NaN;
    this.binU2Y = NaN;
    this.binU2Z = NaN;
 
    this.norT1X = NaN;
    this.norT1Y = NaN;
    this.norT1Z = NaN;
    this.norT2X = NaN;
    this.norT2Y = NaN;
    this.norT2Z = NaN;
    this.tanT1X = NaN;
    this.tanT1Y = NaN;
    this.tanT1Z = NaN;
    this.tanT2X = NaN;
    this.tanT2Y = NaN;
    this.tanT2Z = NaN;
    this.binT1X = NaN;
    this.binT1Y = NaN;
    this.binT1Z = NaN;
    this.binT2X = NaN;
    this.binT2Y = NaN;
    this.binT2Z = NaN;
 
    this.norTU1X = NaN;
    this.norTU1Y = NaN;
    this.norTU1Z = NaN;
    this.norTU2X = NaN;
    this.norTU2Y = NaN;
    this.norTU2Z = NaN;
    this.tanTU1X = NaN;
    this.tanTU1Y = NaN;
    this.tanTU1Z = NaN;
    this.tanTU2X = NaN;
    this.tanTU2Y = NaN;
    this.tanTU2Z = NaN;
    this.binTU1X = NaN;
    this.binTU1Y = NaN;
    this.binTU1Z = NaN;
    this.binTU2X = NaN;
    this.binTU2Y = NaN;
    this.binTU2Z = NaN;
 
    this.norImp = NaN;
    this.tanImp = NaN;
    this.binImp = NaN;
    this.norDen = NaN;
    this.tanDen = NaN;
    this.binDen = NaN;
    this.norTar = NaN;
    this.next = null;
    this.last = false;
}
OIMO.ImpulseDataBuffer = function () {
    this.lp1X = NaN;
    this.lp1Y = NaN;
    this.lp1Z = NaN;
    this.lp2X = NaN;
    this.lp2Y = NaN;
    this.lp2Z = NaN;
    this.impulse = NaN;
}
/**
* The class holds details of the contact point.
* @author saharan
*/
OIMO.ManifoldPoint = function () {
    // Whether this manifold point is persisting or not.
    this.warmStarted = false;
    //  The position of this manifold point.
    this.position = new OIMO.Vec3();
    // The position in the first shape's coordinate.
    this.localPoint1 = new OIMO.Vec3();
    //  The position in the second shape's coordinate.
    this.localPoint2 = new OIMO.Vec3();
    // The normal vector of this manifold point.
    this.normal = new OIMO.Vec3();
    // The tangent vector of this manifold point.
    this.tangent = new OIMO.Vec3();
    // The binormal vector of this manifold point.
    this.binormal = new OIMO.Vec3();
    // The impulse in normal direction.
    this.normalImpulse = 0;
    // The impulse in tangent direction.
    this.tangentImpulse = 0;
    // The impulse in binormal direction.
    this.binormalImpulse = 0;
    // The denominator in normal direction.
    this.normalDenominator = 0;
    // The denominator in tangent direction.
    this.tangentDenominator = 0;
    // The denominator in binormal direction.
    this.binormalDenominator = 0;
    // The depth of penetration.
    this.penetration = 0;
}
/**
* This class holds mass information of a shape.
* @author saharan
*/
OIMO.MassInfo = function () {
 
    // Mass of the shape.
    this.mass = 0;
    // The moment inertia of the shape.
    this.inertia = new OIMO.Mat33();
 
};
/**
 * A shape is used to detect collisions of rigid bodies.
 * @author saharan
 * @author lo-th
 */
 
OIMO.Shape = function (config) {
 
    this.type = OIMO.SHAPE_NULL;
 
    // The global identification of the shape should be unique to the shape.
    this.id = OIMO.nextID++;
 
    // The previous shape in parent rigid body.
    this.prev = null;
    // The next shape in parent rigid body.
    this.next = null;
 
    // The proxy of the shape used for broad-phase collision detection.
    this.proxy = null;
    // The parent rigid body of the shape.
    this.parent = null;
    // The linked list of the contacts with the shape.
    this.contactLink = null;
    // The number of the contacts with the shape.
    this.numContacts = 0;
 
    // The center of gravity of the shape in world coordinate system.
    this.position = new OIMO.Vec3();
    // The rotation matrix of the shape in world coordinate system
    this.rotation = new OIMO.Mat33();
 
    // The position of the shape in parent's coordinate system.
    this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
    // The rotation matrix of the shape in parent's coordinate system.
    this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
 
    // The axis-aligned bounding box of the shape.
    this.aabb = new OIMO.AABB();
 
    // The density of the shape.
    this.density = config.density;
    // The coefficient of friction of the shape.
    this.friction = config.friction;
    // The coefficient of restitution of the shape.
    this.restitution = config.restitution;
    // The bits of the collision groups to which the shape belongs.
    this.belongsTo = config.belongsTo;
    // The bits of the collision groups with which the shape collides.
    this.collidesWith = config.collidesWith;
 
};
 
OIMO.Shape.prototype = {
 
    constructor: OIMO.Shape,
 
    // Calculate the mass information of the shape.
 
    calculateMassInfo: function (out) {
 
        OIMO.Error("Shape", "Inheritance error.");
 
    },
 
    // Update the proxy of the shape.
 
    updateProxy: function () {
 
        OIMO.Error("Shape", "Inheritance error.");
 
    }
 
};
/**
 * A shape configuration holds common configuration data for constructing a shape.
 * Shape configurations can be reused safely.
 * @author saharan
 */
 
OIMO.ShapeConfig = function () {
 
    // The position of the shape in parent's coordinate system.
    this.relativePosition = new OIMO.Vec3();
    // The rotation matrix of the shape in parent's coordinate system.
    this.relativeRotation = new OIMO.Mat33();
    // The coefficient of friction of the shape.
    this.friction = 0.4;
    // The coefficient of restitution of the shape.
    this.restitution = 0.2;
    // The density of the shape.
    this.density = 1;
    // The bits of the collision groups to which the shape belongs.
    this.belongsTo = 1;
    // The bits of the collision groups with which the shape collides.
    this.collidesWith = 0xffffffff;
 
};
/**
 * A box shape.
 * @author saharan
 * @author lo-th
 */
 
OIMO.BoxShape = function (config, Width, Height, Depth) {
 
    OIMO.Shape.call(this, config);
 
    this.type = OIMO.SHAPE_BOX;
 
    // The width of the box.
    this.width = Width;
    // The height of the box.
    this.height = Height;
    // The depth of the box.
    this.depth = Depth;
    // The half-width of the box.
    this.halfWidth = Width * 0.5;
    // The half-height of the box.
    this.halfHeight = Height * 0.5;
    // The half-depth of the box.
    this.halfDepth = Depth * 0.5;
 
    this.dimentions = new OIMO_ARRAY_TYPE(18);
    this.elements = new OIMO_ARRAY_TYPE(24);
 
};
 
OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
 
OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
 
    var mass = this.width * this.height * this.depth * this.density;
    var divid = 1 / 12;
    out.mass = mass;
    out.inertia.set(
        mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
        0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
        0, 0, mass * (this.width * this.width + this.height * this.height) * divid
    );
 
};
 
OIMO.BoxShape.prototype.updateProxy = function () {
 
    var te = this.rotation.elements;
    var di = this.dimentions;
    // Width
    di[0] = te[0];
    di[1] = te[3];
    di[2] = te[6];
    // Height
    di[3] = te[1];
    di[4] = te[4];
    di[5] = te[7];
    // Depth
    di[6] = te[2];
    di[7] = te[5];
    di[8] = te[8];
    // halp Width
    di[9] = te[0] * this.halfWidth;
    di[10] = te[3] * this.halfWidth;
    di[11] = te[6] * this.halfWidth;
    // halp Height
    di[12] = te[1] * this.halfHeight;
    di[13] = te[4] * this.halfHeight;
    di[14] = te[7] * this.halfHeight;
    // halp Depth
    di[15] = te[2] * this.halfDepth;
    di[16] = te[5] * this.halfDepth;
    di[17] = te[8] * this.halfDepth;
 
    var wx = di[9];
    var wy = di[10];
    var wz = di[11];
    var hx = di[12];
    var hy = di[13];
    var hz = di[14];
    var dx = di[15];
    var dy = di[16];
    var dz = di[17];
 
    var x = this.position.x;
    var y = this.position.y;
    var z = this.position.z;
 
    var v = this.elements;
    //v1
    v[0] = x + wx + hx + dx;
    v[1] = y + wy + hy + dy;
    v[2] = z + wz + hz + dz;
    //v2
    v[3] = x + wx + hx - dx;
    v[4] = y + wy + hy - dy;
    v[5] = z + wz + hz - dz;
    //v3
    v[6] = x + wx - hx + dx;
    v[7] = y + wy - hy + dy;
    v[8] = z + wz - hz + dz;
    //v4
    v[9] = x + wx - hx - dx;
    v[10] = y + wy - hy - dy;
    v[11] = z + wz - hz - dz;
    //v5
    v[12] = x - wx + hx + dx;
    v[13] = y - wy + hy + dy;
    v[14] = z - wz + hz + dz;
    //v6
    v[15] = x - wx + hx - dx;
    v[16] = y - wy + hy - dy;
    v[17] = z - wz + hz - dz;
    //v7
    v[18] = x - wx - hx + dx;
    v[19] = y - wy - hy + dy;
    v[20] = z - wz - hz + dz;
    //v8
    v[21] = x - wx - hx - dx;
    v[22] = y - wy - hy - dy;
    v[23] = z - wz - hz - dz;
 
    var w = di[9] < 0 ? -di[9] : di[9];
    var h = di[10] < 0 ? -di[10] : di[10];
    var d = di[11] < 0 ? -di[11] : di[11];
 
    w = di[12] < 0 ? w - di[12] : w + di[12];
    h = di[13] < 0 ? h - di[13] : h + di[13];
    d = di[14] < 0 ? d - di[14] : d + di[14];
 
    w = di[15] < 0 ? w - di[15] : w + di[15];
    h = di[16] < 0 ? h - di[16] : h + di[16];
    d = di[17] < 0 ? d - di[17] : d + di[17];
 
    var p = OIMO.AABB_PROX;
 
    this.aabb.set(
        this.position.x - w - p, this.position.x + w + p,
        this.position.y - h - p, this.position.y + h + p,
        this.position.z - d - p, this.position.z + d + p
    );
 
    if (this.proxy != null) this.proxy.update();
 
};
/**
 * A sphere shape.
 * @author saharan
 * @author lo-th
 */
 
OIMO.SphereShape = function (config, radius) {
 
    OIMO.Shape.call(this, config);
 
    this.type = OIMO.SHAPE_SPHERE;
 
    // The radius of the shape.
    this.radius = radius;
};
 
OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
 
OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
 
    var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
    out.mass = mass;
    var inertia = mass * this.radius * this.radius * 0.4;
    out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
 
};
 
OIMO.SphereShape.prototype.updateProxy = function () {
 
    var p = OIMO.AABB_PROX;
 
    this.aabb.set(
        this.position.x - this.radius - p, this.position.x + this.radius + p,
        this.position.y - this.radius - p, this.position.y + this.radius + p,
        this.position.z - this.radius - p, this.position.z + this.radius + p
    );
 
    if (this.proxy != null) this.proxy.update();
 
};
/**
 * A cylinder shap.
 * @author saharan
 * @author lo-th
 */
 
OIMO.CylinderShape = function (config, radius, height) {
 
    OIMO.Shape.call(this, config);
 
    this.type = OIMO.SHAPE_CYLINDER;
 
    this.radius = radius;
    this.height = height;
    this.halfHeight = height * 0.5;
 
    this.normalDirection = new OIMO.Vec3();
    this.halfDirection = new OIMO.Vec3();
 
};
 
OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
 
OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
 
    var rsq = this.radius * this.radius;
    var mass = OIMO.PI * rsq * this.height * this.density;
    var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
    var inertiaY = 0.5 * rsq;
    out.mass = mass;
    out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
 
};
 
OIMO.CylinderShape.prototype.updateProxy = function () {
 
    var te = this.rotation.elements;
    var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
 
    xx = te[1] * te[1];
    yy = te[4] * te[4];
    zz = te[7] * te[7];
 
    this.normalDirection.set(te[1], te[4], te[7]);
    this.halfDirection.scale(this.normalDirection, this.halfHeight);
 
    wx = 1 - xx;
    len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
    if (len > 0) len = this.radius / len;
    wx *= len;
    hy = 1 - yy;
    len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
    if (len > 0) len = this.radius / len;
    hy *= len;
    dz = 1 - zz;
    len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
    if (len > 0) len = this.radius / len;
    dz *= len;
 
    w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
    h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
    d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
 
    w = wx < 0 ? w - wx : w + wx;
    h = hy < 0 ? h - hy : h + hy;
    d = dz < 0 ? d - dz : d + dz;
 
    p = OIMO.AABB_PROX;
 
    this.aabb.set(
        this.position.x - w - p, this.position.x + w + p,
        this.position.y - h - p, this.position.y + h + p,
        this.position.z - d - p, this.position.z + d + p
    );
 
    if (this.proxy != null) this.proxy.update();
 
};
/**
 * A tetra shape.
 * @author xprogram
 */
OIMO.TetraShape = function (config, p1, p2, p3, p4) {
    OIMO.Shape.call(this, config);
    this.type = OIMO.SHAPE_TETRA;
 
    // Vertices and faces of tetra
    this.verts = [p1, p2, p3, p4];
    this.faces = [
      mtri(0, 1, 2),
      mtri(1, 2, 3),
      mtri(2, 3, 4),
      mtri(4, 0, 1),
    ];
};
OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
 
OIMO.TetraShape.prototype.calculateMassInfo = function () {
    // I guess you could calculate box mass and split it
    // in half for the tetra...
};
OIMO.TetraShape.prototype.updateProxy = function () {
    this.aabb.setFromPoints(this.verts);
 
    if (this.proxy !== null)
        this.proxy.update();
};
 
function mtri(a, b, c) {
    return { a: a, b: b, c: c };
}
 
OIMO.CollisionDetector = function () {
 
    this.flip = false;
 
};
 
OIMO.CollisionDetector.prototype = {
 
    constructor: OIMO.CollisionDetector,
 
    detectCollision: function (shape1, shape2, manifold) {
 
        OIMO.Error("CollisionDetector", "Inheritance error.");
 
    }
 
};
/**
 * A collision detector which detects collisions between two boxes.
 * @author saharan
 */
OIMO.BoxBoxCollisionDetector = function () {
 
    OIMO.CollisionDetector.call(this);
    this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
    this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
    this.used = new OIMO_ARRAY_TYPE(8);
 
    this.INF = 1 / 0;
 
};
 
OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
 
OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
    // What you are doing 
    // · I to prepare a separate axis of the fifteen 
    //-Six in each of three normal vectors of the xyz direction of the box both 
    // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1 
    // · Calculate the depth to the separation axis 
 
    // Calculates the distance using the inner product and put the amount of embedment 
    // · However a vertical separation axis and side to weight a little to avoid vibration 
    // And end when there is a separate axis that is remote even one 
    // · I look for separation axis with little to dent most 
    // Men and if separation axis of the first six - end collision 
    // Heng If it separate axis of nine other - side collision 
    // Heng - case of a side collision 
    // · Find points of two sides on which you made ​​the separation axis 
 
    // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point 
    //-Surface - the case of the plane crash 
    //-Box A, box B and the other a box of better made ​​a separate axis 
    // • The surface A and the plane that made the separation axis of the box A, and B to the surface the face of the box B close in the opposite direction to the most isolated axis 
 
    // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B 
    //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B 
    // • If more than one candidate 5 exists, scraping up to four 
 
    // For potential collision points of all, to examine the distance between the surface A 
    // • If you were on the inside surface of A, and the collision point
 
    var b1;
    var b2;
    if (shape1.id < shape2.id) {
        b1 = (shape1);
        b2 = (shape2);
    } else {
        b1 = (shape2);
        b2 = (shape1);
    }
    var V1 = b1.elements;
    var V2 = b2.elements;
 
    var D1 = b1.dimentions;
    var D2 = b2.dimentions;
 
    var p1 = b1.position;
    var p2 = b2.position;
    var p1x = p1.x;
    var p1y = p1.y;
    var p1z = p1.z;
    var p2x = p2.x;
    var p2y = p2.y;
    var p2z = p2.z;
    // diff
    var dx = p2x - p1x;
    var dy = p2y - p1y;
    var dz = p2z - p1z;
    // distance
    var w1 = b1.halfWidth;
    var h1 = b1.halfHeight;
    var d1 = b1.halfDepth;
    var w2 = b2.halfWidth;
    var h2 = b2.halfHeight;
    var d2 = b2.halfDepth;
    // direction
 
    // ----------------------------
    // 15 separating axes
    // 1~6: face
    // 7~f: edge
    // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
    // ----------------------------
 
    var a1x = D1[0];
    var a1y = D1[1];
    var a1z = D1[2];
    var a2x = D1[3];
    var a2y = D1[4];
    var a2z = D1[5];
    var a3x = D1[6];
    var a3y = D1[7];
    var a3z = D1[8];
    var d1x = D1[9];
    var d1y = D1[10];
    var d1z = D1[11];
    var d2x = D1[12];
    var d2y = D1[13];
    var d2z = D1[14];
    var d3x = D1[15];
    var d3y = D1[16];
    var d3z = D1[17];
 
    var a4x = D2[0];
    var a4y = D2[1];
    var a4z = D2[2];
    var a5x = D2[3];
    var a5y = D2[4];
    var a5z = D2[5];
    var a6x = D2[6];
    var a6y = D2[7];
    var a6z = D2[8];
    var d4x = D2[9];
    var d4y = D2[10];
    var d4z = D2[11];
    var d5x = D2[12];
    var d5y = D2[13];
    var d5z = D2[14];
    var d6x = D2[15];
    var d6y = D2[16];
    var d6z = D2[17];
 
    var a7x = a1y * a4z - a1z * a4y;
    var a7y = a1z * a4x - a1x * a4z;
    var a7z = a1x * a4y - a1y * a4x;
    var a8x = a1y * a5z - a1z * a5y;
    var a8y = a1z * a5x - a1x * a5z;
    var a8z = a1x * a5y - a1y * a5x;
    var a9x = a1y * a6z - a1z * a6y;
    var a9y = a1z * a6x - a1x * a6z;
    var a9z = a1x * a6y - a1y * a6x;
    var aax = a2y * a4z - a2z * a4y;
    var aay = a2z * a4x - a2x * a4z;
    var aaz = a2x * a4y - a2y * a4x;
    var abx = a2y * a5z - a2z * a5y;
    var aby = a2z * a5x - a2x * a5z;
    var abz = a2x * a5y - a2y * a5x;
    var acx = a2y * a6z - a2z * a6y;
    var acy = a2z * a6x - a2x * a6z;
    var acz = a2x * a6y - a2y * a6x;
    var adx = a3y * a4z - a3z * a4y;
    var ady = a3z * a4x - a3x * a4z;
    var adz = a3x * a4y - a3y * a4x;
    var aex = a3y * a5z - a3z * a5y;
    var aey = a3z * a5x - a3x * a5z;
    var aez = a3x * a5y - a3y * a5x;
    var afx = a3y * a6z - a3z * a6y;
    var afy = a3z * a6x - a3x * a6z;
    var afz = a3x * a6y - a3y * a6x;
    // right or left flags
    var right1;
    var right2;
    var right3;
    var right4;
    var right5;
    var right6;
    var right7;
    var right8;
    var right9;
    var righta;
    var rightb;
    var rightc;
    var rightd;
    var righte;
    var rightf;
    // overlapping distances
    var overlap1;
    var overlap2;
    var overlap3;
    var overlap4;
    var overlap5;
    var overlap6;
    var overlap7;
    var overlap8;
    var overlap9;
    var overlapa;
    var overlapb;
    var overlapc;
    var overlapd;
    var overlape;
    var overlapf;
    // invalid flags
    var invalid7 = false;
    var invalid8 = false;
    var invalid9 = false;
    var invalida = false;
    var invalidb = false;
    var invalidc = false;
    var invalidd = false;
    var invalide = false;
    var invalidf = false;
    // temporary variables
    var len;
    var len1;
    var len2;
    var dot1;
    var dot2;
    var dot3;
    // try axis 1
    len = a1x * dx + a1y * dy + a1z * dz;
    right1 = len > 0;
    if (!right1) len = -len;
    len1 = w1;
    dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
    dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
    dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
    if (dot1 < 0) dot1 = -dot1;
    if (dot2 < 0) dot2 = -dot2;
    if (dot3 < 0) dot3 = -dot3;
    len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
    overlap1 = len - len1 - len2;
    if (overlap1 > 0) return;
    // try axis 2
    len = a2x * dx + a2y * dy + a2z * dz;
    right2 = len > 0;
    if (!right2) len = -len;
    len1 = h1;
    dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
    dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
    dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
    if (dot1 < 0) dot1 = -dot1;
    if (dot2 < 0) dot2 = -dot2;
    if (dot3 < 0) dot3 = -dot3;
    len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
    overlap2 = len - len1 - len2;
    if (overlap2 > 0) return;
    // try axis 3
    len = a3x * dx + a3y * dy + a3z * dz;
    right3 = len > 0;
    if (!right3) len = -len;
    len1 = d1;
    dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
    dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
    dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
    if (dot1 < 0) dot1 = -dot1;
    if (dot2 < 0) dot2 = -dot2;
    if (dot3 < 0) dot3 = -dot3;
    len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
    overlap3 = len - len1 - len2;
    if (overlap3 > 0) return;
    // try axis 4
    len = a4x * dx + a4y * dy + a4z * dz;
    right4 = len > 0;
    if (!right4) len = -len;
    dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
    dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
    dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
    if (dot1 < 0) dot1 = -dot1;
    if (dot2 < 0) dot2 = -dot2;
    if (dot3 < 0) dot3 = -dot3;
    len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
    len2 = w2;
    overlap4 = (len - len1 - len2) * 1.0;
    if (overlap4 > 0) return;
    // try axis 5
    len = a5x * dx + a5y * dy + a5z * dz;
    right5 = len > 0;
    if (!right5) len = -len;
    dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
    dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
    dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
    if (dot1 < 0) dot1 = -dot1;
    if (dot2 < 0) dot2 = -dot2;
    if (dot3 < 0) dot3 = -dot3;
    len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
    len2 = h2;
    overlap5 = (len - len1 - len2) * 1.0;
    if (overlap5 > 0) return;
    // try axis 6
    len = a6x * dx + a6y * dy + a6z * dz;
    right6 = len > 0;
    if (!right6) len = -len;
    dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
    dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
    dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
    if (dot1 < 0) dot1 = -dot1;
    if (dot2 < 0) dot2 = -dot2;
    if (dot3 < 0) dot3 = -dot3;
    len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
    len2 = d2;
    overlap6 = (len - len1 - len2) * 1.0;
    if (overlap6 > 0) return;
    // try axis 7
    len = a7x * a7x + a7y * a7y + a7z * a7z;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        a7x *= len;
        a7y *= len;
        a7z *= len;
        len = a7x * dx + a7y * dy + a7z * dz;
        right7 = len > 0;
        if (!right7) len = -len;
        dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
        dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * h1 + dot2 * d1;
        dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
        dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * h2 + dot2 * d2;
        overlap7 = len - len1 - len2;
        if (overlap7 > 0) return;
    } else {
        right7 = false;
        overlap7 = 0;
        invalid7 = true;
    }
    // try axis 8
    len = a8x * a8x + a8y * a8y + a8z * a8z;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        a8x *= len;
        a8y *= len;
        a8z *= len;
        len = a8x * dx + a8y * dy + a8z * dz;
        right8 = len > 0;
        if (!right8) len = -len;
        dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
        dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * h1 + dot2 * d1;
        dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
        dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * w2 + dot2 * d2;
        overlap8 = len - len1 - len2;
        if (overlap8 > 0) return;
    } else {
        right8 = false;
        overlap8 = 0;
        invalid8 = true;
    }
    // try axis 9
    len = a9x * a9x + a9y * a9y + a9z * a9z;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        a9x *= len;
        a9y *= len;
        a9z *= len;
        len = a9x * dx + a9y * dy + a9z * dz;
        right9 = len > 0;
        if (!right9) len = -len;
        dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
        dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * h1 + dot2 * d1;
        dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
        dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * w2 + dot2 * h2;
        overlap9 = len - len1 - len2;
        if (overlap9 > 0) return;
    } else {
        right9 = false;
        overlap9 = 0;
        invalid9 = true;
    }
    // try axis 10
    len = aax * aax + aay * aay + aaz * aaz;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        aax *= len;
        aay *= len;
        aaz *= len;
        len = aax * dx + aay * dy + aaz * dz;
        righta = len > 0;
        if (!righta) len = -len;
        dot1 = aax * a1x + aay * a1y + aaz * a1z;
        dot2 = aax * a3x + aay * a3y + aaz * a3z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * w1 + dot2 * d1;
        dot1 = aax * a5x + aay * a5y + aaz * a5z;
        dot2 = aax * a6x + aay * a6y + aaz * a6z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * h2 + dot2 * d2;
        overlapa = len - len1 - len2;
        if (overlapa > 0) return;
    } else {
        righta = false;
        overlapa = 0;
        invalida = true;
    }
    // try axis 11
    len = abx * abx + aby * aby + abz * abz;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        abx *= len;
        aby *= len;
        abz *= len;
        len = abx * dx + aby * dy + abz * dz;
        rightb = len > 0;
        if (!rightb) len = -len;
        dot1 = abx * a1x + aby * a1y + abz * a1z;
        dot2 = abx * a3x + aby * a3y + abz * a3z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * w1 + dot2 * d1;
        dot1 = abx * a4x + aby * a4y + abz * a4z;
        dot2 = abx * a6x + aby * a6y + abz * a6z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * w2 + dot2 * d2;
        overlapb = len - len1 - len2;
        if (overlapb > 0) return;
    } else {
        rightb = false;
        overlapb = 0;
        invalidb = true;
    }
    // try axis 12
    len = acx * acx + acy * acy + acz * acz;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        acx *= len;
        acy *= len;
        acz *= len;
        len = acx * dx + acy * dy + acz * dz;
        rightc = len > 0;
        if (!rightc) len = -len;
        dot1 = acx * a1x + acy * a1y + acz * a1z;
        dot2 = acx * a3x + acy * a3y + acz * a3z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * w1 + dot2 * d1;
        dot1 = acx * a4x + acy * a4y + acz * a4z;
        dot2 = acx * a5x + acy * a5y + acz * a5z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * w2 + dot2 * h2;
        overlapc = len - len1 - len2;
        if (overlapc > 0) return;
    } else {
        rightc = false;
        overlapc = 0;
        invalidc = true;
    }
    // try axis 13
    len = adx * adx + ady * ady + adz * adz;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        adx *= len;
        ady *= len;
        adz *= len;
        len = adx * dx + ady * dy + adz * dz;
        rightd = len > 0;
        if (!rightd) len = -len;
        dot1 = adx * a1x + ady * a1y + adz * a1z;
        dot2 = adx * a2x + ady * a2y + adz * a2z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * w1 + dot2 * h1;
        dot1 = adx * a5x + ady * a5y + adz * a5z;
        dot2 = adx * a6x + ady * a6y + adz * a6z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * h2 + dot2 * d2;
        overlapd = len - len1 - len2;
        if (overlapd > 0) return;
    } else {
        rightd = false;
        overlapd = 0;
        invalidd = true;
    }
    // try axis 14
    len = aex * aex + aey * aey + aez * aez;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        aex *= len;
        aey *= len;
        aez *= len;
        len = aex * dx + aey * dy + aez * dz;
        righte = len > 0;
        if (!righte) len = -len;
        dot1 = aex * a1x + aey * a1y + aez * a1z;
        dot2 = aex * a2x + aey * a2y + aez * a2z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * w1 + dot2 * h1;
        dot1 = aex * a4x + aey * a4y + aez * a4z;
        dot2 = aex * a6x + aey * a6y + aez * a6z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * w2 + dot2 * d2;
        overlape = len - len1 - len2;
        if (overlape > 0) return;
    } else {
        righte = false;
        overlape = 0;
        invalide = true;
    }
    // try axis 15
    len = afx * afx + afy * afy + afz * afz;
    if (len > 1e-5) {
        len = 1 / OIMO.sqrt(len);
        afx *= len;
        afy *= len;
        afz *= len;
        len = afx * dx + afy * dy + afz * dz;
        rightf = len > 0;
        if (!rightf) len = -len;
        dot1 = afx * a1x + afy * a1y + afz * a1z;
        dot2 = afx * a2x + afy * a2y + afz * a2z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len1 = dot1 * w1 + dot2 * h1;
        dot1 = afx * a4x + afy * a4y + afz * a4z;
        dot2 = afx * a5x + afy * a5y + afz * a5z;
        if (dot1 < 0) dot1 = -dot1;
        if (dot2 < 0) dot2 = -dot2;
        len2 = dot1 * w2 + dot2 * h2;
        overlapf = len - len1 - len2;
        if (overlapf > 0) return;
    } else {
        rightf = false;
        overlapf = 0;
        invalidf = true;
    }
    // boxes are overlapping
    var depth = overlap1;
    var depth2 = overlap1;
    var minIndex = 0;
    var right = right1;
    if (overlap2 > depth2) {
        depth = overlap2;
        depth2 = overlap2;
        minIndex = 1;
        right = right2;
    }
    if (overlap3 > depth2) {
        depth = overlap3;
        depth2 = overlap3;
        minIndex = 2;
        right = right3;
    }
    if (overlap4 > depth2) {
        depth = overlap4;
        depth2 = overlap4;
        minIndex = 3;
        right = right4;
    }
    if (overlap5 > depth2) {
        depth = overlap5;
        depth2 = overlap5;
        minIndex = 4;
        right = right5;
    }
    if (overlap6 > depth2) {
        depth = overlap6;
        depth2 = overlap6;
        minIndex = 5;
        right = right6;
    }
    if (overlap7 - 0.01 > depth2 && !invalid7) {
        depth = overlap7;
        depth2 = overlap7 - 0.01;
        minIndex = 6;
        right = right7;
    }
    if (overlap8 - 0.01 > depth2 && !invalid8) {
        depth = overlap8;
        depth2 = overlap8 - 0.01;
        minIndex = 7;
        right = right8;
    }
    if (overlap9 - 0.01 > depth2 && !invalid9) {
        depth = overlap9;
        depth2 = overlap9 - 0.01;
        minIndex = 8;
        right = right9;
    }
    if (overlapa - 0.01 > depth2 && !invalida) {
        depth = overlapa;
        depth2 = overlapa - 0.01;
        minIndex = 9;
        right = righta;
    }
    if (overlapb - 0.01 > depth2 && !invalidb) {
        depth = overlapb;
        depth2 = overlapb - 0.01;
        minIndex = 10;
        right = rightb;
    }
    if (overlapc - 0.01 > depth2 && !invalidc) {
        depth = overlapc;
        depth2 = overlapc - 0.01;
        minIndex = 11;
        right = rightc;
    }
    if (overlapd - 0.01 > depth2 && !invalidd) {
        depth = overlapd;
        depth2 = overlapd - 0.01;
        minIndex = 12;
        right = rightd;
    }
    if (overlape - 0.01 > depth2 && !invalide) {
        depth = overlape;
        depth2 = overlape - 0.01;
        minIndex = 13;
        right = righte;
    }
    if (overlapf - 0.01 > depth2 && !invalidf) {
        depth = overlapf;
        minIndex = 14;
        right = rightf;
    }
    // normal
    var nx = 0;
    var ny = 0;
    var nz = 0;
    // edge line or face side normal
    var n1x = 0;
    var n1y = 0;
    var n1z = 0;
    var n2x = 0;
    var n2y = 0;
    var n2z = 0;
    // center of current face
    var cx = 0;
    var cy = 0;
    var cz = 0;
    // face side
    var s1x = 0;
    var s1y = 0;
    var s1z = 0;
    var s2x = 0;
    var s2y = 0;
    var s2z = 0;
    // swap b1 b2
    var swap = false;
 
    //_______________________________________
 
    if (minIndex == 0) {// b1.x * b2
        if (right) {
            cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
            nx = a1x; ny = a1y; nz = a1z;
        } else {
            cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
            nx = -a1x; ny = -a1y; nz = -a1z;
        }
        s1x = d2x; s1y = d2y; s1z = d2z;
        n1x = -a2x; n1y = -a2y; n1z = -a2z;
        s2x = d3x; s2y = d3y; s2z = d3z;
        n2x = -a3x; n2y = -a3y; n2z = -a3z;
    }
    else if (minIndex == 1) {// b1.y * b2
        if (right) {
            cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
            nx = a2x; ny = a2y; nz = a2z;
        } else {
            cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
            nx = -a2x; ny = -a2y; nz = -a2z;
        }
        s1x = d1x; s1y = d1y; s1z = d1z;
        n1x = -a1x; n1y = -a1y; n1z = -a1z;
        s2x = d3x; s2y = d3y; s2z = d3z;
        n2x = -a3x; n2y = -a3y; n2z = -a3z;
    }
    else if (minIndex == 2) {// b1.z * b2
        if (right) {
            cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
            nx = a3x; ny = a3y; nz = a3z;
        } else {
            cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
            nx = -a3x; ny = -a3y; nz = -a3z;
        }
        s1x = d1x; s1y = d1y; s1z = d1z;
        n1x = -a1x; n1y = -a1y; n1z = -a1z;
        s2x = d2x; s2y = d2y; s2z = d2z;
        n2x = -a2x; n2y = -a2y; n2z = -a2z;
    }
    else if (minIndex == 3) {// b2.x * b1
        swap = true;
        if (!right) {
            cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
            nx = a4x; ny = a4y; nz = a4z;
        } else {
            cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
            nx = -a4x; ny = -a4y; nz = -a4z;
        }
        s1x = d5x; s1y = d5y; s1z = d5z;
        n1x = -a5x; n1y = -a5y; n1z = -a5z;
        s2x = d6x; s2y = d6y; s2z = d6z;
        n2x = -a6x; n2y = -a6y; n2z = -a6z;
    }
    else if (minIndex == 4) {// b2.y * b1
        swap = true;
        if (!right) {
            cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
            nx = a5x; ny = a5y; nz = a5z;
        } else {
            cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
            nx = -a5x; ny = -a5y; nz = -a5z;
        }
        s1x = d4x; s1y = d4y; s1z = d4z;
        n1x = -a4x; n1y = -a4y; n1z = -a4z;
        s2x = d6x; s2y = d6y; s2z = d6z;
        n2x = -a6x; n2y = -a6y; n2z = -a6z;
    }
    else if (minIndex == 5) {// b2.z * b1
        swap = true;
        if (!right) {
            cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
            nx = a6x; ny = a6y; nz = a6z;
        } else {
            cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
            nx = -a6x; ny = -a6y; nz = -a6z;
        }
        s1x = d4x; s1y = d4y; s1z = d4z;
        n1x = -a4x; n1y = -a4y; n1z = -a4z;
        s2x = d5x; s2y = d5y; s2z = d5z;
        n2x = -a5x; n2y = -a5y; n2z = -a5z;
    }
    else if (minIndex == 6) {// b1.x * b2.x
        nx = a7x; ny = a7y; nz = a7z;
        n1x = a1x; n1y = a1y; n1z = a1z;
        n2x = a4x; n2y = a4y; n2z = a4z;
    }
    else if (minIndex == 7) {// b1.x * b2.y
        nx = a8x; ny = a8y; nz = a8z;
        n1x = a1x; n1y = a1y; n1z = a1z;
        n2x = a5x; n2y = a5y; n2z = a5z;
    }
    else if (minIndex == 8) {// b1.x * b2.z
        nx = a9x; ny = a9y; nz = a9z;
        n1x = a1x; n1y = a1y; n1z = a1z;
        n2x = a6x; n2y = a6y; n2z = a6z;
    }
    else if (minIndex == 9) {// b1.y * b2.x
        nx = aax; ny = aay; nz = aaz;
        n1x = a2x; n1y = a2y; n1z = a2z;
        n2x = a4x; n2y = a4y; n2z = a4z
    }
    else if (minIndex == 10) {// b1.y * b2.y
        nx = abx; ny = aby; nz = abz;
        n1x = a2x; n1y = a2y; n1z = a2z;
        n2x = a5x; n2y = a5y; n2z = a5z;
    }
    else if (minIndex == 11) {// b1.y * b2.z
        nx = acx; ny = acy; nz = acz;
        n1x = a2x; n1y = a2y; n1z = a2z;
        n2x = a6x; n2y = a6y; n2z = a6z;
    }
    else if (minIndex == 12) {// b1.z * b2.x
        nx = adx; ny = ady; nz = adz;
        n1x = a3x; n1y = a3y; n1z = a3z;
        n2x = a4x; n2y = a4y; n2z = a4z;
    }
    else if (minIndex == 13) {// b1.z * b2.y
        nx = aex; ny = aey; nz = aez;
        n1x = a3x; n1y = a3y; n1z = a3z;
        n2x = a5x; n2y = a5y; n2z = a5z;
    }
    else if (minIndex == 14) {// b1.z * b2.z
        nx = afx; ny = afy; nz = afz;
        n1x = a3x; n1y = a3y; n1z = a3z;
        n2x = a6x; n2y = a6y; n2z = a6z;
    }
 
    //__________________________________________
 
    var v;
    if (minIndex > 5) {
        if (!right) {
            nx = -nx; ny = -ny; nz = -nz;
        }
        var distance;
        var maxDistance;
        var vx;
        var vy;
        var vz;
        var v1x;
        var v1y;
        var v1z;
        var v2x;
        var v2y;
        var v2z;
        //vertex1;
        v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
        maxDistance = nx * v1x + ny * v1y + nz * v1z;
        //vertex2;
        vx = V1[3]; vy = V1[4]; vz = V1[5];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex3;
        vx = V1[6]; vy = V1[7]; vz = V1[8];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex4;
        vx = V1[9]; vy = V1[10]; vz = V1[11];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex5;
        vx = V1[12]; vy = V1[13]; vz = V1[14];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex6;
        vx = V1[15]; vy = V1[16]; vz = V1[17];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex7;
        vx = V1[18]; vy = V1[19]; vz = V1[20];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex8;
        vx = V1[21]; vy = V1[22]; vz = V1[23];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance > maxDistance) {
            maxDistance = distance;
            v1x = vx; v1y = vy; v1z = vz;
        }
        //vertex1;
        v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
        maxDistance = nx * v2x + ny * v2y + nz * v2z;
        //vertex2;
        vx = V2[3]; vy = V2[4]; vz = V2[5];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        //vertex3;
        vx = V2[6]; vy = V2[7]; vz = V2[8];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        //vertex4;
        vx = V2[9]; vy = V2[10]; vz = V2[11];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        //vertex5;
        vx = V2[12]; vy = V2[13]; vz = V2[14];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        //vertex6;
        vx = V2[15]; vy = V2[16]; vz = V2[17];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        //vertex7;
        vx = V2[18]; vy = V2[19]; vz = V2[20];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        //vertex8;
        vx = V2[21]; vy = V2[22]; vz = V2[23];
        distance = nx * vx + ny * vy + nz * vz;
        if (distance < maxDistance) {
            maxDistance = distance;
            v2x = vx; v2y = vy; v2z = vz;
        }
        vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
        dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
        var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
        manifold.addPoint(v1x + n1x * t + nx * depth * 0.5, v1y + n1y * t + ny * depth * 0.5, v1z + n1z * t + nz * depth * 0.5, nx, ny, nz, depth, false);
        return;
    }
    // now detect face-face collision...
    // target quad
    var q1x;
    var q1y;
    var q1z;
    var q2x;
    var q2y;
    var q2z;
    var q3x;
    var q3y;
    var q3z;
    var q4x;
    var q4y;
    var q4z;
    // search support face and vertex
    var minDot = 1;
    var dot = 0;
    var minDotIndex = 0;
    if (swap) {
        dot = a1x * nx + a1y * ny + a1z * nz;
        if (dot < minDot) {
            minDot = dot;
            minDotIndex = 0;
        }
        if (-dot < minDot) {
            minDot = -dot;
            minDotIndex = 1;
        }
        dot = a2x * nx + a2y * ny + a2z * nz;
        if (dot < minDot) {
            minDot = dot;
            minDotIndex = 2;
        }
        if (-dot < minDot) {
            minDot = -dot;
            minDotIndex = 3;
        }
        dot = a3x * nx + a3y * ny + a3z * nz;
        if (dot < minDot) {
            minDot = dot;
            minDotIndex = 4;
        }
        if (-dot < minDot) {
            minDot = -dot;
            minDotIndex = 5;
        }
 
        if (minDotIndex == 0) {// x+ face
            q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
            q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
            q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
            q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
        }
        else if (minDotIndex == 1) {// x- face
            q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
            q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
            q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
            q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
        }
        else if (minDotIndex == 2) {// y+ face
            q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
            q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
            q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
            q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
        }
        else if (minDotIndex == 3) {// y- face
            q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
            q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
            q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
            q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
        }
        else if (minDotIndex == 4) {// z+ face
            q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
            q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
            q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
            q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
        }
        else if (minDotIndex == 5) {// z- face
            q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
            q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
            q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
            q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
        }
 
    } else {
        dot = a4x * nx + a4y * ny + a4z * nz;
        if (dot < minDot) {
            minDot = dot;
            minDotIndex = 0;
        }
        if (-dot < minDot) {
            minDot = -dot;
            minDotIndex = 1;
        }
        dot = a5x * nx + a5y * ny + a5z * nz;
        if (dot < minDot) {
            minDot = dot;
            minDotIndex = 2;
        }
        if (-dot < minDot) {
            minDot = -dot;
            minDotIndex = 3;
        }
        dot = a6x * nx + a6y * ny + a6z * nz;
        if (dot < minDot) {
            minDot = dot;
            minDotIndex = 4;
        }
        if (-dot < minDot) {
            minDot = -dot;
            minDotIndex = 5;
        }
 
        //______________________________________________________
 
        if (minDotIndex == 0) {// x+ face
            q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
            q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
            q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
            q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
        }
        else if (minDotIndex == 1) {// x- face
            q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
            q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
            q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
            q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
        }
        else if (minDotIndex == 2) {// y+ face
            q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
            q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
            q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
            q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
        }
        else if (minDotIndex == 3) {// y- face
            q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
            q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
            q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
            q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
        }
        else if (minDotIndex == 4) {// z+ face
            q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
            q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
            q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
            q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
        }
        else if (minDotIndex == 5) {// z- face
            q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
            q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
            q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
            q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
        }
 
    }
    // clip vertices
    var numClipVertices;
    var numAddedClipVertices;
    var index;
    var x1;
    var y1;
    var z1;
    var x2;
    var y2;
    var z2;
    this.clipVertices1[0] = q1x;
    this.clipVertices1[1] = q1y;
    this.clipVertices1[2] = q1z;
    this.clipVertices1[3] = q2x;
    this.clipVertices1[4] = q2y;
    this.clipVertices1[5] = q2z;
    this.clipVertices1[6] = q3x;
    this.clipVertices1[7] = q3y;
    this.clipVertices1[8] = q3z;
    this.clipVertices1[9] = q4x;
    this.clipVertices1[10] = q4y;
    this.clipVertices1[11] = q4z;
    numAddedClipVertices = 0;
    x1 = this.clipVertices1[9];
    y1 = this.clipVertices1[10];
    z1 = this.clipVertices1[11];
    dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
 
    //var i = 4;
    //while(i--){
    for (var i = 0; i < 4; i++) {
        index = i * 3;
        x2 = this.clipVertices1[index];
        y2 = this.clipVertices1[index + 1];
        z2 = this.clipVertices1[index + 2];
        dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
        if (dot1 > 0) {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices2[index] = x2;
                this.clipVertices2[index + 1] = y2;
                this.clipVertices2[index + 2] = z2;
            } else {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices2[index] = x1 + (x2 - x1) * t;
                this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
            }
        } else {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices2[index] = x1 + (x2 - x1) * t;
                this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices2[index] = x2;
                this.clipVertices2[index + 1] = y2;
                this.clipVertices2[index + 2] = z2;
            }
        }
        x1 = x2;
        y1 = y2;
        z1 = z2;
        dot1 = dot2;
    }
 
    numClipVertices = numAddedClipVertices;
    if (numClipVertices == 0) return;
    numAddedClipVertices = 0;
    index = (numClipVertices - 1) * 3;
    x1 = this.clipVertices2[index];
    y1 = this.clipVertices2[index + 1];
    z1 = this.clipVertices2[index + 2];
    dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
 
    //i = numClipVertices;
    //while(i--){
    for (i = 0; i < numClipVertices; i++) {
        index = i * 3;
        x2 = this.clipVertices2[index];
        y2 = this.clipVertices2[index + 1];
        z2 = this.clipVertices2[index + 2];
        dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
        if (dot1 > 0) {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices1[index] = x2;
                this.clipVertices1[index + 1] = y2;
                this.clipVertices1[index + 2] = z2;
            } else {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices1[index] = x1 + (x2 - x1) * t;
                this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
            }
        } else {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices1[index] = x1 + (x2 - x1) * t;
                this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices1[index] = x2;
                this.clipVertices1[index + 1] = y2;
                this.clipVertices1[index + 2] = z2;
            }
        }
        x1 = x2;
        y1 = y2;
        z1 = z2;
        dot1 = dot2;
    }
 
    numClipVertices = numAddedClipVertices;
    if (numClipVertices == 0) return;
    numAddedClipVertices = 0;
    index = (numClipVertices - 1) * 3;
    x1 = this.clipVertices1[index];
    y1 = this.clipVertices1[index + 1];
    z1 = this.clipVertices1[index + 2];
    dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
 
    //i = numClipVertices;
    //while(i--){
    for (i = 0; i < numClipVertices; i++) {
        index = i * 3;
        x2 = this.clipVertices1[index];
        y2 = this.clipVertices1[index + 1];
        z2 = this.clipVertices1[index + 2];
        dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
        if (dot1 > 0) {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices2[index] = x2;
                this.clipVertices2[index + 1] = y2;
                this.clipVertices2[index + 2] = z2;
            } else {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices2[index] = x1 + (x2 - x1) * t;
                this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
            }
        } else {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices2[index] = x1 + (x2 - x1) * t;
                this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices2[index] = x2;
                this.clipVertices2[index + 1] = y2;
                this.clipVertices2[index + 2] = z2;
            }
        }
        x1 = x2;
        y1 = y2;
        z1 = z2;
        dot1 = dot2;
    }
 
    numClipVertices = numAddedClipVertices;
    if (numClipVertices == 0) return;
    numAddedClipVertices = 0;
    index = (numClipVertices - 1) * 3;
    x1 = this.clipVertices2[index];
    y1 = this.clipVertices2[index + 1];
    z1 = this.clipVertices2[index + 2];
    dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
 
    //i = numClipVertices;
    //while(i--){
    for (i = 0; i < numClipVertices; i++) {
        index = i * 3;
        x2 = this.clipVertices2[index];
        y2 = this.clipVertices2[index + 1];
        z2 = this.clipVertices2[index + 2];
        dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
        if (dot1 > 0) {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices1[index] = x2;
                this.clipVertices1[index + 1] = y2;
                this.clipVertices1[index + 2] = z2;
            } else {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices1[index] = x1 + (x2 - x1) * t;
                this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
            }
        } else {
            if (dot2 > 0) {
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                t = dot1 / (dot1 - dot2);
                this.clipVertices1[index] = x1 + (x2 - x1) * t;
                this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
                this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
                index = numAddedClipVertices * 3;
                numAddedClipVertices++;
                this.clipVertices1[index] = x2;
                this.clipVertices1[index + 1] = y2;
                this.clipVertices1[index + 2] = z2;
            }
        }
        x1 = x2;
        y1 = y2;
        z1 = z2;
        dot1 = dot2;
    }
 
    numClipVertices = numAddedClipVertices;
    if (swap) {
        var tb = b1;
        b1 = b2;
        b2 = tb;
    }
    if (numClipVertices == 0) return;
    var flipped = b1 != shape1;
    if (numClipVertices > 4) {
        x1 = (q1x + q2x + q3x + q4x) * 0.25;
        y1 = (q1y + q2y + q3y + q4y) * 0.25;
        z1 = (q1z + q2z + q3z + q4z) * 0.25;
        n1x = q1x - x1;
        n1y = q1y - y1;
        n1z = q1z - z1;
        n2x = q2x - x1;
        n2y = q2y - y1;
        n2z = q2z - z1;
        var index1 = 0;
        var index2 = 0;
        var index3 = 0;
        var index4 = 0;
        var maxDot = -this.INF;
        minDot = this.INF;
 
        //i = numClipVertices;
        //while(i--){
        for (i = 0; i < numClipVertices; i++) {
            this.used[i] = false;
            index = i * 3;
            x1 = this.clipVertices1[index];
            y1 = this.clipVertices1[index + 1];
            z1 = this.clipVertices1[index + 2];
            dot = x1 * n1x + y1 * n1y + z1 * n1z;
            if (dot < minDot) {
                minDot = dot;
                index1 = i;
            }
            if (dot > maxDot) {
                maxDot = dot;
                index3 = i;
            }
        }
 
        this.used[index1] = true;
        this.used[index3] = true;
        maxDot = -this.INF;
        minDot = this.INF;
 
        //i = numClipVertices;
        //while(i--){
        for (i = 0; i < numClipVertices; i++) {
            if (this.used[i]) continue;
            index = i * 3;
            x1 = this.clipVertices1[index];
            y1 = this.clipVertices1[index + 1];
            z1 = this.clipVertices1[index + 2];
            dot = x1 * n2x + y1 * n2y + z1 * n2z;
            if (dot < minDot) {
                minDot = dot;
                index2 = i;
            }
            if (dot > maxDot) {
                maxDot = dot;
                index4 = i;
            }
        }
 
        index = index1 * 3;
        x1 = this.clipVertices1[index];
        y1 = this.clipVertices1[index + 1];
        z1 = this.clipVertices1[index + 2];
        dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
        if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
 
        index = index2 * 3;
        x1 = this.clipVertices1[index];
        y1 = this.clipVertices1[index + 1];
        z1 = this.clipVertices1[index + 2];
        dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
        if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
 
        index = index3 * 3;
        x1 = this.clipVertices1[index];
        y1 = this.clipVertices1[index + 1];
        z1 = this.clipVertices1[index + 2];
        dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
        if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
 
        index = index4 * 3;
        x1 = this.clipVertices1[index];
        y1 = this.clipVertices1[index + 1];
        z1 = this.clipVertices1[index + 2];
        dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
        if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
 
    } else {
        //i = numClipVertices;
        //while(i--){
        for (i = 0; i < numClipVertices; i++) {
            index = i * 3;
            x1 = this.clipVertices1[index];
            y1 = this.clipVertices1[index + 1];
            z1 = this.clipVertices1[index + 2];
            dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
            if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
        }
    }
 
};
/**
 * A collision detector which detects collisions between sphere and box.
 * @author saharan
 */
OIMO.SphereBoxCollisionDetector = function (flip) {
 
    OIMO.CollisionDetector.call(this);
    this.flip = flip;
 
};
 
OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
 
OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
 
    var s;
    var b;
    if (this.flip) {
        s = (shape2);
        b = (shape1);
    } else {
        s = (shape1);
        b = (shape2);
    }
 
    var D = b.dimentions;
 
    var ps = s.position;
    var psx = ps.x;
    var psy = ps.y;
    var psz = ps.z;
    var pb = b.position;
    var pbx = pb.x;
    var pby = pb.y;
    var pbz = pb.z;
    var rad = s.radius;
 
    var hw = b.halfWidth;
    var hh = b.halfHeight;
    var hd = b.halfDepth;
 
    var dx = psx - pbx;
    var dy = psy - pby;
    var dz = psz - pbz;
    var sx = D[0] * dx + D[1] * dy + D[2] * dz;
    var sy = D[3] * dx + D[4] * dy + D[5] * dz;
    var sz = D[6] * dx + D[7] * dy + D[8] * dz;
    var cx;
    var cy;
    var cz;
    var len;
    var invLen;
    var overlap = 0;
    if (sx > hw) {
        sx = hw;
    } else if (sx < -hw) {
        sx = -hw;
    } else {
        overlap = 1;
    }
    if (sy > hh) {
        sy = hh;
    } else if (sy < -hh) {
        sy = -hh;
    } else {
        overlap |= 2;
    }
    if (sz > hd) {
        sz = hd;
    } else if (sz < -hd) {
        sz = -hd;
    } else {
        overlap |= 4;
    }
    if (overlap == 7) {
        // center of sphere is in the box
        if (sx < 0) {
            dx = hw + sx;
        } else {
            dx = hw - sx;
        }
        if (sy < 0) {
            dy = hh + sy;
        } else {
            dy = hh - sy;
        }
        if (sz < 0) {
            dz = hd + sz;
        } else {
            dz = hd - sz;
        }
        if (dx < dy) {
            if (dx < dz) {
                len = dx - hw;
                if (sx < 0) {
                    sx = -hw;
                    dx = D[0];
                    dy = D[1];
                    dz = D[2];
                } else {
                    sx = hw;
                    dx = -D[0];
                    dy = -D[1];
                    dz = -D[2];
                }
            } else {
                len = dz - hd;
                if (sz < 0) {
                    sz = -hd;
                    dx = D[6];
                    dy = D[7];
                    dz = D[8];
                } else {
                    sz = hd;
                    dx = -D[6];
                    dy = -D[7];
                    dz = -D[8];
                }
            }
        } else {
            if (dy < dz) {
                len = dy - hh;
                if (sy < 0) {
                    sy = -hh;
                    dx = D[3];
                    dy = D[4];
                    dz = D[5];
                } else {
                    sy = hh;
                    dx = -D[3];
                    dy = -D[4];
                    dz = -D[5];
                }
            } else {
                len = dz - hd;
                if (sz < 0) {
                    sz = -hd;
                    dx = D[6];
                    dy = D[7];
                    dz = D[8];
                } else {
                    sz = hd;
                    dx = -D[6];
                    dy = -D[7];
                    dz = -D[8];
                }
            }
        }
        cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
        cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
        cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
        manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
    } else {
        cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
        cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
        cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
        dx = cx - ps.x;
        dy = cy - ps.y;
        dz = cz - ps.z;
        len = dx * dx + dy * dy + dz * dz;
        if (len > 0 && len < rad * rad) {
            len = OIMO.sqrt(len);
            invLen = 1 / len;
            dx *= invLen;
            dy *= invLen;
            dz *= invLen;
            manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
        }
    }
 
};
/**
 * A collision detector which detects collisions between two spheres.
 * @author saharan
 */
OIMO.SphereSphereCollisionDetector = function () {
 
    OIMO.CollisionDetector.call(this);
 
};
 
OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
 
OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
 
    var s1 = shape1;
    var s2 = shape2;
    var p1 = s1.position;
    var p2 = s2.position;
    var dx = p2.x - p1.x;
    var dy = p2.y - p1.y;
    var dz = p2.z - p1.z;
    var len = dx * dx + dy * dy + dz * dz;
    var r1 = s1.radius;
    var r2 = s2.radius;
    var rad = r1 + r2;
    if (len > 0 && len < rad * rad) {
        len = OIMO.sqrt(len);
        var invLen = 1 / len;
        dx *= invLen;
        dy *= invLen;
        dz *= invLen;
        manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
    }
 
};
OIMO.BoxCylinderCollisionDetector = function (flip) {
    OIMO.CollisionDetector.call(this);
    this.flip = flip;
};
 
OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
 
OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
 
    var t1x;
    var t1y;
    var t1z;
    var t2x;
    var t2y;
    var t2z;
    var sup = new OIMO.Vec3();
    var len;
    var p1x;
    var p1y;
    var p1z;
    var p2x;
    var p2y;
    var p2z;
    var v01x = c1.position.x;
    var v01y = c1.position.y;
    var v01z = c1.position.z;
    var v02x = c2.position.x;
    var v02y = c2.position.y;
    var v02z = c2.position.z;
    var v0x = v02x - v01x;
    var v0y = v02y - v01y;
    var v0z = v02z - v01z;
    if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
    var nx = -v0x;
    var ny = -v0y;
    var nz = -v0z;
    this.supportPointB(c1, -nx, -ny, -nz, sup);
    var v11x = sup.x;
    var v11y = sup.y;
    var v11z = sup.z;
    this.supportPointC(c2, nx, ny, nz, sup);
    var v12x = sup.x;
    var v12y = sup.y;
    var v12z = sup.z;
    var v1x = v12x - v11x;
    var v1y = v12y - v11y;
    var v1z = v12z - v11z;
    if (v1x * nx + v1y * ny + v1z * nz <= 0) {
        return false;
    }
    nx = v1y * v0z - v1z * v0y;
    ny = v1z * v0x - v1x * v0z;
    nz = v1x * v0y - v1y * v0x;
    if (nx * nx + ny * ny + nz * nz == 0) {
        sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
        sep.normalize(sep);
        pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
        return true;
    }
    this.supportPointB(c1, -nx, -ny, -nz, sup);
    var v21x = sup.x;
    var v21y = sup.y;
    var v21z = sup.z;
    this.supportPointC(c2, nx, ny, nz, sup);
    var v22x = sup.x;
    var v22y = sup.y;
    var v22z = sup.z;
    var v2x = v22x - v21x;
    var v2y = v22y - v21y;
    var v2z = v22z - v21z;
    if (v2x * nx + v2y * ny + v2z * nz <= 0) {
        return false;
    }
    t1x = v1x - v0x;
    t1y = v1y - v0y;
    t1z = v1z - v0z;
    t2x = v2x - v0x;
    t2y = v2y - v0y;
    t2z = v2z - v0z;
    nx = t1y * t2z - t1z * t2y;
    ny = t1z * t2x - t1x * t2z;
    nz = t1x * t2y - t1y * t2x;
    if (nx * v0x + ny * v0y + nz * v0z > 0) {
        t1x = v1x;
        t1y = v1y;
        t1z = v1z;
        v1x = v2x;
        v1y = v2y;
        v1z = v2z;
        v2x = t1x;
        v2y = t1y;
        v2z = t1z;
        t1x = v11x;
        t1y = v11y;
        t1z = v11z;
        v11x = v21x;
        v11y = v21y;
        v11z = v21z;
        v21x = t1x;
        v21y = t1y;
        v21z = t1z;
        t1x = v12x;
        t1y = v12y;
        t1z = v12z;
        v12x = v22x;
        v12y = v22y;
        v12z = v22z;
        v22x = t1x;
        v22y = t1y;
        v22z = t1z;
        nx = -nx;
        ny = -ny;
        nz = -nz;
    }
    var iterations = 0;
    while (true) {
        if (++iterations > 100) {
            return false;
        }
        this.supportPointB(c1, -nx, -ny, -nz, sup);
        var v31x = sup.x;
        var v31y = sup.y;
        var v31z = sup.z;
        this.supportPointC(c2, nx, ny, nz, sup);
        var v32x = sup.x;
        var v32y = sup.y;
        var v32z = sup.z;
        var v3x = v32x - v31x;
        var v3y = v32y - v31y;
        var v3z = v32z - v31z;
        if (v3x * nx + v3y * ny + v3z * nz <= 0) {
            return false;
        }
        if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
            v2x = v3x;
            v2y = v3y;
            v2z = v3z;
            v21x = v31x;
            v21y = v31y;
            v21z = v31z;
            v22x = v32x;
            v22y = v32y;
            v22z = v32z;
            t1x = v1x - v0x;
            t1y = v1y - v0y;
            t1z = v1z - v0z;
            t2x = v3x - v0x;
            t2y = v3y - v0y;
            t2z = v3z - v0z;
            nx = t1y * t2z - t1z * t2y;
            ny = t1z * t2x - t1x * t2z;
            nz = t1x * t2y - t1y * t2x;
            continue;
        }
        if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
            v1x = v3x;
            v1y = v3y;
            v1z = v3z;
            v11x = v31x;
            v11y = v31y;
            v11z = v31z;
            v12x = v32x;
            v12y = v32y;
            v12z = v32z;
            t1x = v3x - v0x;
            t1y = v3y - v0y;
            t1z = v3z - v0z;
            t2x = v2x - v0x;
            t2y = v2y - v0y;
            t2z = v2z - v0z;
            nx = t1y * t2z - t1z * t2y;
            ny = t1z * t2x - t1x * t2z;
            nz = t1x * t2y - t1y * t2x;
            continue;
        }
        var hit = false;
        while (true) {
            t1x = v2x - v1x;
            t1y = v2y - v1y;
            t1z = v2z - v1z;
            t2x = v3x - v1x;
            t2y = v3y - v1y;
            t2z = v3z - v1z;
            nx = t1y * t2z - t1z * t2y;
            ny = t1z * t2x - t1x * t2z;
            nz = t1x * t2y - t1y * t2x;
            len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
            nx *= len;
            ny *= len;
            nz *= len;
            if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
                var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
                var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
                var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
                var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
                var sum = b0 + b1 + b2 + b3;
                if (sum <= 0) {
                    b0 = 0;
                    b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
                    b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
                    b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
                    sum = b1 + b2 + b3;
                }
                var inv = 1 / sum;
                p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
                p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
                p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
                p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
                p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
                p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
                hit = true;
            }
            this.supportPointB(c1, -nx, -ny, -nz, sup);
            var v41x = sup.x;
            var v41y = sup.y;
            var v41z = sup.z;
            this.supportPointC(c2, nx, ny, nz, sup);
            var v42x = sup.x;
            var v42y = sup.y;
            var v42z = sup.z;
            var v4x = v42x - v41x;
            var v4y = v42y - v41y;
            var v4z = v42z - v41z;
            var separation = -(v4x * nx + v4y * ny + v4z * nz);
            if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
                if (hit) {
                    sep.init(-nx, -ny, -nz);
                    pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
                    dep.x = separation;
                    return true;
                }
                return false;
            }
            if (
            (v4y * v1z - v4z * v1y) * v0x +
            (v4z * v1x - v4x * v1z) * v0y +
            (v4x * v1y - v4y * v1x) * v0z < 0
            ) {
                if (
                (v4y * v2z - v4z * v2y) * v0x +
                (v4z * v2x - v4x * v2z) * v0y +
                (v4x * v2y - v4y * v2x) * v0z < 0
                ) {
                    v1x = v4x;
                    v1y = v4y;
                    v1z = v4z;
                    v11x = v41x;
                    v11y = v41y;
                    v11z = v41z;
                    v12x = v42x;
                    v12y = v42y;
                    v12z = v42z;
                } else {
                    v3x = v4x;
                    v3y = v4y;
                    v3z = v4z;
                    v31x = v41x;
                    v31y = v41y;
                    v31z = v41z;
                    v32x = v42x;
                    v32y = v42y;
                    v32z = v42z;
                }
            } else {
                if (
                (v4y * v3z - v4z * v3y) * v0x +
                (v4z * v3x - v4x * v3z) * v0y +
                (v4x * v3y - v4y * v3x) * v0z < 0
                ) {
                    v2x = v4x;
                    v2y = v4y;
                    v2z = v4z;
                    v21x = v41x;
                    v21y = v41y;
                    v21z = v41z;
                    v22x = v42x;
                    v22y = v42y;
                    v22z = v42z;
                } else {
                    v1x = v4x;
                    v1y = v4y;
                    v1z = v4z;
                    v11x = v41x;
                    v11y = v41y;
                    v11z = v41z;
                    v12x = v42x;
                    v12y = v42y;
                    v12z = v42z;
                }
            }
        }
    }
    //return false;
};
 
OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
 
    var rot = c.rotation.elements;
    var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
    var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
    var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
    var w = c.halfWidth;
    var h = c.halfHeight;
    var d = c.halfDepth;
    var ox;
    var oy;
    var oz;
    if (ldx < 0) ox = -w;
    else ox = w;
    if (ldy < 0) oy = -h;
    else oy = h;
    if (ldz < 0) oz = -d;
    else oz = d;
    ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
    ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
    ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
    out.init(ldx, ldy, ldz);
 
};
 
OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
 
    var rot = c.rotation.elements;
    var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
    var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
    var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
    var radx = ldx;
    var radz = ldz;
    var len = radx * radx + radz * radz;
    var rad = c.radius;
    var hh = c.halfHeight;
    var ox;
    var oy;
    var oz;
    if (len == 0) {
        if (ldy < 0) {
            ox = rad;
            oy = -hh;
            oz = 0;
        } else {
            ox = rad;
            oy = hh;
            oz = 0;
        }
    } else {
        len = c.radius / OIMO.sqrt(len);
        if (ldy < 0) {
            ox = radx * len;
            oy = -hh;
            oz = radz * len;
        } else {
            ox = radx * len;
            oy = hh;
            oz = radz * len;
        }
    }
    ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
    ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
    ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
    out.init(ldx, ldy, ldz);
 
};
 
OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
 
    var b;
    var c;
    if (this.flip) {
        b = shape2;
        c = shape1;
    } else {
        b = shape1;
        c = shape2;
    }
    var sep = new OIMO.Vec3();
    var pos = new OIMO.Vec3();
    var dep = new OIMO.Vec3();
    var co;
    if (!this.getSep(b, c, sep, pos, dep)) return;
    var pbx = b.position.x;
    var pby = b.position.y;
    var pbz = b.position.z;
    var pcx = c.position.x;
    var pcy = c.position.y;
    var pcz = c.position.z;
    var bw = b.halfWidth;
    var bh = b.halfHeight;
    var bd = b.halfDepth;
    var ch = c.halfHeight;
    var r = c.radius;
 
    var D = b.dimentions;
 
    var nwx = D[0];//b.normalDirectionWidth.x;
    var nwy = D[1];//b.normalDirectionWidth.y;
    var nwz = D[2];//b.normalDirectionWidth.z;
    var nhx = D[3];//b.normalDirectionHeight.x;
    var nhy = D[4];//b.normalDirectionHeight.y;
    var nhz = D[5];//b.normalDirectionHeight.z;
    var ndx = D[6];//b.normalDirectionDepth.x;
    var ndy = D[7];//b.normalDirectionDepth.y;
    var ndz = D[8];//b.normalDirectionDepth.z;
 
    var dwx = D[9];//b.halfDirectionWidth.x;
    var dwy = D[10];//b.halfDirectionWidth.y;
    var dwz = D[11];//b.halfDirectionWidth.z;
    var dhx = D[12];//b.halfDirectionHeight.x;
    var dhy = D[13];//b.halfDirectionHeight.y;
    var dhz = D[14];//b.halfDirectionHeight.z;
    var ddx = D[15];//b.halfDirectionDepth.x;
    var ddy = D[16];//b.halfDirectionDepth.y;
    var ddz = D[17];//b.halfDirectionDepth.z;
 
    var ncx = c.normalDirection.x;
    var ncy = c.normalDirection.y;
    var ncz = c.normalDirection.z;
    var dcx = c.halfDirection.x;
    var dcy = c.halfDirection.y;
    var dcz = c.halfDirection.z;
    var nx = sep.x;
    var ny = sep.y;
    var nz = sep.z;
    var dotw = nx * nwx + ny * nwy + nz * nwz;
    var doth = nx * nhx + ny * nhy + nz * nhz;
    var dotd = nx * ndx + ny * ndy + nz * ndz;
    var dotc = nx * ncx + ny * ncy + nz * ncz;
    var right1 = dotw > 0;
    var right2 = doth > 0;
    var right3 = dotd > 0;
    var right4 = dotc > 0;
    if (!right1) dotw = -dotw;
    if (!right2) doth = -doth;
    if (!right3) dotd = -dotd;
    if (!right4) dotc = -dotc;
    var state = 0;
    if (dotc > 0.999) {
        if (dotw > 0.999) {
            if (dotw > dotc) state = 1;
            else state = 4;
        } else if (doth > 0.999) {
            if (doth > dotc) state = 2;
            else state = 4;
        } else if (dotd > 0.999) {
            if (dotd > dotc) state = 3;
            else state = 4;
        } else state = 4;
    } else {
        if (dotw > 0.999) state = 1;
        else if (doth > 0.999) state = 2;
        else if (dotd > 0.999) state = 3;
    }
    var cbx;
    var cby;
    var cbz;
    var ccx;
    var ccy;
    var ccz;
    var r00;
    var r01;
    var r02;
    var r10;
    var r11;
    var r12;
    var r20;
    var r21;
    var r22;
    var px;
    var py;
    var pz;
    var pd;
    var dot;
    var len;
    var tx;
    var ty;
    var tz;
    var td;
    var dx;
    var dy;
    var dz;
    var d1x;
    var d1y;
    var d1z;
    var d2x;
    var d2y;
    var d2z;
    var sx;
    var sy;
    var sz;
    var sd;
    var ex;
    var ey;
    var ez;
    var ed;
    var dot1;
    var dot2;
    var t1;
    var t2;
    var dir1x;
    var dir1y;
    var dir1z;
    var dir2x;
    var dir2y;
    var dir2z;
    var dir1l;
    var dir2l;
    if (state == 0) {
        //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
        manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
    } else if (state == 4) {
        if (right4) {
            ccx = pcx - dcx;
            ccy = pcy - dcy;
            ccz = pcz - dcz;
            nx = -ncx;
            ny = -ncy;
            nz = -ncz;
        } else {
            ccx = pcx + dcx;
            ccy = pcy + dcy;
            ccz = pcz + dcz;
            nx = ncx;
            ny = ncy;
            nz = ncz;
        }
        var v1x;
        var v1y;
        var v1z;
        var v2x;
        var v2y;
        var v2z;
        var v3x;
        var v3y;
        var v3z;
        var v4x;
        var v4y;
        var v4z;
 
        dot = 1;
        state = 0;
        dot1 = nwx * nx + nwy * ny + nwz * nz;
        if (dot1 < dot) {
            dot = dot1;
            state = 0;
        }
        if (-dot1 < dot) {
            dot = -dot1;
            state = 1;
        }
        dot1 = nhx * nx + nhy * ny + nhz * nz;
        if (dot1 < dot) {
            dot = dot1;
            state = 2;
        }
        if (-dot1 < dot) {
            dot = -dot1;
            state = 3;
        }
        dot1 = ndx * nx + ndy * ny + ndz * nz;
        if (dot1 < dot) {
            dot = dot1;
            state = 4;
        }
        if (-dot1 < dot) {
            dot = -dot1;
            state = 5;
        }
        var v = b.elements;
        switch (state) {
            case 0:
                //v=b.vertex1;
                v1x = v[0];//v.x;
                v1y = v[1];//v.y;
                v1z = v[2];//v.z;
                //v=b.vertex3;
                v2x = v[6];//v.x;
                v2y = v[7];//v.y;
                v2z = v[8];//v.z;
                //v=b.vertex4;
                v3x = v[9];//v.x;
                v3y = v[10];//v.y;
                v3z = v[11];//v.z;
                //v=b.vertex2;
                v4x = v[3];//v.x;
                v4y = v[4];//v.y;
                v4z = v[5];//v.z;
                break;
            case 1:
                //v=b.vertex6;
                v1x = v[15];//v.x;
                v1y = v[16];//v.y;
                v1z = v[17];//v.z;
                //v=b.vertex8;
                v2x = v[21];//v.x;
                v2y = v[22];//v.y;
                v2z = v[23];//v.z;
                //v=b.vertex7;
                v3x = v[18];//v.x;
                v3y = v[19];//v.y;
                v3z = v[20];//v.z;
                //v=b.vertex5;
                v4x = v[12];//v.x;
                v4y = v[13];//v.y;
                v4z = v[14];//v.z;
                break;
            case 2:
                //v=b.vertex5;
                v1x = v[12];//v.x;
                v1y = v[13];//v.y;
                v1z = v[14];//v.z;
                //v=b.vertex1;
                v2x = v[0];//v.x;
                v2y = v[1];//v.y;
                v2z = v[2];//v.z;
                //v=b.vertex2;
                v3x = v[3];//v.x;
                v3y = v[4];//v.y;
                v3z = v[5];//v.z;
                //v=b.vertex6;
                v4x = v[15];//v.x;
                v4y = v[16];//v.y;
                v4z = v[17];//v.z;
                break;
            case 3:
                //v=b.vertex8;
                v1x = v[21];//v.x;
                v1y = v[22];//v.y;
                v1z = v[23];//v.z;
                //v=b.vertex4;
                v2x = v[9];//v.x;
                v2y = v[10];//v.y;
                v2z = v[11];//v.z;
                //v=b.vertex3;
                v3x = v[6];//v.x;
                v3y = v[7];//v.y;
                v3z = v[8];//v.z;
                //v=b.vertex7;
                v4x = v[18];//v.x;
                v4y = v[19];//v.y;
                v4z = v[20];//v.z;
                break;
            case 4:
                //v=b.vertex5;
                v1x = v[12];//v.x;
                v1y = v[13];//v.y;
                v1z = v[14];//v.z;
                //v=b.vertex7;
                v2x = v[18];//v.x;
                v2y = v[19];//v.y;
                v2z = v[20];//v.z;
                //v=b.vertex3;
                v3x = v[6];//v.x;
                v3y = v[7];//v.y;
                v3z = v[8];//v.z;
                //v=b.vertex1;
                v4x = v[0];//v.x;
                v4y = v[1];//v.y;
                v4z = v[2];//v.z;
                break;
            case 5:
                //v=b.vertex2;
                v1x = v[3];//v.x;
                v1y = v[4];//v.y;
                v1z = v[5];//v.z;
                //v=b.vertex4;
                v2x = v[9];//v.x;
                v2y = v[10];//v.y;
                v2z = v[11];//v.z;
                //v=b.vertex8;
                v3x = v[21];//v.x;
                v3y = v[22];//v.y;
                v3z = v[23];//v.z;
                //v=b.vertex6;
                v4x = v[15];//v.x;
                v4y = v[16];//v.y;
                v4z = v[17];//v.z;
                break;
        }
        pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
        if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
        pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
        if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
        pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
        if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
        pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
        if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
    } else {
        switch (state) {
            case 1:
                if (right1) {
                    cbx = pbx + dwx;
                    cby = pby + dwy;
                    cbz = pbz + dwz;
                    nx = nwx;
                    ny = nwy;
                    nz = nwz;
                } else {
                    cbx = pbx - dwx;
                    cby = pby - dwy;
                    cbz = pbz - dwz;
                    nx = -nwx;
                    ny = -nwy;
                    nz = -nwz;
                }
                dir1x = nhx;
                dir1y = nhy;
                dir1z = nhz;
                dir1l = bh;
                dir2x = ndx;
                dir2y = ndy;
                dir2z = ndz;
                dir2l = bd;
                break;
            case 2:
                if (right2) {
                    cbx = pbx + dhx;
                    cby = pby + dhy;
                    cbz = pbz + dhz;
                    nx = nhx;
                    ny = nhy;
                    nz = nhz;
                } else {
                    cbx = pbx - dhx;
                    cby = pby - dhy;
                    cbz = pbz - dhz;
                    nx = -nhx;
                    ny = -nhy;
                    nz = -nhz;
                }
                dir1x = nwx;
                dir1y = nwy;
                dir1z = nwz;
                dir1l = bw;
                dir2x = ndx;
                dir2y = ndy;
                dir2z = ndz;
                dir2l = bd;
                break;
            case 3:
                if (right3) {
                    cbx = pbx + ddx;
                    cby = pby + ddy;
                    cbz = pbz + ddz;
                    nx = ndx;
                    ny = ndy;
                    nz = ndz;
                } else {
                    cbx = pbx - ddx;
                    cby = pby - ddy;
                    cbz = pbz - ddz;
                    nx = -ndx;
                    ny = -ndy;
                    nz = -ndz;
                }
                dir1x = nwx;
                dir1y = nwy;
                dir1z = nwz;
                dir1l = bw;
                dir2x = nhx;
                dir2y = nhy;
                dir2z = nhz;
                dir2l = bh;
                break;
        }
        dot = nx * ncx + ny * ncy + nz * ncz;
        if (dot < 0) len = ch;
        else len = -ch;
        ccx = pcx + len * ncx;
        ccy = pcy + len * ncy;
        ccz = pcz + len * ncz;
        if (dotc >= 0.999999) {
            tx = -ny;
            ty = nz;
            tz = nx;
        } else {
            tx = nx;
            ty = ny;
            tz = nz;
        }
        len = tx * ncx + ty * ncy + tz * ncz;
        dx = len * ncx - tx;
        dy = len * ncy - ty;
        dz = len * ncz - tz;
        len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
        if (len == 0) return;
        len = r / len;
        dx *= len;
        dy *= len;
        dz *= len;
        tx = ccx + dx;
        ty = ccy + dy;
        tz = ccz + dz;
        if (dot < -0.96 || dot > 0.96) {
            r00 = ncx * ncx * 1.5 - 0.5;
            r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
            r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
            r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
            r11 = ncy * ncy * 1.5 - 0.5;
            r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
            r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
            r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
            r22 = ncz * ncz * 1.5 - 0.5;
            px = tx;
            py = ty;
            pz = tz;
            pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
            tx = px - pd * nx - cbx;
            ty = py - pd * ny - cby;
            tz = pz - pd * nz - cbz;
            sd = dir1x * tx + dir1y * ty + dir1z * tz;
            ed = dir2x * tx + dir2y * ty + dir2z * tz;
            if (sd < -dir1l) sd = -dir1l;
            else if (sd > dir1l) sd = dir1l;
            if (ed < -dir2l) ed = -dir2l;
            else if (ed > dir2l) ed = dir2l;
            tx = sd * dir1x + ed * dir2x;
            ty = sd * dir1y + ed * dir2y;
            tz = sd * dir1z + ed * dir2z;
            px = cbx + tx;
            py = cby + ty;
            pz = cbz + tz;
            manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
            px = dx * r00 + dy * r01 + dz * r02;
            py = dx * r10 + dy * r11 + dz * r12;
            pz = dx * r20 + dy * r21 + dz * r22;
            px = (dx = px) + ccx;
            py = (dy = py) + ccy;
            pz = (dz = pz) + ccz;
            pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
            if (pd <= 0) {
                tx = px - pd * nx - cbx;
                ty = py - pd * ny - cby;
                tz = pz - pd * nz - cbz;
                sd = dir1x * tx + dir1y * ty + dir1z * tz;
                ed = dir2x * tx + dir2y * ty + dir2z * tz;
                if (sd < -dir1l) sd = -dir1l;
                else if (sd > dir1l) sd = dir1l;
                if (ed < -dir2l) ed = -dir2l;
                else if (ed > dir2l) ed = dir2l;
                tx = sd * dir1x + ed * dir2x;
                ty = sd * dir1y + ed * dir2y;
                tz = sd * dir1z + ed * dir2z;
                px = cbx + tx;
                py = cby + ty;
                pz = cbz + tz;
                //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
                manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
            }
            px = dx * r00 + dy * r01 + dz * r02;
            py = dx * r10 + dy * r11 + dz * r12;
            pz = dx * r20 + dy * r21 + dz * r22;
            px = (dx = px) + ccx;
            py = (dy = py) + ccy;
            pz = (dz = pz) + ccz;
            pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
            if (pd <= 0) {
                tx = px - pd * nx - cbx;
                ty = py - pd * ny - cby;
                tz = pz - pd * nz - cbz;
                sd = dir1x * tx + dir1y * ty + dir1z * tz;
                ed = dir2x * tx + dir2y * ty + dir2z * tz;
                if (sd < -dir1l) sd = -dir1l;
                else if (sd > dir1l) sd = dir1l;
                if (ed < -dir2l) ed = -dir2l;
                else if (ed > dir2l) ed = dir2l;
                tx = sd * dir1x + ed * dir2x;
                ty = sd * dir1y + ed * dir2y;
                tz = sd * dir1z + ed * dir2z;
                px = cbx + tx;
                py = cby + ty;
                pz = cbz + tz;
                //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
                manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
            }
        } else {
            sx = tx;
            sy = ty;
            sz = tz;
            sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
            sx -= sd * nx;
            sy -= sd * ny;
            sz -= sd * nz;
            if (dot > 0) {
                ex = tx + dcx * 2;
                ey = ty + dcy * 2;
                ez = tz + dcz * 2;
            } else {
                ex = tx - dcx * 2;
                ey = ty - dcy * 2;
                ez = tz - dcz * 2;
            }
            ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
            ex -= ed * nx;
            ey -= ed * ny;
            ez -= ed * nz;
            d1x = sx - cbx;
            d1y = sy - cby;
            d1z = sz - cbz;
            d2x = ex - cbx;
            d2y = ey - cby;
            d2z = ez - cbz;
            tx = ex - sx;
            ty = ey - sy;
            tz = ez - sz;
            td = ed - sd;
            dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
            doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
            dot1 = dotw - dir1l;
            dot2 = doth - dir1l;
            if (dot1 > 0) {
                if (dot2 > 0) return;
                t1 = dot1 / (dot1 - dot2);
                sx = sx + tx * t1;
                sy = sy + ty * t1;
                sz = sz + tz * t1;
                sd = sd + td * t1;
                d1x = sx - cbx;
                d1y = sy - cby;
                d1z = sz - cbz;
                dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                td = ed - sd;
            } else if (dot2 > 0) {
                t1 = dot1 / (dot1 - dot2);
                ex = sx + tx * t1;
                ey = sy + ty * t1;
                ez = sz + tz * t1;
                ed = sd + td * t1;
                d2x = ex - cbx;
                d2y = ey - cby;
                d2z = ez - cbz;
                doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                td = ed - sd;
            }
            dot1 = dotw + dir1l;
            dot2 = doth + dir1l;
            if (dot1 < 0) {
                if (dot2 < 0) return;
                t1 = dot1 / (dot1 - dot2);
                sx = sx + tx * t1;
                sy = sy + ty * t1;
                sz = sz + tz * t1;
                sd = sd + td * t1;
                d1x = sx - cbx;
                d1y = sy - cby;
                d1z = sz - cbz;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                td = ed - sd;
            } else if (dot2 < 0) {
                t1 = dot1 / (dot1 - dot2);
                ex = sx + tx * t1;
                ey = sy + ty * t1;
                ez = sz + tz * t1;
                ed = sd + td * t1;
                d2x = ex - cbx;
                d2y = ey - cby;
                d2z = ez - cbz;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                td = ed - sd;
            }
            dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
            doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
            dot1 = dotw - dir2l;
            dot2 = doth - dir2l;
            if (dot1 > 0) {
                if (dot2 > 0) return;
                t1 = dot1 / (dot1 - dot2);
                sx = sx + tx * t1;
                sy = sy + ty * t1;
                sz = sz + tz * t1;
                sd = sd + td * t1;
                d1x = sx - cbx;
                d1y = sy - cby;
                d1z = sz - cbz;
                dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                td = ed - sd;
            } else if (dot2 > 0) {
                t1 = dot1 / (dot1 - dot2);
                ex = sx + tx * t1;
                ey = sy + ty * t1;
                ez = sz + tz * t1;
                ed = sd + td * t1;
                d2x = ex - cbx;
                d2y = ey - cby;
                d2z = ez - cbz;
                doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                td = ed - sd;
            }
            dot1 = dotw + dir2l;
            dot2 = doth + dir2l;
            if (dot1 < 0) {
                if (dot2 < 0) return;
                t1 = dot1 / (dot1 - dot2);
                sx = sx + tx * t1;
                sy = sy + ty * t1;
                sz = sz + tz * t1;
                sd = sd + td * t1;
            } else if (dot2 < 0) {
                t1 = dot1 / (dot1 - dot2);
                ex = sx + tx * t1;
                ey = sy + ty * t1;
                ez = sz + tz * t1;
                ed = sd + td * t1;
            }
            if (sd < 0) {
                //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
                manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
            }
            if (ed < 0) {
                //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
                manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
            }
        }
    }
 
};
OIMO.CylinderCylinderCollisionDetector = function () {
 
    OIMO.CollisionDetector.call(this);
 
};
 
OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
 
OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
 
    var t1x;
    var t1y;
    var t1z;
    var t2x;
    var t2y;
    var t2z;
    var sup = new OIMO.Vec3();
    var len;
    var p1x;
    var p1y;
    var p1z;
    var p2x;
    var p2y;
    var p2z;
    var v01x = c1.position.x;
    var v01y = c1.position.y;
    var v01z = c1.position.z;
    var v02x = c2.position.x;
    var v02y = c2.position.y;
    var v02z = c2.position.z;
    var v0x = v02x - v01x;
    var v0y = v02y - v01y;
    var v0z = v02z - v01z;
    if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
    var nx = -v0x;
    var ny = -v0y;
    var nz = -v0z;
    this.supportPoint(c1, -nx, -ny, -nz, sup);
    var v11x = sup.x;
    var v11y = sup.y;
    var v11z = sup.z;
    this.supportPoint(c2, nx, ny, nz, sup);
    var v12x = sup.x;
    var v12y = sup.y;
    var v12z = sup.z;
    var v1x = v12x - v11x;
    var v1y = v12y - v11y;
    var v1z = v12z - v11z;
    if (v1x * nx + v1y * ny + v1z * nz <= 0) {
        return false;
    }
    nx = v1y * v0z - v1z * v0y;
    ny = v1z * v0x - v1x * v0z;
    nz = v1x * v0y - v1y * v0x;
    if (nx * nx + ny * ny + nz * nz == 0) {
        sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
        sep.normalize(sep);
        pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
        return true;
    }
    this.supportPoint(c1, -nx, -ny, -nz, sup);
    var v21x = sup.x;
    var v21y = sup.y;
    var v21z = sup.z;
    this.supportPoint(c2, nx, ny, nz, sup);
    var v22x = sup.x;
    var v22y = sup.y;
    var v22z = sup.z;
    var v2x = v22x - v21x;
    var v2y = v22y - v21y;
    var v2z = v22z - v21z;
    if (v2x * nx + v2y * ny + v2z * nz <= 0) {
        return false;
    }
    t1x = v1x - v0x;
    t1y = v1y - v0y;
    t1z = v1z - v0z;
    t2x = v2x - v0x;
    t2y = v2y - v0y;
    t2z = v2z - v0z;
    nx = t1y * t2z - t1z * t2y;
    ny = t1z * t2x - t1x * t2z;
    nz = t1x * t2y - t1y * t2x;
    if (nx * v0x + ny * v0y + nz * v0z > 0) {
        t1x = v1x;
        t1y = v1y;
        t1z = v1z;
        v1x = v2x;
        v1y = v2y;
        v1z = v2z;
        v2x = t1x;
        v2y = t1y;
        v2z = t1z;
        t1x = v11x;
        t1y = v11y;
        t1z = v11z;
        v11x = v21x;
        v11y = v21y;
        v11z = v21z;
        v21x = t1x;
        v21y = t1y;
        v21z = t1z;
        t1x = v12x;
        t1y = v12y;
        t1z = v12z;
        v12x = v22x;
        v12y = v22y;
        v12z = v22z;
        v22x = t1x;
        v22y = t1y;
        v22z = t1z;
        nx = -nx;
        ny = -ny;
        nz = -nz;
    }
    var iterations = 0;
    while (true) {
        if (++iterations > 100) {
            return false;
        }
        this.supportPoint(c1, -nx, -ny, -nz, sup);
        var v31x = sup.x;
        var v31y = sup.y;
        var v31z = sup.z;
        this.supportPoint(c2, nx, ny, nz, sup);
        var v32x = sup.x;
        var v32y = sup.y;
        var v32z = sup.z;
        var v3x = v32x - v31x;
        var v3y = v32y - v31y;
        var v3z = v32z - v31z;
        if (v3x * nx + v3y * ny + v3z * nz <= 0) {
            return false;
        }
        if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
            v2x = v3x;
            v2y = v3y;
            v2z = v3z;
            v21x = v31x;
            v21y = v31y;
            v21z = v31z;
            v22x = v32x;
            v22y = v32y;
            v22z = v32z;
            t1x = v1x - v0x;
            t1y = v1y - v0y;
            t1z = v1z - v0z;
            t2x = v3x - v0x;
            t2y = v3y - v0y;
            t2z = v3z - v0z;
            nx = t1y * t2z - t1z * t2y;
            ny = t1z * t2x - t1x * t2z;
            nz = t1x * t2y - t1y * t2x;
            continue;
        }
        if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
            v1x = v3x;
            v1y = v3y;
            v1z = v3z;
            v11x = v31x;
            v11y = v31y;
            v11z = v31z;
            v12x = v32x;
            v12y = v32y;
            v12z = v32z;
            t1x = v3x - v0x;
            t1y = v3y - v0y;
            t1z = v3z - v0z;
            t2x = v2x - v0x;
            t2y = v2y - v0y;
            t2z = v2z - v0z;
            nx = t1y * t2z - t1z * t2y;
            ny = t1z * t2x - t1x * t2z;
            nz = t1x * t2y - t1y * t2x;
            continue;
        }
        var hit = false;
        while (true) {
            t1x = v2x - v1x;
            t1y = v2y - v1y;
            t1z = v2z - v1z;
            t2x = v3x - v1x;
            t2y = v3y - v1y;
            t2z = v3z - v1z;
            nx = t1y * t2z - t1z * t2y;
            ny = t1z * t2x - t1x * t2z;
            nz = t1x * t2y - t1y * t2x;
            len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
            nx *= len;
            ny *= len;
            nz *= len;
            if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
                var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
                var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
                var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
                var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
                var sum = b0 + b1 + b2 + b3;
                if (sum <= 0) {
                    b0 = 0;
                    b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
                    b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
                    b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
                    sum = b1 + b2 + b3;
                }
                var inv = 1 / sum;
                p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
                p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
                p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
                p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
                p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
                p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
                hit = true;
            }
            this.supportPoint(c1, -nx, -ny, -nz, sup);
            var v41x = sup.x;
            var v41y = sup.y;
            var v41z = sup.z;
            this.supportPoint(c2, nx, ny, nz, sup);
            var v42x = sup.x;
            var v42y = sup.y;
            var v42z = sup.z;
            var v4x = v42x - v41x;
            var v4y = v42y - v41y;
            var v4z = v42z - v41z;
            var separation = -(v4x * nx + v4y * ny + v4z * nz);
            if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
                if (hit) {
                    sep.init(-nx, -ny, -nz);
                    pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
                    dep.x = separation;
                    return true;
                }
                return false;
            }
            if (
            (v4y * v1z - v4z * v1y) * v0x +
            (v4z * v1x - v4x * v1z) * v0y +
            (v4x * v1y - v4y * v1x) * v0z < 0
            ) {
                if (
                (v4y * v2z - v4z * v2y) * v0x +
                (v4z * v2x - v4x * v2z) * v0y +
                (v4x * v2y - v4y * v2x) * v0z < 0
                ) {
                    v1x = v4x;
                    v1y = v4y;
                    v1z = v4z;
                    v11x = v41x;
                    v11y = v41y;
                    v11z = v41z;
                    v12x = v42x;
                    v12y = v42y;
                    v12z = v42z;
                } else {
                    v3x = v4x;
                    v3y = v4y;
                    v3z = v4z;
                    v31x = v41x;
                    v31y = v41y;
                    v31z = v41z;
                    v32x = v42x;
                    v32y = v42y;
                    v32z = v42z;
                }
            } else {
                if (
                (v4y * v3z - v4z * v3y) * v0x +
                (v4z * v3x - v4x * v3z) * v0y +
                (v4x * v3y - v4y * v3x) * v0z < 0
                ) {
                    v2x = v4x;
                    v2y = v4y;
                    v2z = v4z;
                    v21x = v41x;
                    v21y = v41y;
                    v21z = v41z;
                    v22x = v42x;
                    v22y = v42y;
                    v22z = v42z;
                } else {
                    v1x = v4x;
                    v1y = v4y;
                    v1z = v4z;
                    v11x = v41x;
                    v11y = v41y;
                    v11z = v41z;
                    v12x = v42x;
                    v12y = v42y;
                    v12z = v42z;
                }
            }
        }
    }
    //return false;
};
 
OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
 
    var rot = c.rotation.elements;
    var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
    var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
    var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
    var radx = ldx;
    var radz = ldz;
    var len = radx * radx + radz * radz;
    var rad = c.radius;
    var hh = c.halfHeight;
    var ox;
    var oy;
    var oz;
    if (len == 0) {
        if (ldy < 0) {
            ox = rad;
            oy = -hh;
            oz = 0;
        } else {
            ox = rad;
            oy = hh;
            oz = 0;
        }
    } else {
        len = c.radius / OIMO.sqrt(len);
        if (ldy < 0) {
            ox = radx * len;
            oy = -hh;
            oz = radz * len;
        } else {
            ox = radx * len;
            oy = hh;
            oz = radz * len;
        }
    }
    ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
    ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
    ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
    out.init(ldx, ldy, ldz);
 
};
 
OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
 
    var c1;
    var c2;
    if (shape1.id < shape2.id) {
        c1 = shape1;
        c2 = shape2;
    } else {
        c1 = shape2;
        c2 = shape1;
    }
    var p1 = c1.position;
    var p2 = c2.position;
    var p1x = p1.x;
    var p1y = p1.y;
    var p1z = p1.z;
    var p2x = p2.x;
    var p2y = p2.y;
    var p2z = p2.z;
    var h1 = c1.halfHeight;
    var h2 = c2.halfHeight;
    var n1 = c1.normalDirection;
    var n2 = c2.normalDirection;
    var d1 = c1.halfDirection;
    var d2 = c2.halfDirection;
    var r1 = c1.radius;
    var r2 = c2.radius;
    var n1x = n1.x;
    var n1y = n1.y;
    var n1z = n1.z;
    var n2x = n2.x;
    var n2y = n2.y;
    var n2z = n2.z;
    var d1x = d1.x;
    var d1y = d1.y;
    var d1z = d1.z;
    var d2x = d2.x;
    var d2y = d2.y;
    var d2z = d2.z;
    var dx = p1x - p2x;
    var dy = p1y - p2y;
    var dz = p1z - p2z;
    var len;
    var len1;
    var len2;
    var c;
    var c1x;
    var c1y;
    var c1z;
    var c2x;
    var c2y;
    var c2z;
    var tx;
    var ty;
    var tz;
    var sx;
    var sy;
    var sz;
    var ex;
    var ey;
    var ez;
    var depth1;
    var depth2;
    var dot;
    var t1;
    var t2;
    var sep = new OIMO.Vec3();
    var pos = new OIMO.Vec3();
    var dep = new OIMO.Vec3();
    if (!this.getSep(c1, c2, sep, pos, dep)) return;
    var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
    var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
    var right1 = dot1 > 0;
    var right2 = dot2 > 0;
    if (!right1) dot1 = -dot1;
    if (!right2) dot2 = -dot2;
    var state = 0;
    if (dot1 > 0.999 || dot2 > 0.999) {
        if (dot1 > dot2) state = 1;
        else state = 2;
    }
    var nx;
    var ny;
    var nz;
    var depth = dep.x;
    var r00;
    var r01;
    var r02;
    var r10;
    var r11;
    var r12;
    var r20;
    var r21;
    var r22;
    var px;
    var py;
    var pz;
    var pd;
    var a;
    var b;
    var e;
    var f;
    nx = sep.x;
    ny = sep.y;
    nz = sep.z;
    switch (state) {
        case 0:
            manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
            break;
        case 1:
            if (right1) {
                c1x = p1x + d1x;
                c1y = p1y + d1y;
                c1z = p1z + d1z;
                nx = n1x;
                ny = n1y;
                nz = n1z;
            } else {
                c1x = p1x - d1x;
                c1y = p1y - d1y;
                c1z = p1z - d1z;
                nx = -n1x;
                ny = -n1y;
                nz = -n1z;
            }
            dot = nx * n2x + ny * n2y + nz * n2z;
            if (dot < 0) len = h2;
            else len = -h2;
            c2x = p2x + len * n2x;
            c2y = p2y + len * n2y;
            c2z = p2z + len * n2z;
            if (dot2 >= 0.999999) {
                tx = -ny;
                ty = nz;
                tz = nx;
            } else {
                tx = nx;
                ty = ny;
                tz = nz;
            }
            len = tx * n2x + ty * n2y + tz * n2z;
            dx = len * n2x - tx;
            dy = len * n2y - ty;
            dz = len * n2z - tz;
            len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
            if (len == 0) break;
            len = r2 / len;
            dx *= len;
            dy *= len;
            dz *= len;
            tx = c2x + dx;
            ty = c2y + dy;
            tz = c2z + dz;
            if (dot < -0.96 || dot > 0.96) {
                r00 = n2x * n2x * 1.5 - 0.5;
                r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
                r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
                r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
                r11 = n2y * n2y * 1.5 - 0.5;
                r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
                r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
                r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
                r22 = n2z * n2z * 1.5 - 0.5;
                px = tx;
                py = ty;
                pz = tz;
                pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
                tx = px - pd * nx - c1x;
                ty = py - pd * ny - c1y;
                tz = pz - pd * nz - c1z;
                len = tx * tx + ty * ty + tz * tz;
                if (len > r1 * r1) {
                    len = r1 / OIMO.sqrt(len);
                    tx *= len;
                    ty *= len;
                    tz *= len;
                }
                px = c1x + tx;
                py = c1y + ty;
                pz = c1z + tz;
                manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
                px = dx * r00 + dy * r01 + dz * r02;
                py = dx * r10 + dy * r11 + dz * r12;
                pz = dx * r20 + dy * r21 + dz * r22;
                px = (dx = px) + c2x;
                py = (dy = py) + c2y;
                pz = (dz = pz) + c2z;
                pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
                if (pd <= 0) {
                    tx = px - pd * nx - c1x;
                    ty = py - pd * ny - c1y;
                    tz = pz - pd * nz - c1z;
                    len = tx * tx + ty * ty + tz * tz;
                    if (len > r1 * r1) {
                        len = r1 / OIMO.sqrt(len);
                        tx *= len;
                        ty *= len;
                        tz *= len;
                    }
                    px = c1x + tx;
                    py = c1y + ty;
                    pz = c1z + tz;
                    manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
                }
                px = dx * r00 + dy * r01 + dz * r02;
                py = dx * r10 + dy * r11 + dz * r12;
                pz = dx * r20 + dy * r21 + dz * r22;
                px = (dx = px) + c2x;
                py = (dy = py) + c2y;
                pz = (dz = pz) + c2z;
                pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
                if (pd <= 0) {
                    tx = px - pd * nx - c1x;
                    ty = py - pd * ny - c1y;
                    tz = pz - pd * nz - c1z;
                    len = tx * tx + ty * ty + tz * tz;
                    if (len > r1 * r1) {
                        len = r1 / OIMO.sqrt(len);
                        tx *= len;
                        ty *= len;
                        tz *= len;
                    }
                    px = c1x + tx;
                    py = c1y + ty;
                    pz = c1z + tz;
                    manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
                }
            } else {
                sx = tx;
                sy = ty;
                sz = tz;
                depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
                sx -= depth1 * nx;
                sy -= depth1 * ny;
                sz -= depth1 * nz;
                if (dot > 0) {
                    ex = tx + n2x * h2 * 2;
                    ey = ty + n2y * h2 * 2;
                    ez = tz + n2z * h2 * 2;
                } else {
                    ex = tx - n2x * h2 * 2;
                    ey = ty - n2y * h2 * 2;
                    ez = tz - n2z * h2 * 2;
                }
                depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
                ex -= depth2 * nx;
                ey -= depth2 * ny;
                ez -= depth2 * nz;
                dx = c1x - sx;
                dy = c1y - sy;
                dz = c1z - sz;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                a = dx * dx + dy * dy + dz * dz;
                b = dx * tx + dy * ty + dz * tz;
                e = tx * tx + ty * ty + tz * tz;
                f = b * b - e * (a - r1 * r1);
                if (f < 0) break;
                f = OIMO.sqrt(f);
                t1 = (b + f) / e;
                t2 = (b - f) / e;
                if (t2 < t1) {
                    len = t1;
                    t1 = t2;
                    t2 = len;
                }
                if (t2 > 1) t2 = 1;
                if (t1 < 0) t1 = 0;
                tx = sx + (ex - sx) * t1;
                ty = sy + (ey - sy) * t1;
                tz = sz + (ez - sz) * t1;
                ex = sx + (ex - sx) * t2;
                ey = sy + (ey - sy) * t2;
                ez = sz + (ez - sz) * t2;
                sx = tx;
                sy = ty;
                sz = tz;
                len = depth1 + (depth2 - depth1) * t1;
                depth2 = depth1 + (depth2 - depth1) * t2;
                depth1 = len;
                if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
                if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
 
            }
            break;
        case 2:
            if (right2) {
                c2x = p2x - d2x;
                c2y = p2y - d2y;
                c2z = p2z - d2z;
                nx = -n2x;
                ny = -n2y;
                nz = -n2z;
            } else {
                c2x = p2x + d2x;
                c2y = p2y + d2y;
                c2z = p2z + d2z;
                nx = n2x;
                ny = n2y;
                nz = n2z;
            }
            dot = nx * n1x + ny * n1y + nz * n1z;
            if (dot < 0) len = h1;
            else len = -h1;
            c1x = p1x + len * n1x;
            c1y = p1y + len * n1y;
            c1z = p1z + len * n1z;
            if (dot1 >= 0.999999) {
                tx = -ny;
                ty = nz;
                tz = nx;
            } else {
                tx = nx;
                ty = ny;
                tz = nz;
            }
            len = tx * n1x + ty * n1y + tz * n1z;
            dx = len * n1x - tx;
            dy = len * n1y - ty;
            dz = len * n1z - tz;
            len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
            if (len == 0) break;
            len = r1 / len;
            dx *= len;
            dy *= len;
            dz *= len;
            tx = c1x + dx;
            ty = c1y + dy;
            tz = c1z + dz;
            if (dot < -0.96 || dot > 0.96) {
                r00 = n1x * n1x * 1.5 - 0.5;
                r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
                r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
                r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
                r11 = n1y * n1y * 1.5 - 0.5;
                r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
                r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
                r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
                r22 = n1z * n1z * 1.5 - 0.5;
                px = tx;
                py = ty;
                pz = tz;
                pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
                tx = px - pd * nx - c2x;
                ty = py - pd * ny - c2y;
                tz = pz - pd * nz - c2z;
                len = tx * tx + ty * ty + tz * tz;
                if (len > r2 * r2) {
                    len = r2 / OIMO.sqrt(len);
                    tx *= len;
                    ty *= len;
                    tz *= len;
                }
                px = c2x + tx;
                py = c2y + ty;
                pz = c2z + tz;
                manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
                px = dx * r00 + dy * r01 + dz * r02;
                py = dx * r10 + dy * r11 + dz * r12;
                pz = dx * r20 + dy * r21 + dz * r22;
                px = (dx = px) + c1x;
                py = (dy = py) + c1y;
                pz = (dz = pz) + c1z;
                pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
                if (pd <= 0) {
                    tx = px - pd * nx - c2x;
                    ty = py - pd * ny - c2y;
                    tz = pz - pd * nz - c2z;
                    len = tx * tx + ty * ty + tz * tz;
                    if (len > r2 * r2) {
                        len = r2 / OIMO.sqrt(len);
                        tx *= len;
                        ty *= len;
                        tz *= len;
                    }
                    px = c2x + tx;
                    py = c2y + ty;
                    pz = c2z + tz;
                    manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
                }
                px = dx * r00 + dy * r01 + dz * r02;
                py = dx * r10 + dy * r11 + dz * r12;
                pz = dx * r20 + dy * r21 + dz * r22;
                px = (dx = px) + c1x;
                py = (dy = py) + c1y;
                pz = (dz = pz) + c1z;
                pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
                if (pd <= 0) {
                    tx = px - pd * nx - c2x;
                    ty = py - pd * ny - c2y;
                    tz = pz - pd * nz - c2z;
                    len = tx * tx + ty * ty + tz * tz;
                    if (len > r2 * r2) {
                        len = r2 / OIMO.sqrt(len);
                        tx *= len;
                        ty *= len;
                        tz *= len;
                    }
                    px = c2x + tx;
                    py = c2y + ty;
                    pz = c2z + tz;
                    manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
                }
            } else {
                sx = tx;
                sy = ty;
                sz = tz;
                depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
                sx -= depth1 * nx;
                sy -= depth1 * ny;
                sz -= depth1 * nz;
                if (dot > 0) {
                    ex = tx + n1x * h1 * 2;
                    ey = ty + n1y * h1 * 2;
                    ez = tz + n1z * h1 * 2;
                } else {
                    ex = tx - n1x * h1 * 2;
                    ey = ty - n1y * h1 * 2;
                    ez = tz - n1z * h1 * 2;
                }
                depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
                ex -= depth2 * nx;
                ey -= depth2 * ny;
                ez -= depth2 * nz;
                dx = c2x - sx;
                dy = c2y - sy;
                dz = c2z - sz;
                tx = ex - sx;
                ty = ey - sy;
                tz = ez - sz;
                a = dx * dx + dy * dy + dz * dz;
                b = dx * tx + dy * ty + dz * tz;
                e = tx * tx + ty * ty + tz * tz;
                f = b * b - e * (a - r2 * r2);
                if (f < 0) break;
                f = OIMO.sqrt(f);
                t1 = (b + f) / e;
                t2 = (b - f) / e;
                if (t2 < t1) {
                    len = t1;
                    t1 = t2;
                    t2 = len;
                }
                if (t2 > 1) t2 = 1;
                if (t1 < 0) t1 = 0;
                tx = sx + (ex - sx) * t1;
                ty = sy + (ey - sy) * t1;
                tz = sz + (ez - sz) * t1;
                ex = sx + (ex - sx) * t2;
                ey = sy + (ey - sy) * t2;
                ez = sz + (ez - sz) * t2;
                sx = tx;
                sy = ty;
                sz = tz;
                len = depth1 + (depth2 - depth1) * t1;
                depth2 = depth1 + (depth2 - depth1) * t2;
                depth1 = len;
                if (depth1 < 0) {
                    manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
                }
                if (depth2 < 0) {
                    manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
                }
            }
            break;
    }
 
};
OIMO.SphereCylinderCollisionDetector = function (flip) {
 
    OIMO.CollisionDetector.call(this);
    this.flip = flip;
 
};
 
OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
 
OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
 
    var s;
    var c;
    if (this.flip) {
        s = shape2;
        c = shape1;
    } else {
        s = shape1;
        c = shape2;
    }
    var ps = s.position;
    var psx = ps.x;
    var psy = ps.y;
    var psz = ps.z;
    var pc = c.position;
    var pcx = pc.x;
    var pcy = pc.y;
    var pcz = pc.z;
    var dirx = c.normalDirection.x;
    var diry = c.normalDirection.y;
    var dirz = c.normalDirection.z;
    var rads = s.radius;
    var radc = c.radius;
    var rad2 = rads + radc;
    var halfh = c.halfHeight;
    var dx = psx - pcx;
    var dy = psy - pcy;
    var dz = psz - pcz;
    var dot = dx * dirx + dy * diry + dz * dirz;
    if (dot < -halfh - rads || dot > halfh + rads) return;
    var cx = pcx + dot * dirx;
    var cy = pcy + dot * diry;
    var cz = pcz + dot * dirz;
    var d2x = psx - cx;
    var d2y = psy - cy;
    var d2z = psz - cz;
    var len = d2x * d2x + d2y * d2y + d2z * d2z;
    if (len > rad2 * rad2) return;
    if (len > radc * radc) {
        len = radc / OIMO.sqrt(len);
        d2x *= len;
        d2y *= len;
        d2z *= len;
    }
    if (dot < -halfh) dot = -halfh;
    else if (dot > halfh) dot = halfh;
    cx = pcx + dot * dirx + d2x;
    cy = pcy + dot * diry + d2y;
    cz = pcz + dot * dirz + d2z;
    dx = cx - psx;
    dy = cy - psy;
    dz = cz - psz;
    len = dx * dx + dy * dy + dz * dz;
    var invLen;
    if (len > 0 && len < rads * rads) {
        len = OIMO.sqrt(len);
        invLen = 1 / len;
        dx *= invLen;
        dy *= invLen;
        dz *= invLen;
        ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
        manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
    }
 
};
/**
 * Class for checking collisions between 2 tetras,
 * a shape that is made with 4 vertices and 4 faces
 * arranged in triangles. With this algorigthm, soft
 * body physics are possible and easier to implement.
 * @author xprogram
 */
OIMO.TetraTetraCollisionDetector = function () {
    OIMO.CollisionDetector.call(this);
};
OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
 
OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
    /*
     * What we are doing:
     * Each tetra is represented by four 3D triangles. The only
     * quick way of finding if another tetra is within the other
     * tetra is to see if a single vertex is within the triangles
     * of the other tetra. So, for example, a tetra is represented
     * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
     * There is another tetra with a vertex A which was detected for
     * collision by the broadphase. Now, if the point A is between ALL
     * triangles of the other tetra (BCD, BCE, etc.) then the collision
     * is valid and we can pass point A to the manifold. Since the only
     * points on the tetra are the 4 vertices, collision detection is
     * not so complex. However, it can be time-consuming because we
     * need to split the 3D triangles into three 2D triangles each for
     * collision detection.
     */
    var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
    var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
 
    // fs is undeclared
    var fs = fs1;
 
    for (i = 0; i < 4; i++) {
        vec = vs1[i];
        for (j = 0; j < 4; j++) {
            j1 = vs2[fs[i].a];
            j2 = vs2[fs[i].b];
            j3 = vs2[fs[i].c];
 
            if (
              tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
              tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
              tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
            )
                ts++;
 
            if (ts === 4) // Only add point if it is inside all 4 triangles
                manifold.addPoint(vec);
        }
    }
};
 
// Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
function tricheck(p, p0, p1, p2) {
    var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
    var sg = A < 0 ? -1 : 1;
    var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
    var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
    return s > 0 && t > 0 && (s + t) < 2 * A * sg;
}
 
function pt(x, y) { return { x: x, y: y }; }
 
/**
 * An axis-aligned bounding box.
 * @author saharan
 * @author lo-th
 */
 
OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
 
    this.elements = new OIMO_ARRAY_TYPE(6);
    var te = this.elements;
 
    te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
    te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
 
};
 
OIMO.AABB.prototype = {
 
    constructor: OIMO.AABB,
 
    set: function (minX, maxX, minY, maxY, minZ, maxZ) {
 
        var te = this.elements;
 
        te[0] = minX; te[3] = maxX;
        te[1] = minY; te[4] = maxY;
        te[2] = minZ; te[5] = maxZ;
 
        return this;
 
    },
 
    intersectTest: function (aabb) {
 
        var te = this.elements;
        var ue = aabb.elements;
        return te[0] > ue[3] || te[1] > ue[4] || te[2] > ue[5] || te[3] < ue[0] || te[4] < ue[1] || te[5] < ue[2];
 
    },
 
    intersectTestTwo: function (aabb) {
 
        var te = this.elements;
        var ue = aabb.elements;
        return te[0] < ue[0] || te[1] < ue[1] || te[2] < ue[2] || te[3] > ue[3] || te[4] > ue[4] || te[5] > ue[5];
 
    },
 
    clone: function () {
 
        return new this.constructor().fromArray(this.elements);
 
    },
 
    copy: function (aabb, margin) {
 
        var m = margin || 0;
        var me = aabb.elements;
        this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
        return this;
 
    },
 
    fromArray: function (array) {
 
        this.elements.set(array);
        return this;
 
    },
 
    // Set this AABB to the combined AABB of aabb1 and aabb2.
 
    combine: function (aabb1, aabb2) {
 
        var a = aabb1.elements;
        var b = aabb2.elements;
        var te = this.elements;
 
        te[0] = a[0] < b[0] ? a[0] : b[0];
        te[1] = a[1] < b[1] ? a[1] : b[1];
        te[2] = a[2] < b[2] ? a[2] : b[2];
 
        te[3] = a[3] > b[3] ? a[3] : b[3];
        te[4] = a[4] > b[4] ? a[4] : b[4];
        te[5] = a[5] > b[5] ? a[5] : b[5];
 
        return this;
 
    },
 
 
    // Get the surface area.
 
    surfaceArea: function () {
 
        var te = this.elements;
        var a = te[3] - te[0];
        var h = te[4] - te[1];
        var d = te[5] - te[2];
        return 2 * (a * (h + d) + h * d);
 
    },
 
 
    // Get whether the AABB intersects with the point or not.
 
    intersectsWithPoint: function (x, y, z) {
 
        var te = this.elements;
        return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
 
    },
 
    /**
     * Set the AABB from an array
     * of vertices. From THREE.
     * @author mrdoob
     * @author xprogram
     */
    setFromPoints: function (arr) {
        this.makeEmpty();
        for (var i = 0; i < arr.length; i++) {
            this.expandByPoint(arr[i]);
        }
    },
    makeEmpty: function () {
        this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
    },
    expandByPoint: function (pt) {
        var te = this.elements;
        this.set(
            OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
            OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
        );
    }
 
};
/**
* A proxy is used for broad-phase collecting pairs that can be colliding.
*/
 
OIMO.Proxy = function (shape) {
 
    // The parent shape.
    this.shape = shape;
    // The axis-aligned bounding box.
    this.aabb = shape.aabb;
 
};
 
OIMO.Proxy.prototype = {
 
    constructor: OIMO.Proxy,
 
    // Update the proxy.
 
    update: function () {
 
        OIMO.Error("Proxy", "Inheritance error.");
 
    }
 
};
/**
* A basic implementation of proxies.
* @author saharan
*/
 
OIMO.BasicProxy = function (shape) {
 
    OIMO.Proxy.call(this, shape);
 
    this.id = OIMO.proxyID++;
 
};
 
OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
 
OIMO.BasicProxy.prototype.update = function () {
 
};
/**
* The broad-phase is used for collecting all possible pairs for collision.
*/
 
OIMO.BroadPhase = function () {
 
    this.types = OIMO.BR_NULL;
    this.numPairChecks = 0;
    this.numPairs = 0;
    this.pairs = [];
 
};
 
OIMO.BroadPhase.prototype = {
 
    constructor: OIMO.BroadPhase,
    /**
    * Create a new proxy.
    * @param   shape
    * @return
    */
    createProxy: function (shape) {
 
        OIMO.Error("BroadPhase", "Inheritance error.");
 
    },
 
    /**
    * Add the proxy into the broad-phase.
    * @param   proxy
    */
    addProxy: function (proxy) {
 
        OIMO.Error("BroadPhase", "Inheritance error.");
    },
 
    /**
    * Remove the proxy from the broad-phase.
    * @param   proxy
    */
    removeProxy: function (proxy) {
 
        OIMO.Error("BroadPhase", "Inheritance error.");
 
    },
 
    /**
    * Returns whether the pair is available or not.
    * @param   s1
    * @param   s2
    * @return
    */
    isAvailablePair: function (s1, s2) {
 
        var b1 = s1.parent;
        var b2 = s2.parent;
        if (b1 == b2 || // same parents 
            (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
            (s1.belongsTo & s2.collidesWith) == 0 ||
            (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
        ) { return false; }
        var js;
        if (b1.numJoints < b2.numJoints) js = b1.jointLink;
        else js = b2.jointLink;
        while (js !== null) {
            var joint = js.joint;
            if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
            js = js.next;
        }
 
        return true;
 
    },
 
    // Detect overlapping pairs.
    detectPairs: function () {
 
        // clear old
        this.pairs = [];
        this.numPairs = 0;
        this.numPairChecks = 0;
 
        this.collectPairs();
 
    },
 
    collectPairs: function () {
 
        OIMO.Error("BroadPhase", "Inheritance error.");
 
    },
 
    addPair: function (s1, s2) {
 
        var pair = new OIMO.Pair(s1, s2);
        this.pairs.push(pair);
        this.numPairs++;
 
    }
};
/**
* A broad-phase algorithm with brute-force search.
* This always checks for all possible pairs.
*/
OIMO.BruteForceBroadPhase = function () {
    OIMO.BroadPhase.call(this);
    this.types = OIMO.BR_BRUTE_FORCE;;
    //this.numProxies=0;
    ///this.maxProxies = 256;
    this.proxies = [];
    //this.proxies.length = 256;
};
 
OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
 
OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
 
    return new OIMO.BasicProxy(shape);
 
};
 
OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
    /*if(this.numProxies==this.maxProxies){
        //this.maxProxies<<=1;
        this.maxProxies*=2;
        var newProxies=[];
        newProxies.length = this.maxProxies;
        var i = this.numProxies;
        while(i--){
        //for(var i=0, l=this.numProxies;i<l;i++){
            newProxies[i]=this.proxies[i];
        }
        this.proxies=newProxies;
    }*/
    //this.proxies[this.numProxies++] = proxy;
    this.proxies.push(proxy);
    //this.numProxies++;
 
};
 
OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
 
    var n = this.proxies.indexOf(proxy);
    if (n > -1) {
        this.proxies.splice(n, 1);
        //this.numProxies--;
    }
 
    /*var i = this.numProxies;
    while(i--){
    //for(var i=0, l=this.numProxies;i<l;i++){
        if(this.proxies[i] == proxy){
            this.proxies[i] = this.proxies[--this.numProxies];
            this.proxies[this.numProxies] = null;
            return;
        }
    }*/
 
};
 
OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
 
    var i = 0, j, p1, p2;
 
    var px = this.proxies;
    var l = px.length;//this.numProxies;
    //var ar1 = [];
    //var ar2 = [];
 
    //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
    //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
 
    //var ar1 = JSON.parse(JSON.stringify(this.proxies))
    //var ar2 = JSON.parse(JSON.stringify(this.proxies))
 
    this.numPairChecks = l * (l - 1) >> 1;
    //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
 
    while (i < l) {
        p1 = px[i++];
        j = i + 1;
        while (j < l) {
            p2 = px[j++];
            if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
            this.addPair(p1.shape, p2.shape);
        }
    }
 
};
/**
* A pair of shapes that may collide.
* @author saharan
*/
OIMO.Pair = function (s1, s2) {
    // The first shape.
    this.shape1 = s1 || null;
    // The second shape.
    this.shape2 = s2 || null;
};
/**
 * A projection axis for sweep and prune broad-phase.
 * @author saharan
 */
 
OIMO.SAPAxis = function () {
 
    this.numElements = 0;
    this.bufferSize = 256;
    this.elements = [];
    this.elements.length = this.bufferSize;
    this.stack = new OIMO_ARRAY_TYPE(64);
 
};
 
OIMO.SAPAxis.prototype = {
 
    constructor: OIMO.SAPAxis,
 
    addElements: function (min, max) {
 
        if (this.numElements + 2 >= this.bufferSize) {
            //this.bufferSize<<=1;
            this.bufferSize *= 2;
            var newElements = [];
            var i = this.numElements;
            while (i--) {
                //for(var i=0, l=this.numElements; i<l; i++){
                newElements[i] = this.elements[i];
            }
        }
        this.elements[this.numElements++] = min;
        this.elements[this.numElements++] = max;
 
    },
 
    removeElements: function (min, max) {
        var minIndex = -1;
        var maxIndex = -1;
        for (var i = 0, l = this.numElements; i < l; i++) {
            var e = this.elements[i];
            if (e == min || e == max) {
                if (minIndex == -1) {
                    minIndex = i;
                } else {
                    maxIndex = i;
                    break;
                }
            }
        }
        for (i = minIndex + 1, l = maxIndex; i < l; i++) {
            this.elements[i - 1] = this.elements[i];
        }
        for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
            this.elements[i - 2] = this.elements[i];
        }
 
        this.elements[--this.numElements] = null;
        this.elements[--this.numElements] = null;
    },
 
    sort: function () {
 
        var count = 0;
        var threshold = 1;
        while ((this.numElements >> threshold) != 0) threshold++;
        threshold = threshold * this.numElements >> 2;
        count = 0;
 
        var giveup = false;
        var elements = this.elements;
        for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
            var tmp = elements[i];
            var pivot = tmp.value;
            var tmp2 = elements[i - 1];
            if (tmp2.value > pivot) {
                var j = i;
                do {
                    elements[j] = tmp2;
                    if (--j == 0) break;
                    tmp2 = elements[j - 1];
                } while (tmp2.value > pivot);
                elements[j] = tmp;
                count += i - j;
                if (count > threshold) {
                    giveup = true; // stop and use quick sort
                    break;
                }
            }
        }
        if (!giveup) return;
        count = 2; var stack = this.stack;
        stack[0] = 0;
        stack[1] = this.numElements - 1;
        while (count > 0) {
            var right = stack[--count];
            var left = stack[--count];
            var diff = right - left;
            if (diff > 16) {  // quick sort
                //var mid=left+(diff>>1);
                var mid = left + (OIMO.floor(diff * 0.5));
                tmp = elements[mid];
                elements[mid] = elements[right];
                elements[right] = tmp;
                pivot = tmp.value;
                i = left - 1;
                j = right;
                while (true) {
                    var ei;
                    var ej;
                    do { ei = elements[++i]; } while (ei.value < pivot);
                    do { ej = elements[--j]; } while (pivot < ej.value && j != left);
                    if (i >= j) break;
                    elements[i] = ej;
                    elements[j] = ei;
                }
 
                elements[right] = elements[i];
                elements[i] = tmp;
                if (i - left > right - i) {
                    stack[count++] = left;
                    stack[count++] = i - 1;
                    stack[count++] = i + 1;
                    stack[count++] = right;
                } else {
                    stack[count++] = i + 1;
                    stack[count++] = right;
                    stack[count++] = left;
                    stack[count++] = i - 1;
                }
            } else {
                for (i = left + 1; i <= right; i++) {
                    tmp = elements[i];
                    pivot = tmp.value;
                    tmp2 = elements[i - 1];
                    if (tmp2.value > pivot) {
                        j = i;
                        do {
                            elements[j] = tmp2;
                            if (--j == 0) break;
                            tmp2 = elements[j - 1];
                        } while (tmp2.value > pivot);
                        elements[j] = tmp;
                    }
                }
            }
        }
 
    },
 
    calculateTestCount: function () {
 
        var num = 1;
        var sum = 0;
        for (var i = 1, l = this.numElements; i < l; i++) {
            if (this.elements[i].max) {
                num--;
            } else {
                sum += num;
                num++;
            }
        }
        return sum;
 
    }
}
/**
 * A broad-phase collision detection algorithm using sweep and prune.
 * @author saharan
 * @author lo-th
 */
 
OIMO.SAPBroadPhase = function () {
 
    OIMO.BroadPhase.call(this);
    this.types = OIMO.BR_SWEEP_AND_PRUNE;
 
    this.numElementsD = 0;
    this.numElementsS = 0;
    // dynamic proxies
    this.axesD = [
       new OIMO.SAPAxis(),
       new OIMO.SAPAxis(),
       new OIMO.SAPAxis()
    ];
    // static or sleeping proxies
    this.axesS = [
       new OIMO.SAPAxis(),
       new OIMO.SAPAxis(),
       new OIMO.SAPAxis()
    ];
 
    this.index1 = 0;
    this.index2 = 1;
 
};
 
OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
 
OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
 
    return new OIMO.SAPProxy(this, shape);
 
};
 
OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
 
    var p = proxy;
    if (p.isDynamic()) {
        this.axesD[0].addElements(p.min[0], p.max[0]);
        this.axesD[1].addElements(p.min[1], p.max[1]);
        this.axesD[2].addElements(p.min[2], p.max[2]);
        p.belongsTo = 1;
        this.numElementsD += 2;
    } else {
        this.axesS[0].addElements(p.min[0], p.max[0]);
        this.axesS[1].addElements(p.min[1], p.max[1]);
        this.axesS[2].addElements(p.min[2], p.max[2]);
        p.belongsTo = 2;
        this.numElementsS += 2;
    }
 
};
 
OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
 
    var p = proxy;
    if (p.belongsTo == 0) return;
 
    /*else if ( p.belongsTo == 1 ) {
        this.axesD[0].removeElements( p.min[0], p.max[0] );
        this.axesD[1].removeElements( p.min[1], p.max[1] );
        this.axesD[2].removeElements( p.min[2], p.max[2] );
        this.numElementsD -= 2;
    } else if ( p.belongsTo == 2 ) {
        this.axesS[0].removeElements( p.min[0], p.max[0] );
        this.axesS[1].removeElements( p.min[1], p.max[1] );
        this.axesS[2].removeElements( p.min[2], p.max[2] );
        this.numElementsS -= 2;
    }*/
 
    switch (p.belongsTo) {
        case 1:
            this.axesD[0].removeElements(p.min[0], p.max[0]);
            this.axesD[1].removeElements(p.min[1], p.max[1]);
            this.axesD[2].removeElements(p.min[2], p.max[2]);
            this.numElementsD -= 2;
            break;
        case 2:
            this.axesS[0].removeElements(p.min[0], p.max[0]);
            this.axesS[1].removeElements(p.min[1], p.max[1]);
            this.axesS[2].removeElements(p.min[2], p.max[2]);
            this.numElementsS -= 2;
            break;
    }
 
    p.belongsTo = 0;
 
};
 
OIMO.SAPBroadPhase.prototype.collectPairs = function () {
 
    if (this.numElementsD == 0) return;
 
    var axis1 = this.axesD[this.index1];
    var axis2 = this.axesD[this.index2];
 
    axis1.sort();
    axis2.sort();
 
    var count1 = axis1.calculateTestCount();
    var count2 = axis2.calculateTestCount();
    var elementsD;
    var elementsS;
    if (count1 <= count2) {// select the best axis
        axis2 = this.axesS[this.index1];
        axis2.sort();
        elementsD = axis1.elements;
        elementsS = axis2.elements;
    } else {
        axis1 = this.axesS[this.index2];
        axis1.sort();
        elementsD = axis2.elements;
        elementsS = axis1.elements;
        this.index1 ^= this.index2;
        this.index2 ^= this.index1;
        this.index1 ^= this.index2;
    }
    var activeD;
    var activeS;
    var p = 0;
    var q = 0;
    while (p < this.numElementsD) {
        var e1;
        var dyn;
        if (q == this.numElementsS) {
            e1 = elementsD[p];
            dyn = true;
            p++;
        } else {
            var d = elementsD[p];
            var s = elementsS[q];
            if (d.value < s.value) {
                e1 = d;
                dyn = true;
                p++;
            } else {
                e1 = s;
                dyn = false;
                q++;
            }
        }
        if (!e1.max) {
            var s1 = e1.proxy.shape;
            var min1 = e1.min1.value;
            var max1 = e1.max1.value;
            var min2 = e1.min2.value;
            var max2 = e1.max2.value;
 
            for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
                var s2 = e2.proxy.shape;
 
                this.numPairChecks++;
                if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
                this.addPair(s1, s2);
            }
            if (dyn) {
                for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
                    s2 = e2.proxy.shape;
 
                    this.numPairChecks++;
 
                    if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
                    this.addPair(s1, s2);
                }
                e1.pair = activeD;
                activeD = e1;
            } else {
                e1.pair = activeS;
                activeS = e1;
            }
        } else {
            var min = e1.pair;
            if (dyn) {
                if (min == activeD) {
                    activeD = activeD.pair;
                    continue;
                } else {
                    e1 = activeD;
                }
            } else {
                if (min == activeS) {
                    activeS = activeS.pair;
                    continue;
                } else {
                    e1 = activeS;
                }
            }
            do {
                e2 = e1.pair;
                if (e2 == min) {
                    e1.pair = e2.pair;
                    break;
                }
                e1 = e2;
            } while (e1 != null);
        }
    }
    this.index2 = (this.index1 | this.index2) ^ 3;
 
};
/**
 * An element of proxies.
 * @author saharan
 */
 
OIMO.SAPElement = function (proxy, max) {
 
    // The parent proxy
    this.proxy = proxy;
    // The pair element.
    this.pair = null;
    // The minimum element on other axis.
    this.min1 = null;
    // The maximum element on other axis.
    this.max1 = null;
    // The minimum element on other axis.
    this.min2 = null;
    // The maximum element on other axis.
    this.max2 = null;
    // Whether the element has maximum value or not.
    this.max = max;
    // The value of the element.
    this.value = 0;
 
};
/**
 * A proxy for sweep and prune broad-phase.
 * @author saharan
 * @author lo-th
 */
 
OIMO.SAPProxy = function (sap, shape) {
 
    OIMO.Proxy.call(this, shape);
    // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
    this.belongsTo = 0;
    // The maximum elements on each axis.
    this.max = [];
    // The minimum elements on each axis.
    this.min = [];
 
    this.sap = sap;
    this.min[0] = new OIMO.SAPElement(this, false);
    this.max[0] = new OIMO.SAPElement(this, true);
    this.min[1] = new OIMO.SAPElement(this, false);
    this.max[1] = new OIMO.SAPElement(this, true);
    this.min[2] = new OIMO.SAPElement(this, false);
    this.max[2] = new OIMO.SAPElement(this, true);
    this.max[0].pair = this.min[0];
    this.max[1].pair = this.min[1];
    this.max[2].pair = this.min[2];
    this.min[0].min1 = this.min[1];
    this.min[0].max1 = this.max[1];
    this.min[0].min2 = this.min[2];
    this.min[0].max2 = this.max[2];
    this.min[1].min1 = this.min[0];
    this.min[1].max1 = this.max[0];
    this.min[1].min2 = this.min[2];
    this.min[1].max2 = this.max[2];
    this.min[2].min1 = this.min[0];
    this.min[2].max1 = this.max[0];
    this.min[2].min2 = this.min[1];
    this.min[2].max2 = this.max[1];
 
};
 
OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
 
// Returns whether the proxy is dynamic or not.
 
OIMO.SAPProxy.prototype.isDynamic = function () {
 
    var body = this.shape.parent;
    return body.isDynamic && !body.sleeping;
 
};
 
OIMO.SAPProxy.prototype.update = function () {
 
    var te = this.aabb.elements;
    this.min[0].value = te[0];
    this.min[1].value = te[1];
    this.min[2].value = te[2];
    this.max[0].value = te[3];
    this.max[1].value = te[4];
    this.max[2].value = te[5];
 
    if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
        this.sap.removeProxy(this);
        this.sap.addProxy(this);
    }
 
};
/**
 * A dynamic bounding volume tree for the broad-phase algorithm.
 * @author saharan
 * @author lo-th
 */
 
OIMO.DBVT = function () {
 
    // The root of the tree.
    this.root = null;
    this.freeNodes = [];
    this.freeNodes.length = 16384;
    this.numFreeNodes = 0;
    this.aabb = new OIMO.AABB();
 
};
 
OIMO.DBVT.prototype = {
 
    constructor: OIMO.DBVT,
    /**
    * Move a leaf.
    * @param   leaf
    */
    moveLeaf: function (leaf) {
 
        this.deleteLeaf(leaf);
        this.insertLeaf(leaf);
 
    },
 
    /**
    * Insert a leaf to the tree.
    * @param   node
    */
    insertLeaf: function (leaf) {
 
        if (this.root == null) {
            this.root = leaf;
            return;
        }
        var lb = leaf.aabb;
        var sibling = this.root;
        var oldArea;
        var newArea;
        while (sibling.proxy == null) { // descend the node to search the best pair
            var c1 = sibling.child1;
            var c2 = sibling.child2;
            var b = sibling.aabb;
            var c1b = c1.aabb;
            var c2b = c2.aabb;
            oldArea = b.surfaceArea();
            this.aabb.combine(lb, b);
            newArea = this.aabb.surfaceArea();
            var creatingCost = newArea * 2;
            var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
            var discendingCost1 = incrementalCost;
            this.aabb.combine(lb, c1b);
            if (c1.proxy != null) {
                // leaf cost = area(combined aabb)
                discendingCost1 += this.aabb.surfaceArea();
            } else {
                // node cost = area(combined aabb) - area(old aabb)
                discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
            }
            var discendingCost2 = incrementalCost;
            this.aabb.combine(lb, c2b);
            if (c2.proxy != null) {
                // leaf cost = area(combined aabb)
                discendingCost2 += this.aabb.surfaceArea();
            } else {
                // node cost = area(combined aabb) - area(old aabb)
                discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
            }
            if (discendingCost1 < discendingCost2) {
                if (creatingCost < discendingCost1) {
                    break;// stop descending
                } else {
                    sibling = c1;// descend into first child
                }
            } else {
                if (creatingCost < discendingCost2) {
                    break;// stop descending
                } else {
                    sibling = c2;// descend into second child
                }
            }
        }
        var oldParent = sibling.parent;
        var newParent;
        if (this.numFreeNodes > 0) {
            newParent = this.freeNodes[--this.numFreeNodes];
        } else {
            newParent = new OIMO.DBVTNode();
        }
 
        newParent.parent = oldParent;
        newParent.child1 = leaf;
        newParent.child2 = sibling;
        newParent.aabb.combine(leaf.aabb, sibling.aabb);
        newParent.height = sibling.height + 1;
        sibling.parent = newParent;
        leaf.parent = newParent;
        if (sibling == this.root) {
            // replace root
            this.root = newParent;
        } else {
            // replace child
            if (oldParent.child1 == sibling) {
                oldParent.child1 = newParent;
            } else {
                oldParent.child2 = newParent;
            }
        }
        // update whole tree
        do {
            newParent = this.balance(newParent);
            this.fix(newParent);
            newParent = newParent.parent;
        } while (newParent != null);
    },
    getBalance: function (node) {
        if (node.proxy != null) return 0;
        return node.child1.height - node.child2.height;
    },
 
    /*print:function(node,indent,text){
 
        var hasChild=node.proxy==null;
        if(hasChild)text=this.print(node.child1,indent+1,text);
        for(var i=indent*2;i>=0;i--){
            text+=" ";
        }
        text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
        if(hasChild)text=this.print(node.child2,indent+1,text);
        return text;
    },*/
 
    /**
    * Delete a leaf from the tree.
    * @param   node
    */
    deleteLeaf: function (leaf) {
 
        if (leaf == this.root) {
            this.root = null;
            return;
        }
        var parent = leaf.parent;
        var sibling;
        if (parent.child1 == leaf) {
            sibling = parent.child2;
        } else {
            sibling = parent.child1;
        }
        if (parent == this.root) {
            this.root = sibling;
            sibling.parent = null;
            return;
        }
        var grandParent = parent.parent;
        sibling.parent = grandParent;
        if (grandParent.child1 == parent) {
            grandParent.child1 = sibling;
        } else {
            grandParent.child2 = sibling;
        }
        if (this.numFreeNodes < 16384) {
            this.freeNodes[this.numFreeNodes++] = parent;
        }
        do {
            grandParent = this.balance(grandParent);
            this.fix(grandParent);
            grandParent = grandParent.parent;
        } while (grandParent != null);
 
    },
 
    balance: function (node) {
 
        var nh = node.height;
        if (nh < 2) {
            return node;
        }
        var p = node.parent;
        var l = node.child1;
        var r = node.child2;
        var lh = l.height;
        var rh = r.height;
        var balance = lh - rh;
        var t;// for bit operation
 
        //          [ N ]
        //         /     \
        //    [ L ]       [ R ]
        //     / \         / \
        // [L-L] [L-R] [R-L] [R-R]
 
        // Is the tree balanced?
        if (balance > 1) {
            var ll = l.child1;
            var lr = l.child2;
            var llh = ll.height;
            var lrh = lr.height;
 
            // Is L-L higher than L-R?
            if (llh > lrh) {
                // set N to L-R
                l.child2 = node;
                node.parent = l;
 
                //          [ L ]
                //         /     \
                //    [L-L]       [ N ]
                //     / \         / \
                // [...] [...] [ L ] [ R ]
 
                // set L-R
                node.child1 = lr;
                lr.parent = node;
 
                //          [ L ]
                //         /     \
                //    [L-L]       [ N ]
                //     / \         / \
                // [...] [...] [L-R] [ R ]
 
                // fix bounds and heights
                node.aabb.combine(lr.aabb, r.aabb);
                t = lrh - rh;
                node.height = lrh - (t & t >> 31) + 1;
                l.aabb.combine(ll.aabb, node.aabb);
                t = llh - nh;
                l.height = llh - (t & t >> 31) + 1;
            } else {
                // set N to L-L
                l.child1 = node;
                node.parent = l;
 
                //          [ L ]
                //         /     \
                //    [ N ]       [L-R]
                //     / \         / \
                // [ L ] [ R ] [...] [...]
 
                // set L-L
                node.child1 = ll;
                ll.parent = node;
 
                //          [ L ]
                //         /     \
                //    [ N ]       [L-R]
                //     / \         / \
                // [L-L] [ R ] [...] [...]
 
                // fix bounds and heights
                node.aabb.combine(ll.aabb, r.aabb);
                t = llh - rh;
                node.height = llh - (t & t >> 31) + 1;
 
                l.aabb.combine(node.aabb, lr.aabb);
                t = nh - lrh;
                l.height = nh - (t & t >> 31) + 1;
            }
            // set new parent of L
            if (p != null) {
                if (p.child1 == node) {
                    p.child1 = l;
                } else {
                    p.child2 = l;
                }
            } else {
                this.root = l;
            }
            l.parent = p;
            return l;
        } else if (balance < -1) {
            var rl = r.child1;
            var rr = r.child2;
            var rlh = rl.height;
            var rrh = rr.height;
 
            // Is R-L higher than R-R?
            if (rlh > rrh) {
                // set N to R-R
                r.child2 = node;
                node.parent = r;
 
                //          [ R ]
                //         /     \
                //    [R-L]       [ N ]
                //     / \         / \
                // [...] [...] [ L ] [ R ]
 
                // set R-R
                node.child2 = rr;
                rr.parent = node;
 
                //          [ R ]
                //         /     \
                //    [R-L]       [ N ]
                //     / \         / \
                // [...] [...] [ L ] [R-R]
 
                // fix bounds and heights
                node.aabb.combine(l.aabb, rr.aabb);
                t = lh - rrh;
                node.height = lh - (t & t >> 31) + 1;
                r.aabb.combine(rl.aabb, node.aabb);
                t = rlh - nh;
                r.height = rlh - (t & t >> 31) + 1;
            } else {
                // set N to R-L
                r.child1 = node;
                node.parent = r;
                //          [ R ]
                //         /     \
                //    [ N ]       [R-R]
                //     / \         / \
                // [ L ] [ R ] [...] [...]
 
                // set R-L
                node.child2 = rl;
                rl.parent = node;
 
                //          [ R ]
                //         /     \
                //    [ N ]       [R-R]
                //     / \         / \
                // [ L ] [R-L] [...] [...]
 
                // fix bounds and heights
                node.aabb.combine(l.aabb, rl.aabb);
                t = lh - rlh;
                node.height = lh - (t & t >> 31) + 1;
                r.aabb.combine(node.aabb, rr.aabb);
                t = nh - rrh;
                r.height = nh - (t & t >> 31) + 1;
            }
            // set new parent of R
            if (p != null) {
                if (p.child1 == node) {
                    p.child1 = r;
                } else {
                    p.child2 = r;
                }
            } else {
                this.root = r;
            }
            r.parent = p;
            return r;
        }
        return node;
    },
    fix: function (node) {
        var c1 = node.child1;
        var c2 = node.child2;
        node.aabb.combine(c1.aabb, c2.aabb);
        //var h1 = c1.height;
        //var h2 = c2.height;
 
        node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
        /*if( h1 < h2 ) {
            node.height = h2+1;
        }else{
            node.height = h1+1;
        }*/
 
    }
}
/**
 * A broad-phase algorithm using dynamic bounding volume tree.
 * @author saharan
 * @author lo-th
 */
 
OIMO.DBVTBroadPhase = function () {
 
    OIMO.BroadPhase.call(this);
    this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
 
    this.tree = new OIMO.DBVT();
    this.stack = [];
    this.leaves = [];
    this.numLeaves = 0;
 
};
 
OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
 
OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
 
    return new OIMO.DBVTProxy(shape);
 
};
 
OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
 
    this.tree.insertLeaf(proxy.leaf);
    this.leaves.push(proxy.leaf);
    this.numLeaves++;
 
};
 
OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
 
    this.tree.deleteLeaf(proxy.leaf);
    var n = this.leaves.indexOf(proxy.leaf);
    if (n > -1) {
        this.leaves.splice(n, 1);
        this.numLeaves--;
    }
 
};
 
OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
 
    if (this.numLeaves < 2) return;
 
    var leaf, margin = 0.1, i = this.numLeaves;
 
    while (i--) {
 
        leaf = this.leaves[i];
 
        if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
 
            leaf.aabb.copy(leaf.proxy.aabb, margin);
            this.tree.deleteLeaf(leaf);
            this.tree.insertLeaf(leaf);
            this.collide(leaf, this.tree.root);
 
        }
    }
 
};
 
OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
 
    var stackCount = 2;
    var s1, s2, n1, n2, l1, l2;
    this.stack[0] = node1;
    this.stack[1] = node2;
 
    while (stackCount > 0) {
 
        n1 = this.stack[--stackCount];
        n2 = this.stack[--stackCount];
        l1 = n1.proxy != null;
        l2 = n2.proxy != null;
 
        this.numPairChecks++;
 
        if (l1 && l2) {
            s1 = n1.proxy.shape;
            s2 = n2.proxy.shape;
            if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
 
            this.addPair(s1, s2);
 
        } else {
 
            if (n1.aabb.intersectTest(n2.aabb)) continue;
 
            /*if(stackCount+4>=this.maxStack){// expand the stack
                //this.maxStack<<=1;
                this.maxStack*=2;
                var newStack = [];// vector
                newStack.length = this.maxStack;
                for(var i=0;i<stackCount;i++){
                    newStack[i] = this.stack[i];
                }
                this.stack = newStack;
            }*/
 
            if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
                this.stack[stackCount++] = n1.child1;
                this.stack[stackCount++] = n2;
                this.stack[stackCount++] = n1.child2;
                this.stack[stackCount++] = n2;
            } else {
                this.stack[stackCount++] = n1;
                this.stack[stackCount++] = n2.child1;
                this.stack[stackCount++] = n1;
                this.stack[stackCount++] = n2.child2;
            }
        }
    }
 
};
/**
* A node of the dynamic bounding volume tree.
* @author saharan
*/
OIMO.DBVTNode = function () {
 
    // The first child node of this node.
    this.child1 = null;
    // The second child node of this node.
    this.child2 = null;
    //  The parent node of this tree.
    this.parent = null;
    // The proxy of this node. This has no value if this node is not leaf.
    this.proxy = null;
    // The maximum distance from leaf nodes.
    this.height = 0;
    // The AABB of this node.
    this.aabb = new OIMO.AABB();
 
};
/**
* A proxy for dynamic bounding volume tree broad-phase.
* @author saharan
*/
OIMO.DBVTProxy = function (shape) {
 
    OIMO.Proxy.call(this, shape);
    // The leaf of the proxy.
    this.leaf = new OIMO.DBVTNode();
    this.leaf.proxy = this;
 
};
 
OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
 
OIMO.DBVTProxy.prototype.update = function () {
 
};
OIMO.World.prototype.add = function (obj) {
    obj = obj || {};
 
    var type = obj.type || "box";
    if (typeof type === 'string') type = [type];// single shape
 
    if (type[0].substring(0, 5) == 'joint') { // is joint
 
        if (type[0] === 'joint') type[0] = 'jointHinge';
 
        var axe1 = obj.axe1 || [1, 0, 0];
        var axe2 = obj.axe2 || [1, 0, 0];
        var pos1 = obj.pos1 || [0, 0, 0];
        var pos2 = obj.pos2 || [0, 0, 0];
 
        pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
        pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
 
        var min, max;
        if (type[0] === "jointDistance") {
            min = obj.min || 0;
            max = obj.max || 10;
            min = min * OIMO.INV_SCALE;
            max = max * OIMO.INV_SCALE;
        } else {
            min = obj.min || 57.29578;
            max = obj.max || 0;
            min = min * OIMO.degtorad;
            max = max * OIMO.degtorad;
        }
 
        var limit = obj.limit || null;
        var spring = obj.spring || null;
        var motor = obj.motor || null;
 
        // joint setting
        var jc = new OIMO.JointConfig();
        jc.allowCollision = obj.collision || false;;
        jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
        jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
        jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
        jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
        if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
        if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
        jc.body1 = obj.body1;
        jc.body2 = obj.body2;
 
        var joint;
        switch (type[0]) {
            case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
                if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
                if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
                break;
            case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
                if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
                if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
                break;
            case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
            case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
            case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
            case "jointWheel": joint = new OIMO.WheelJoint(jc);
                if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
                if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
                if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
                break;
        }
 
        joint.name = obj.name || '';
        // finaly add to physics world
        this.addJoint(joint);
        return joint;
 
    } else { // is body
 
        // I'm dynamique or not
        var move = obj.move || false;
 
        // I can sleep or not
        var noSleep = obj.noSleep || false;
 
        // My start position
        var p = obj.pos || [0, 0, 0];
        p = p.map(function (x) { return x * OIMO.INV_SCALE; });
 
        // My size 
        var s = obj.size || [1, 1, 1];
        s = s.map(function (x) { return x * OIMO.INV_SCALE; });
 
        // My rotation in degre
        var rot = obj.rot || [0, 0, 0];
        rot = rot.map(function (x) { return x * OIMO.degtorad; });
        var r = [];
        for (var i = 0; i < rot.length / 3; i++) {
            var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
            r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
        }
 
        // My physics setting
        var sc = new OIMO.ShapeConfig();
        if (obj.sc !== undefined) sc = obj.sc;
 
        if (obj.config) {
            // The density of the shape.
            sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
            // The coefficient of friction of the shape.
            sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
            // The coefficient of restitution of the shape.
            sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
            // The bits of the collision groups to which the shape belongs.
            sc.belongsTo = obj.config[3] || 1;
            //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
            // The bits of the collision groups with which the shape collides.
            sc.collidesWith = obj.config[4] || 0xffffffff;
            //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
        }
 
        // direct physics setting
 
        if (obj.density !== undefined) sc.density = obj.density;
        if (obj.friction !== undefined) sc.friction = obj.friction;
        if (obj.restitution !== undefined) sc.restitution = obj.restitution;
        if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
        if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
 
 
 
        if (obj.massPos) {
            obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
            sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
        }
        if (obj.massRot) {
            obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
            sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
        }
 
        // My rigidbody
        var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
 
        // My shapes
        var shapes = [];
 
        //if( typeof type === 'string' ) type = [type];// single shape
 
        var n, n2;
        for (var i = 0; i < type.length; i++) {
            n = i * 3;
            n2 = i * 4;
            switch (type[i]) {
                case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
                case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
                case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
            }
            body.addShape(shapes[i]);
            if (i > 0) {
                //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
                shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
                if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
            }
        }
 
        // I'm static or i move
        if (move) {
            if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
            else body.setupMass(0x1, true);
            if (noSleep) body.allowSleep = false;
            else body.allowSleep = true;
        } else {
            body.setupMass(0x2);
        }
 
        body.name = obj.name || ' ';
        // finaly add to physics world
        this.addRigidBody(body);
        return body;
    }
}
 
 
 
Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.core.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.core.js

Statements: 3.79% (347 / 9152)      Branches: 0.34% (32 / 9281)      Functions: 1.64% (56 / 3423)      Lines: 95.83% (23 / 24)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 2830 16 2 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1        
var __decorate=this&&this.__decorate||function(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},__extends=this&&this.__extends||function(e,t){function i(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);i.prototype=t.prototype,e.prototype=new i},BABYLON;!(function(e){e.ToGammaSpace=1/2.2,e.ToLinearSpace=2.2,e.Epsilon=.001;var t=(function(){function e(){}return e.WithinEpsilon=function(e,t,i){void 0===i&&(i=1.401298e-45);var r=e-t;return-i<=r&&r<=i},e.ToHex=function(e){var t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()},e.Sign=function(e){return e=+e,0===e||isNaN(e)?e:e>0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e})();e.MathTools=t;var i=(function(){function i(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.r=e,this.g=t,this.b=i}return i.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},i.prototype.getClassName=function(){return"Color3"},i.prototype.getHashCode=function(){var e=this.r||0;return e=397*e^(this.g||0),e=397*e^(this.b||0)},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this},i.prototype.toColor4=function(e){return void 0===e&&(e=1),new r(this.r,this.g,this.b,e)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(e){return new i(this.r*e.r,this.g*e.g,this.b*e.b)},i.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this},i.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b},i.prototype.equalsFloats=function(e,t,i){return this.r===e&&this.g===t&&this.b===i},i.prototype.scale=function(e){return new i(this.r*e,this.g*e,this.b*e)},i.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this},i.prototype.add=function(e){return new i(this.r+e.r,this.g+e.g,this.b+e.b)},i.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this},i.prototype.subtract=function(e){return new i(this.r-e.r,this.g-e.g,this.b-e.b)},i.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},i.prototype.copyFromFloats=function(e,t,i){return this.r=e,this.g=t,this.b=i,this},i.prototype.toHexString=function(){var e=255*this.r|0,i=255*this.g|0,r=255*this.b|0;return"#"+t.ToHex(e)+t.ToHex(i)+t.ToHex(r)},i.prototype.toLinearSpace=function(){var e=new i;return this.toLinearSpaceToRef(e),e},i.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,e.ToLinearSpace),t.g=Math.pow(this.g,e.ToLinearSpace),t.b=Math.pow(this.b,e.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var e=new i;return this.toGammaSpaceToRef(e),e},i.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,e.ToGammaSpace),t.g=Math.pow(this.g,e.ToGammaSpace),t.b=Math.pow(this.b,e.ToGammaSpace),this},i.FromHexString=function(e){if("#"!==e.substring(0,1)||7!==e.length)return new i(0,0,0);var t=parseInt(e.substring(1,3),16),r=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return i.FromInts(t,r,n)},i.FromArray=function(e,t){return void 0===t&&(t=0),new i(e[t],e[t+1],e[t+2])},i.FromInts=function(e,t,r){return new i(e/255,t/255,r/255)},i.Lerp=function(e,t,r){var n=e.r+(t.r-e.r)*r,o=e.g+(t.g-e.g)*r,s=e.b+(t.b-e.b)*r;return new i(n,o,s)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i})();e.Color3=i;var r=(function(){function e(e,t,i,r){this.r=e,this.g=t,this.b=i,this.a=r}return e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this},e.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t,this.a*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t},e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},e.prototype.getClassName=function(){return"Color4"},e.prototype.getHashCode=function(){var e=this.r||0;return e=397*e^(this.g||0),e=397*e^(this.b||0),e=397*e^(this.a||0)},e.prototype.clone=function(){return new e(this.r,this.g,this.b,this.a)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},e.prototype.toHexString=function(){var e=255*this.r|0,i=255*this.g|0,r=255*this.b|0,n=255*this.a|0;return"#"+t.ToHex(e)+t.ToHex(i)+t.ToHex(r)+t.ToHex(n)},e.FromHexString=function(t){if("#"!==t.substring(0,1)||9!==t.length)return new e(0,0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16),o=parseInt(t.substring(7,9),16);return e.FromInts(i,r,n,o)},e.Lerp=function(t,i,r){var n=new e(0,0,0,0);return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromInts=function(t,i,r,n){return new e(t/255,i/255,r/255,n/255)},e.CheckColors4=function(e,t){if(e.length===3*t){for(var i=[],r=0;r<e.length;r+=3){var n=r/3*4;i[n]=e[r],i[n+1]=e[r+1],i[n+2]=e[r+2],i[n+3]=1}return i}return e},e})();e.Color4=r;var n=(function(){function i(e,t){this.x=e,this.y=t}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+"}"},i.prototype.getClassName=function(){return"Vector2"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0)},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,this},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this},i.prototype.copyFromFloats=function(e,t){return this.x=e,this.y=t,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,this},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this},i.prototype.addVector3=function(e){return new i(this.x+e.x,this.y+e.y)},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,this},i.prototype.multiplyByFloats=function(e,t){return new i(this.x*e,this.y*t)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,this},i.prototype.negate=function(){return new i((-this.x),(-this.y))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e)},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(e,t){return void 0===t&&(t=0),new i(e[t],e[t+1])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1]},i.CatmullRom=function(e,t,r,n,o){var s=o*o,a=o*s,h=.5*(2*t.x+(-e.x+r.x)*o+(2*e.x-5*t.x+4*r.x-n.x)*s+(-e.x+3*t.x-3*r.x+n.x)*a),c=.5*(2*t.y+(-e.y+r.y)*o+(2*e.y-5*t.y+4*r.y-n.y)*s+(-e.y+3*t.y-3*r.y+n.y)*a);return new i(h,c)},i.Clamp=function(e,t,r){var n=e.x;n=n>r.x?r.x:n,n=n<t.x?t.x:n;var o=e.y;return o=o>r.y?r.y:o,o=o<t.y?t.y:o,new i(n,o)},i.Hermite=function(e,t,r,n,o){var s=o*o,a=o*s,h=2*a-3*s+1,c=-2*a+3*s,l=a-2*s+o,u=a-s,f=e.x*h+r.x*c+t.x*l+n.x*u,d=e.y*h+r.y*c+t.y*l+n.y*u;return new i(f,d)},i.Lerp=function(e,t,r){var n=e.x+(t.x-e.x)*r,o=e.y+(t.y-e.y)*r;return new i(n,o)},i.Dot=function(e,t){return e.x*t.x+e.y*t.y},i.Normalize=function(e){var t=e.clone();return t.normalize(),t},i.Minimize=function(e,t){var r=e.x<t.x?e.x:t.x,n=e.y<t.y?e.y:t.y;return new i(r,n)},i.Maximize=function(e,t){var r=e.x>t.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new i(r,n)},i.Transform=function(e,t){var r=i.Zero();return i.TransformToRef(e,t,r),r},i.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},i.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i.DistanceOfPointFromSegment=function(e,t,r){var n=i.DistanceSquared(t,r);if(0===n)return i.Distance(e,t);var o=r.subtract(t),s=Math.max(0,Math.min(1,i.Dot(e.subtract(t),o)/n)),a=t.add(o.multiplyByFloats(s,s));return i.Distance(e,a)},i})();e.Vector2=n;var o=(function(){function i(e,t,i){this.x=e,this.y=t,this.z=i}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},i.prototype.getClassName=function(){return"Vector3"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},i.prototype.toQuaternion=function(){var e=new h(0,0,0,1),t=Math.cos(.5*(this.x+this.z)),i=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),o=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return e.x=r*s,e.y=-n*s,e.z=i*o,e.w=t*o,e},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y,this.z+e.z)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y,this.z-e.z)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},i.prototype.subtractFromFloats=function(e,t,r){return new i(this.x-e,this.y-t,this.z-r)},i.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},i.prototype.negate=function(){return new i((-this.x),(-this.y),(-this.z))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e,this.z*e)},i.prototype.scaleToRef=function(e,t){t.x=this.x*e,t.y=this.y*e,t.z=this.z*e},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)&&t.WithinEpsilon(this.z,i.z,r)},i.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y,this.z*e.z)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},i.prototype.multiplyByFloats=function(e,t,r){return new i(this.x*e,this.y*t,this.z*r)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y,this.z/e.z)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},i.prototype.MinimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this},i.prototype.MaximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},i.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},i.GetClipFactor=function(e,t,r,n){var o=i.Dot(e,r)-n,s=i.Dot(t,r)-n,a=o/(o-s);return a},i.FromArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2])},i.FromFloatArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},i.FromFloatArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},i.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.Forward=function(){return new i(0,0,1)},i.Right=function(){return new i(1,0,0)},i.Left=function(){return new i((-1),0,0)},i.TransformCoordinates=function(e,t){var r=i.Zero();return i.TransformCoordinatesToRef(e,t,r),r},i.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},i.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],h=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/h,n.y=s/h,n.z=a/h},i.TransformNormal=function(e,t){var r=i.Zero();return i.TransformNormalToRef(e,t,r),r},i.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},i.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},i.CatmullRom=function(e,t,r,n,o){var s=o*o,a=o*s,h=.5*(2*t.x+(-e.x+r.x)*o+(2*e.x-5*t.x+4*r.x-n.x)*s+(-e.x+3*t.x-3*r.x+n.x)*a),c=.5*(2*t.y+(-e.y+r.y)*o+(2*e.y-5*t.y+4*r.y-n.y)*s+(-e.y+3*t.y-3*r.y+n.y)*a),l=.5*(2*t.z+(-e.z+r.z)*o+(2*e.z-5*t.z+4*r.z-n.z)*s+(-e.z+3*t.z-3*r.z+n.z)*a);return new i(h,c,l)},i.Clamp=function(e,t,r){var n=e.x;n=n>r.x?r.x:n,n=n<t.x?t.x:n;var o=e.y;o=o>r.y?r.y:o,o=o<t.y?t.y:o;var s=e.z;return s=s>r.z?r.z:s,s=s<t.z?t.z:s,new i(n,o,s)},i.Hermite=function(e,t,r,n,o){var s=o*o,a=o*s,h=2*a-3*s+1,c=-2*a+3*s,l=a-2*s+o,u=a-s,f=e.x*h+r.x*c+t.x*l+n.x*u,d=e.y*h+r.y*c+t.y*l+n.y*u,p=e.z*h+r.z*c+t.z*l+n.z*u;return new i(f,d,p)},i.Lerp=function(e,t,r){var n=e.x+(t.x-e.x)*r,o=e.y+(t.y-e.y)*r,s=e.z+(t.z-e.z)*r;return new i(n,o,s)},i.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z},i.Cross=function(e,t){var r=i.Zero();return i.CrossToRef(e,t,r),r},i.CrossToRef=function(e,t,i){M.Vector3[0].x=e.y*t.z-e.z*t.y,M.Vector3[0].y=e.z*t.x-e.x*t.z,M.Vector3[0].z=e.x*t.y-e.y*t.x,i.copyFrom(M.Vector3[0])},i.Normalize=function(e){var t=i.Zero();return i.NormalizeToRef(e,t),t},i.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},i.Project=function(e,t,r,n){var o=n.width,s=n.height,a=n.x,h=n.y,l=i._viewportMatrixCache?i._viewportMatrixCache:i._viewportMatrixCache=new c;c.FromValuesToRef(o/2,0,0,0,0,-s/2,0,0,0,0,1,0,a+o/2,s/2+h,0,1,l);var u=i._matrixCache?i._matrixCache:i._matrixCache=new c;return t.multiplyToRef(r,u),u.multiplyToRef(l,u),i.TransformCoordinates(e,u)},i.UnprojectFromTransform=function(e,r,n,o,s){var a=i._matrixCache?i._matrixCache:i._matrixCache=new c;o.multiplyToRef(s,a),a.invert(),e.x=e.x/r*2-1,e.y=-(e.y/n*2-1);var h=i.TransformCoordinates(e,a),l=e.x*a.m[3]+e.y*a.m[7]+e.z*a.m[11]+a.m[15];return t.WithinEpsilon(l,1)&&(h=h.scale(1/l)),h},i.Unproject=function(e,r,n,o,s,a){var h=i._matrixCache?i._matrixCache:i._matrixCache=new c;o.multiplyToRef(s,h),h.multiplyToRef(a,h),h.invert();var l=new i(e.x/r*2-1,(-(e.y/n*2-1)),e.z),u=i.TransformCoordinates(l,h),f=l.x*h.m[3]+l.y*h.m[7]+l.z*h.m[11]+h.m[15];return t.WithinEpsilon(f,1)&&(u=u.scale(1/f)),u},i.Minimize=function(e,t){var i=e.clone();return i.MinimizeInPlace(t),i},i.Maximize=function(e,t){var i=e.clone();return i.MaximizeInPlace(t),i},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z;return i*i+r*r+n*n},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i.RotationFromAxis=function(e,t,r){var n=i.Zero();return i.RotationFromAxisToRef(e,t,r,n),n},i.RotationFromAxisToRef=function(r,n,o,s){var a=r.normalize(),h=o.normalize(),c=d.X,l=d.Y,u=0,f=0,p=0,m=0,g=0,_=0,v=0,y=-1,x=0,b=M.Vector3[0],A=0,T=M.Vector3[1];t.WithinEpsilon(h.z,0,e.Epsilon)?_=1:t.WithinEpsilon(h.x,0,e.Epsilon)?m=1:(v=h.z/h.x,m=-v*Math.sqrt(1/(1+v*v)),_=Math.sqrt(1/(1+v*v))),T.x=m,T.y=g,T.z=_,T.normalize(),i.CrossToRef(a,T,b),b.normalize(),i.Dot(h,b)<0&&(y=1),A=i.Dot(a,T),A=Math.min(1,Math.max(-1,A)),p=Math.acos(A)*y,i.Dot(T,c)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),x++);var E=M.Vector3[2],P=M.Vector3[3];m=0,g=0,_=0,y=-1,t.WithinEpsilon(h.z,0,e.Epsilon)?m=1:(v=T.z/T.x,m=-v*Math.sqrt(1/(1+v*v)),_=Math.sqrt(1/(1+v*v))),E.x=m,E.y=g,E.z=_,E.normalize(),i.CrossToRef(E,T,P),P.normalize(),i.CrossToRef(h,E,b),b.normalize(),i.Dot(T,b)<0&&(y=1),A=i.Dot(h,E),A=Math.min(1,Math.max(-1,A)),f=Math.acos(A)*y,i.Dot(P,l)<0&&(f=Math.PI+f,x++),y=-1,i.CrossToRef(c,T,b),b.normalize(),i.Dot(b,l)<0&&(y=1),A=i.Dot(T,c),A=Math.min(1,Math.max(-1,A)),u=-Math.acos(A)*y,A<0&&x<2&&(u=Math.PI+u),s.x=f,s.y=u,s.z=p},i})();e.Vector3=o;var s=(function(){function i(e,t,i,r){this.x=e,this.y=t,this.z=i,this.w=r}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},i.prototype.getClassName=function(){return"Vector4"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,this},i.prototype.subtractFromFloats=function(e,t,r,n){return new i(this.x-e,this.y-t,this.z-r,this.w-n)},i.prototype.subtractFromFloatsToRef=function(e,t,i,r,n){return n.x=this.x-e,n.y=this.y-t,n.z=this.z-i,n.w=this.w-r,this},i.prototype.negate=function(){return new i((-this.x),(-this.y),(-this.z),(-this.w))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e,this.z*e,this.w*e)},i.prototype.scaleToRef=function(e,t){t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)&&t.WithinEpsilon(this.z,i.z,r)&&t.WithinEpsilon(this.w,i.w,r)},i.prototype.equalsToFloats=function(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,this},i.prototype.multiplyByFloats=function(e,t,r,n){return new i(this.x*e,this.y*t,this.z*r,this.w*n)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,this},i.prototype.MinimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this},i.prototype.MaximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toVector3=function(){return new o(this.x,this.y,this.z)},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},i.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},i.FromArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2],e[t+3])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},i.FromFloatArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},i.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(e){var t=i.Zero();return i.NormalizeToRef(e,t),t},i.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},i.Minimize=function(e,t){var i=e.clone();return i.MinimizeInPlace(t),i},i.Maximize=function(e,t){var i=e.clone();return i.MaximizeInPlace(t),i},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i})();e.Vector4=s;var a=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){this.width=e,this.height=t},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){var i=new e(this.width+t.width,this.height+t.height);return i},e.prototype.substract=function(t){var i=new e(this.width-t.width,this.height-t.height);return i},e.Lerp=function(t,i,r){var n=t.width+(i.width-t.width)*r,o=t.height+(i.height-t.height)*r;return new e(n,o)},e})();e.Size=a;var h=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){var t=new e((-this.x),(-this.y),(-this.z),this.w);return t},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=o.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,h=r*r,c=n*n,l=n*i-r*o,u=.4999999;return l<-u?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):l>u?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-h+c+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-h-c+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,h=this.y*this.z,c=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(h+c),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(h-c),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],h=r[5],c=r[9],l=r[2],u=r[6],f=r[10],d=n+h+f;d>0?(i=.5/Math.sqrt(d+1),t.w=.25/i,t.x=(u-c)*i,t.y=(s-l)*i,t.z=(a-o)*i):n>h&&n>f?(i=2*Math.sqrt(1+n-h-f),t.w=(u-c)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+l)/i):h>f?(i=2*Math.sqrt(1+h-n-f),t.w=(s-l)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(c+u)/i):(i=2*Math.sqrt(1+f-n-h),t.w=(a-o)/i,t.x=(s+l)/i,t.y=(c+u)/i,t.z=.25*i)},e.Inverse=function(t){return new e((-t.x),(-t.y),(-t.z),t.w)},e.Identity=function(){return new e(0,0,0,1)},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),h=Math.cos(n),c=Math.sin(o),l=Math.cos(o),u=Math.sin(s),f=Math.cos(s);r.x=f*c*h+u*l*a,r.y=u*l*h-f*c*a,r.z=f*l*a-u*c*h,r.w=f*l*h+u*c*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=i,a=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,h=!1;if(a<0&&(h=!0,a=-a),a>.999999)o=1-s,n=h?-s:s;else{var c=Math.acos(a),l=1/Math.sin(c);o=Math.sin((1-s)*c)*l,n=h?-Math.sin(s*c)*l:Math.sin(s*c)*l}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e})();e.Quaternion=h;var c=(function(){function e(){this.m=new Float32Array(16)}return e.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],h=this.m[7],c=this.m[8],l=this.m[9],u=this.m[10],f=this.m[11],d=this.m[12],p=this.m[13],m=this.m[14],g=this.m[15],_=u*g-f*m,v=l*g-f*p,y=l*m-u*p,x=c*g-f*d,b=c*m-u*d,A=c*p-l*d,T=s*_-a*v+h*y,E=-(o*_-a*x+h*b),M=o*v-s*x+h*A,P=-(o*y-s*b+a*A),S=1/(t*T+i*E+r*M+n*P),C=a*g-h*m,R=s*g-h*p,O=s*m-a*p,D=o*g-h*d,I=o*m-a*d,L=o*p-s*d,w=a*f-h*u,B=s*f-h*l,F=s*u-a*l,V=o*f-h*c,N=o*u-a*c,U=o*l-s*c;return e.m[0]=T*S,e.m[4]=E*S,e.m[8]=M*S,e.m[12]=P*S,e.m[1]=-(i*_-r*v+n*y)*S,e.m[5]=(t*_-r*x+n*b)*S,e.m[9]=-(t*v-i*x+n*A)*S,e.m[13]=(t*y-i*b+r*A)*S,e.m[2]=(i*C-r*R+n*O)*S,
e.m[6]=-(t*C-r*D+n*I)*S,e.m[10]=(t*R-i*D+n*L)*S,e.m[14]=-(t*O-i*I+r*L)*S,e.m[3]=-(i*w-r*B+n*F)*S,e.m[7]=(t*w-r*V+n*N)*S,e.m[11]=-(t*B-i*V+n*U)*S,e.m[15]=(t*F-i*N+r*U)*S,this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this},e.prototype.getTranslation=function(){return new o(this.m[12],this.m[13],this.m[14])},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],h=this.m[5],c=this.m[6],l=this.m[7],u=this.m[8],f=this.m[9],d=this.m[10],p=this.m[11],m=this.m[12],g=this.m[13],_=this.m[14],v=this.m[15],y=e.m[0],x=e.m[1],b=e.m[2],A=e.m[3],T=e.m[4],E=e.m[5],M=e.m[6],P=e.m[7],S=e.m[8],C=e.m[9],R=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],L=e.m[14],w=e.m[15];return t[i]=r*y+n*T+o*S+s*D,t[i+1]=r*x+n*E+o*C+s*I,t[i+2]=r*b+n*M+o*R+s*L,t[i+3]=r*A+n*P+o*O+s*w,t[i+4]=a*y+h*T+c*S+l*D,t[i+5]=a*x+h*E+c*C+l*I,t[i+6]=a*b+h*M+c*R+l*L,t[i+7]=a*A+h*P+c*O+l*w,t[i+8]=u*y+f*T+d*S+p*D,t[i+9]=u*x+f*E+d*C+p*I,t[i+10]=u*b+f*M+d*R+p*L,t[i+11]=u*A+f*P+d*O+p*w,t[i+12]=m*y+g*T+_*S+v*D,t[i+13]=m*x+g*E+_*C+v*I,t[i+14]=m*b+g*M+_*R+v*L,t[i+15]=m*A+g*P+_*O+v*w,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(i,r,n){n.x=this.m[12],n.y=this.m[13],n.z=this.m[14];var o=t.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=t.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return i.x=o*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),i.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),i.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===i.x||0===i.y||0===i.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(e.FromValuesToRef(this.m[0]/i.x,this.m[1]/i.x,this.m[2]/i.x,0,this.m[4]/i.y,this.m[5]/i.y,this.m[6]/i.y,0,this.m[8]/i.z,this.m[9]/i.z,this.m[10]/i.z,0,0,0,0,1,M.Matrix[0]),h.FromRotationMatrixToRef(M.Matrix[0],r),!0)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=i[0]*i[1]*i[2]*i[3]<0?-1:1,n=i[4]*i[5]*i[6]*i[7]<0?-1:1,o=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=r*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),a=n*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),h=o*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);e.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/a,i[5]/a,i[6]/a,0,i[8]/h,i[9]/h,i[10]/h,0,0,0,0,1,t)},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t]},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,h,c,l,u,f,d,p,m,g){g.m[0]=e,g.m[1]=t,g.m[2]=i,g.m[3]=r,g.m[4]=n,g.m[5]=o,g.m[6]=s,g.m[7]=a,g.m[8]=h,g.m[9]=c,g.m[10]=l,g.m[11]=u,g.m[12]=f,g.m[13]=d,g.m[14]=p,g.m[15]=m},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new s(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this},e.FromValues=function(t,i,r,n,o,s,a,h,c,l,u,f,d,p,m,g){var _=new e;return _.m[0]=t,_.m[1]=i,_.m[2]=r,_.m[3]=n,_.m[4]=o,_.m[5]=s,_.m[6]=a,_.m[7]=h,_.m[8]=c,_.m[9]=l,_.m[10]=u,_.m[11]=f,_.m[12]=d,_.m[13]=p,_.m[14]=m,_.m[15]=g,_},e.Compose=function(t,i,r){var n=e.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),o=e.Identity();return i.toRotationMatrix(o),n=n.multiply(o),n.setTranslation(r),n},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0,i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){h.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){for(var n=e.Zero(),o=0;o<16;o++)n.m[o]=t.m[o]*(1-r)+i.m[o]*r;return n},e.DecomposeLerp=function(t,i,r){var n=new o(0,0,0),s=new h,a=new o(0,0,0);t.decompose(n,s,a);var c=new o(0,0,0),l=new h,u=new o(0,0,0);i.decompose(c,l,u);var f=o.Lerp(n,c,r),d=h.Slerp(s,l,r),p=o.Lerp(a,u,r);return e.Compose(f,d,p)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,n){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-o.Dot(this._xAxis,t),a=-o.Dot(this._yAxis,t),h=-o.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,h,1,n)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,n){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-o.Dot(this._xAxis,t),a=-o.Dot(this._yAxis,t),h=-o.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,h,1,n)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=2/t,a=2/i,h=1/(n-r),c=r/(r-n);e.FromValuesToRef(s,0,0,0,0,a,0,0,0,0,h,0,0,0,c,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(e,t,i,r,n,o,s){s.m[0]=2/(t-e),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-i),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(o-n),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(e+t)/(e-t),s.m[13]=(r+i)/(i-r),s.m[14]=-n/(o-n),s.m[15]=1},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero();return o.m[0]=2*r/t,o.m[1]=o.m[2]=o.m[3]=0,o.m[5]=2*r/i,o.m[4]=o.m[6]=o.m[7]=0,o.m[10]=-n/(r-n),o.m[8]=o.m[9]=0,o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(e,t,i,r,n,o){void 0===o&&(o=!0);var s=1/Math.tan(.5*e);o?n.m[0]=s/t:n.m[0]=s,n.m[1]=n.m[2]=n.m[3]=0,o?n.m[5]=s:n.m[5]=s*t,n.m[4]=n.m[6]=n.m[7]=0,n.m[8]=n.m[9]=0,n.m[10]=r/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(i*r)/(r-i)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(e,t,i,r,n,o){void 0===o&&(o=!0);var s=1/Math.tan(.5*e);o?n.m[0]=s/t:n.m[0]=s,n.m[1]=n.m[2]=n.m[3]=0,o?n.m[5]=s:n.m[5]=s*t,n.m[4]=n.m[6]=n.m[7]=0,n.m[8]=n.m[9]=0,n.m[10]=r/(i-r),n.m[11]=-1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!0);var o=Math.tan(e.upDegrees*Math.PI/180),s=Math.tan(e.downDegrees*Math.PI/180),a=Math.tan(e.leftDegrees*Math.PI/180),h=Math.tan(e.rightDegrees*Math.PI/180),c=2/(a+h),l=2/(o+s);r.m[0]=c,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=l,r.m[6]=r.m[7]=0,r.m[8]=(a-h)*c*.5,r.m[9]=-((o-s)*l*.5),r.m[10]=-i/(t-i),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=t*i/(t-i)},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,h=t.height,c=t.x,l=t.y,u=e.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,s-o,0,c+a/2,h/2+l,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,h=e.y*e.w,c=e.y*e.z,l=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(c+l),t.m[7]=0,t.m[8]=2*(a+h),t.m[9]=2*(c-l),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1},e._tempQuaternion=new h,e._xAxis=o.Zero(),e._yAxis=o.Zero(),e._zAxis=o.Zero(),e})();e.Matrix=c;var l=(function(){function e(e,t,i,r){this.normal=new o(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=c.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d,a=r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],h=r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],l=r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],u=r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15];return new e(a,h,l,u)},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,h=i.y-e.y,c=i.z-e.z,l=o*c-s*h,u=s*a-n*c,f=n*h-o*a,d=Math.sqrt(l*l+u*u+f*f);return r=0!==d?1/d:0,this.normal.x=l*r,this.normal.y=u*r,this.normal.z=f*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){var i=o.Dot(this.normal,e);return i<=t},e.prototype.signedDistanceTo=function(e){return o.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return o.Dot(i,t)+r},e})();e.Plane=l;var u=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){return new e(this.x*t,this.y*i,this.width*t,this.height*i)},e})();e.Viewport=u;var f=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new l(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetPlanesToRef=function(e,t){t[0].normal.x=e.m[3]+e.m[2],t[0].normal.y=e.m[7]+e.m[6],t[0].normal.z=e.m[11]+e.m[10],t[0].d=e.m[15]+e.m[14],t[0].normalize(),t[1].normal.x=e.m[3]-e.m[2],t[1].normal.y=e.m[7]-e.m[6],t[1].normal.z=e.m[11]-e.m[10],t[1].d=e.m[15]-e.m[14],t[1].normalize(),t[2].normal.x=e.m[3]+e.m[0],t[2].normal.y=e.m[7]+e.m[4],t[2].normal.z=e.m[11]+e.m[8],t[2].d=e.m[15]+e.m[12],t[2].normalize(),t[3].normal.x=e.m[3]-e.m[0],t[3].normal.y=e.m[7]-e.m[4],t[3].normal.z=e.m[11]-e.m[8],t[3].d=e.m[15]-e.m[12],t[3].normalize(),t[4].normal.x=e.m[3]-e.m[1],t[4].normal.y=e.m[7]-e.m[5],t[4].normal.z=e.m[11]-e.m[9],t[4].d=e.m[15]-e.m[13],t[4].normalize(),t[5].normal.x=e.m[3]+e.m[1],t[5].normal.y=e.m[7]+e.m[5],t[5].normal.z=e.m[11]+e.m[9],t[5].d=e.m[15]+e.m[13],t[5].normalize()},e})();e.Frustum=f,(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD"})(e.Space||(e.Space={}));var d=(e.Space,(function(){function e(){}return e.X=new o(1,0,0),e.Y=new o(0,1,0),e.Z=new o(0,0,1),e})());e.Axis=d;var p=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,h=e,c=0;c<5;c++){var l=h*h,u=l*h,f=o*u+s*l+a*h,d=1/(3*o*l+2*s*h+a);h-=(f-e)*d,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*i+3*(1-h)*Math.pow(h,2)*n+Math.pow(h,3)},e})();e.BezierCurve=p,(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(e.Orientation||(e.Orientation={}));var m=e.Orientation,g=(function(){function e(e){var t=this;this.degrees=function(){return 180*t._radians/Math.PI},this.radians=function(){return t._radians},this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.BetweenTwoPoints=function(t,i){var r=i.subtract(t),n=Math.atan2(r.y,r.x);return new e(n)},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=g;var _=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var r=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,s=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new n((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=g.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),c=g.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=g.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-h>180&&(c-=360),c-h<-180&&(c+=360),l-c>180&&(l-=360),l-c<-180&&(l+=360),this.orientation=c-h<0?m.CW:m.CCW,this.angle=g.FromDegrees(this.orientation===m.CW?h-l:l-h)}return e})();e.Arc2=_;var v=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(e,t))}return e.prototype.addLineTo=function(e,t){if(closed)return this;var i=new n(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this},e.prototype.addArcTo=function(e,t,i,r,o){if(void 0===o&&(o=36),closed)return this;var s=this._points[this._points.length-1],a=new n(e,t),h=new n(i,r),c=new _(s,a,h),l=c.angle.radians()/o;c.orientation===m.CW&&(l*=-1);for(var u=c.startAngle.radians()+l,f=0;f<o;f++){var d=Math.cos(u)*c.radius+c.centerPoint.x,p=Math.sin(u)*c.radius+c.centerPoint.y;this.addLineTo(d,p),u+=l}return this},e.prototype.close=function(){return this.closed=!0,this},e.prototype.length=function(){var e=this._length;if(!this.closed){var t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e},e.prototype.getPoints=function(){return this._points},e.prototype.getPointAtLengthPosition=function(e){if(e<0||e>1)return n.Zero();for(var t=e*this.length(),i=0,r=0;r<this._points.length;r++){var o=(r+1)%this._points.length,s=this._points[r],a=this._points[o],h=a.subtract(s),c=h.length()+i;if(t>=i&&t<=c){var l=h.normalize(),u=t-i;return new n(s.x+l.x*u,s.y+l.y*u)}i=c}return n.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=v;var y=(function(){function i(e,t,i){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<e.length;r++)this._curve[r]=e[r].clone();this._raw=i||!1,this._compute(t)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(e,t){for(var i=0;i<e.length;i++)this._curve[i].x=e[i].x,this._curve[i].y=e[i].y,this._curve[i].z=e[i].z;return this._compute(t),this},i.prototype._compute=function(e){var t=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[t-1]=this._curve[t-1].subtract(this._curve[t-2]),this._raw||this._tangents[t-1].normalize();var i=this._tangents[0],r=this._normalVector(this._curve[0],i,e);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(i,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var n,s,a,h,c=1;c<t;c++)n=this._getLastNonNullVector(c),c<t-1&&(s=this._getFirstNonNullVector(c),this._tangents[c]=n.add(s),this._tangents[c].normalize()),this._distances[c]=this._distances[c-1]+n.length(),a=this._tangents[c],h=this._binormals[c-1],this._normals[c]=o.Cross(h,a),this._raw||this._normals[c].normalize(),this._binormals[c]=o.Cross(a,this._normals[c]),this._raw||this._binormals[c].normalize()},i.prototype._getFirstNonNullVector=function(e){for(var t=1,i=this._curve[e+t].subtract(this._curve[e]);0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i},i.prototype._getLastNonNullVector=function(e){for(var t=1,i=this._curve[e].subtract(this._curve[e-t]);0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},i.prototype._normalVector=function(i,r,n){var s,a=r.length();if(0===a&&(a=1),void 0===n||null===n){var h;t.WithinEpsilon(Math.abs(r.y)/a,1,e.Epsilon)?t.WithinEpsilon(Math.abs(r.x)/a,1,e.Epsilon)?t.WithinEpsilon(Math.abs(r.z)/a,1,e.Epsilon)||(h=new o(0,0,1)):h=new o(1,0,0):h=new o(0,(-1),0),s=o.Cross(r,h)}else s=o.Cross(r,n),o.CrossToRef(s,r,s);return s.normalize(),s},i})();e.Path3D=y;var x=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,n){n=n>2?n:3;for(var s=new Array,a=function(e,t,i,r){var n=(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;return n},h=0;h<=n;h++)s.push(new o(a(h/n,t.x,i.x,r.x),a(h/n,t.y,i.y,r.y),a(h/n,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,n,s){s=s>3?s:4;for(var a=new Array,h=function(e,t,i,r,n){var o=(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n;return o},c=0;c<=s;c++)a.push(new o(h(c/s,t.x,i.x,r.x,n.x),h(c/s,t.y,i.y,r.y,n.y),h(c/s,t.z,i.z,r.z,n.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,n,s){for(var a=new Array,h=1/s,c=0;c<=s;c++)a.push(o.Hermite(t,i,r,n,c*h));return new e(a)},e.prototype.getPoints=function(){return this._points},e.prototype.length=function(){return this._length},e.prototype["continue"]=function(t){for(var i=this._points[this._points.length-1],r=this._points.slice(),n=t.getPoints(),o=1;o<n.length;o++)r.push(n[o].subtract(n[0]).add(i));var s=new e(r);return s},e.prototype._computeLength=function(e){for(var t=0,i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t},e})();e.Curve3=x;var b=(function(){function e(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return e.prototype.addLight=function(e,t,i){var r=new o(t.r,t.g,t.b),n=r.scale(i);this.L00=this.L00.add(n.scale(.282095)),this.L1_1=this.L1_1.add(n.scale(.488603*e.y)),this.L10=this.L10.add(n.scale(.488603*e.z)),this.L11=this.L11.add(n.scale(.488603*e.x)),this.L2_2=this.L2_2.add(n.scale(1.092548*e.x*e.y)),this.L2_1=this.L2_1.add(n.scale(1.092548*e.y*e.z)),this.L21=this.L21.add(n.scale(1.092548*e.x*e.z)),this.L20=this.L20.add(n.scale(.315392*(3*e.z*e.z-1))),this.L22=this.L22.add(n.scale(.546274*(e.x*e.x-e.y*e.y)))},e.prototype.scale=function(e){this.L00=this.L00.scale(e),this.L1_1=this.L1_1.scale(e),this.L10=this.L10.scale(e),this.L11=this.L11.scale(e),this.L2_2=this.L2_2.scale(e),this.L2_1=this.L2_1.scale(e),this.L20=this.L20.scale(e),this.L21=this.L21.scale(e),this.L22=this.L22.scale(e)},e})();e.SphericalHarmonics=b;var A=(function(){function e(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return e.prototype.addAmbient=function(e){var t=new o(e.r,e.g,e.b);this.xx=this.xx.add(t),this.yy=this.yy.add(t),this.zz=this.zz.add(t)},e.getSphericalPolynomialFromHarmonics=function(t){var i=new e;return i.x=t.L11.scale(1.02333),i.y=t.L1_1.scale(1.02333),i.z=t.L10.scale(1.02333),i.xx=t.L00.scale(.886277).subtract(t.L20.scale(.247708)).add(t.L22.scale(.429043)),i.yy=t.L00.scale(.886277).subtract(t.L20.scale(.247708)).subtract(t.L22.scale(.429043)),i.zz=t.L00.scale(.886277).add(t.L20.scale(.495417)),i.yz=t.L2_1.scale(.858086),i.zx=t.L21.scale(.858086),i.xy=t.L2_2.scale(.858086),i},e})();e.SphericalPolynomial=A;var T=(function(){function e(e,t){void 0===e&&(e=o.Zero()),void 0===t&&(t=o.Up()),this.position=e,this.normal=t}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone())},e})();e.PositionNormalVertex=T;var E=(function(){function e(e,t,i){void 0===e&&(e=o.Zero()),void 0===t&&(t=o.Up()),void 0===i&&(i=n.Zero()),this.position=e,this.normal=t,this.uv=i}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone(),this.uv.clone())},e})();e.PositionNormalTextureVertex=E;var M=(function(){function e(){}return e.Color3=[i.Black(),i.Black(),i.Black()],e.Vector2=[n.Zero(),n.Zero(),n.Zero()],e.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],e.Vector4=[s.Zero(),s.Zero(),s.Zero()],e.Quaternion=[new h(0,0,0,0)],e.Matrix=[c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero()],e})();e.Tmp=M})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){function t(e,t){return function(i,r){i.__serializableMembers||(i.__serializableMembers={}),i.__serializableMembers[r]||(i.__serializableMembers[r]={type:e,sourceName:t})}}function i(e){return t(0,e)}function r(e){return t(1,e)}function n(e){return t(2,e)}function o(e){return t(3,e)}function s(e){return t(4,e)}function a(e){return t(5,e)}function h(e){return t(6,e)}function c(e){return t(7,e)}e.serialize=i,e.serializeAsTexture=r,e.serializeAsColor3=n,e.serializeAsFresnelParameters=o,e.serializeAsVector2=s,e.serializeAsVector3=a,e.serializeAsMeshReference=h,e.serializeAsColorCurves=c;var l=(function(){function t(){}return t.Serialize=function(t,i){i||(i={}),i.tags=e.Tags.GetTags(t);for(var r in t.__serializableMembers){var n=t.__serializableMembers[r],o=n.sourceName||r,s=n.type,a=t[r];if(void 0!==a&&null!==a)switch(s){case 0:i[o]=a;break;case 1:i[o]=a.serialize();break;case 2:i[o]=a.asArray();break;case 3:i[o]=a.serialize();break;case 4:i[o]=a.asArray();break;case 5:i[o]=a.asArray();break;case 6:i[o]=a.id;break;case 7:i[o]=a.serialize()}}return i},t.Parse=function(t,i,r,n){var o=t();e.Tags.AddTagsTo(o,i.tags);for(var s in o.__serializableMembers){var a=o.__serializableMembers[s],h=i[a.sourceName||s],c=a.type;if(void 0!==h&&null!==h)switch(c){case 0:o[s]=h;break;case 1:o[s]=e.Texture.Parse(h,r,n);break;case 2:o[s]=e.Color3.FromArray(h);break;case 3:o[s]=e.FresnelParameters.Parse(h);break;case 4:o[s]=e.Vector2.FromArray(h);break;case 5:o[s]=e.Vector3.FromArray(h);break;case 6:o[s]=r.getLastMeshByID(h);break;case 7:o[s]=e.ColorCurves.Parse(h)}}return o},t.Clone=function(t,i){var r=t();e.Tags.AddTagsTo(r,i.tags);for(var n in r.__serializableMembers){var o=r.__serializableMembers[n],s=i[n],a=o.type;if(void 0!==s&&null!==s)switch(a){case 0:case 6:r[n]=s;break;case 1:case 2:case 3:case 4:case 5:case 7:r[n]=s.clone()}}return r},t})();e.SerializationHelper=l})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t){void 0===t&&(t=!1),this.initalize(e,t)}return e.prototype.initalize=function(e,t){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this},e})();e.EventState=t;var i=(function(){function e(e,t){this.callback=e,this.mask=t}return e})();e.Observer=i;var r=(function(){function e(){this._observers=new Array,this._eventState=new t(0)}return e.prototype.add=function(e,t,r){if(void 0===t&&(t=-1),void 0===r&&(r=!1),!e)return null;var n=new i(e,t);return r?this._observers.unshift(n):this._observers.push(n),n},e.prototype.remove=function(e){var t=this._observers.indexOf(e);return t!==-1&&(this._observers.splice(t,1),!0)},e.prototype.removeCallback=function(e){for(var t=0;t<this._observers.length;t++)if(this._observers[t].callback===e)return this._observers.splice(t,1),!0;return!1},e.prototype.notifyObservers=function(e,t){void 0===t&&(t=-1);var i=this._eventState;i.mask=t,i.skipNextObservers=!1;for(var r=0,n=this._observers;r<n.length;r++){var o=n[r];if(o.mask&t&&o.callback(e,i),i.skipNextObservers)return!1}return!0},e.prototype.hasObservers=function(){return this._observers.length>0},e.prototype.clear=function(){this._observers=new Array},e.prototype.clone=function(){var t=new e;return t._observers=this._observers.slice(0),t},e})();e.Observable=r})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,i){this.idbFactory=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,this.callbackManifestChecked=i,this.currentSceneUrl=t.ReturnFullUrlLocation(e),this.db=null,this.enableSceneOffline=!1,this.enableTexturesOffline=!1,this.manifestVersionFound=0,this.mustUpdateRessources=!1,this.hasReachedQuota=!1,t.IDBStorageEnabled?this.checkManifestFile():this.callbackManifestChecked(!0)}return t.prototype.checkManifestFile=function(){function t(){r.enableSceneOffline=!1,r.enableTexturesOffline=!1,r.callbackManifestChecked(!1)}var i=this,r=this,n=!1,o=this.currentSceneUrl+".manifest",s=new XMLHttpRequest;navigator.onLine&&(n=!0,o=o+(null==o.match(/\?/)?"?":"&")+(new Date).getTime()),s.open("GET",o,!0),s.addEventListener("load",(function(){if(200===s.status||e.Tools.ValidateXHRData(s,1))try{var r=JSON.parse(s.response);i.enableSceneOffline=r.enableSceneOffline,i.enableTexturesOffline=r.enableTexturesOffline,r.version&&!isNaN(parseInt(r.version))&&(i.manifestVersionFound=r.version),i.callbackManifestChecked&&i.callbackManifestChecked(!0)}catch(n){t()}else t()}),!1),s.addEventListener("error",(function(e){if(n){n=!1;var r=i.currentSceneUrl+".manifest";s.open("GET",r,!0),s.send()}else t()}),!1);try{s.send()}catch(a){e.Tools.Error("Error on XHR send request."),r.callbackManifestChecked(!1)}},t.prototype.openAsync=function(t,i){function r(){o.isSupported=!1,i&&i()}var n=this,o=this;if(this.idbFactory&&(this.enableSceneOffline||this.enableTexturesOffline))if(this.db)t&&t();else{this.hasReachedQuota=!1,this.isSupported=!0;var s=this.idbFactory.open("babylonjs",1);s.onerror=function(e){r()},s.onblocked=function(t){e.Tools.Error("IDB request blocked. Please reload the page."),r()},s.onsuccess=function(e){n.db=s.result,t()},s.onupgradeneeded=function(t){n.db=t.target.result;try{n.db.createObjectStore("scenes",{keyPath:"sceneUrl"}),n.db.createObjectStore("versions",{keyPath:"sceneUrl"}),n.db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(i){e.Tools.Error("Error while creating object stores. Exception: "+i.message),r()}}}else this.isSupported=!1,i&&i()},t.prototype.loadImageFromDB=function(e,i){var r=this,n=t.ReturnFullUrlLocation(e),o=function(){r.hasReachedQuota||null===r.db?i.src=e:r._saveImageIntoDBAsync(n,i)};this.mustUpdateRessources?o():this._loadImageFromDBAsync(n,i,o)},t.prototype._loadImageFromDBAsync=function(t,i,r){if(this.isSupported&&null!==this.db){var n,o=this.db.transaction(["textures"]);o.onabort=function(e){i.src=t},o.oncomplete=function(o){var s;if(n){var a=window.URL||window.webkitURL;s=a.createObjectURL(n.data,{oneTimeOnly:!0}),i.onerror=function(){e.Tools.Error("Error loading image from blob URL: "+s+" switching back to web url: "+t),i.src=t},i.src=s}else r()};var s=o.objectStore("textures").get(t);s.onsuccess=function(e){n=e.target.result},s.onerror=function(r){e.Tools.Error("Error loading texture "+t+" from DB."),i.src=t}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i.src=t},t.prototype._saveImageIntoDBAsync=function(i,r){var n=this;if(this.isSupported){var o=function(){var e;if(s){var t=window.URL||window.webkitURL;try{e=t.createObjectURL(s,{oneTimeOnly:!0})}catch(i){e=t.createObjectURL(s)}}r.src=e};if(t.IsUASupportingBlobStorage){var s,a=new XMLHttpRequest;a.open("GET",i,!0),a.responseType="blob",a.addEventListener("load",(function(){if(200===a.status){s=a.response;var e=n.db.transaction(["textures"],"readwrite");e.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(n.hasReachedQuota=!0)}catch(t){}o()},e.oncomplete=function(e){o()};var h={textureUrl:i,data:s};try{var c=e.objectStore("textures").put(h);c.onsuccess=function(e){},c.onerror=function(e){o()}}catch(l){25===l.code&&(t.IsUASupportingBlobStorage=!1),r.src=i}}else r.src=i}),!1),a.addEventListener("error",(function(t){e.Tools.Error("Error in XHR request in BABYLON.Database."),r.src=i}),!1),a.send()}else r.src=i}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),
r.src=i},t.prototype._checkVersionFromDB=function(e,t){var i=this,r=function(r){i._saveVersionIntoDBAsync(e,t)};this._loadVersionFromDBAsync(e,t,r)},t.prototype._loadVersionFromDBAsync=function(t,i,r){var n=this;if(this.isSupported){var o;try{var s=this.db.transaction(["versions"]);s.oncomplete=function(e){o?n.manifestVersionFound>o.data?(n.mustUpdateRessources=!0,r()):i(o.data):(n.mustUpdateRessources=!0,r())},s.onabort=function(e){i(-1)};var a=s.objectStore("versions").get(t);a.onsuccess=function(e){o=e.target.result},a.onerror=function(r){e.Tools.Error("Error loading version for scene "+t+" from DB."),i(-1)}}catch(h){e.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: "+h.message),i(-1)}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i(-1)},t.prototype._saveVersionIntoDBAsync=function(t,i){var r=this;if(this.isSupported&&!this.hasReachedQuota)try{var n=this.db.transaction(["versions"],"readwrite");n.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(r.hasReachedQuota=!0)}catch(t){}i(-1)},n.oncomplete=function(e){i(r.manifestVersionFound)};var o={sceneUrl:t,data:this.manifestVersionFound},s=n.objectStore("versions").put(o);s.onsuccess=function(e){},s.onerror=function(t){e.Tools.Error("Error in DB add version request in BABYLON.Database.")}}catch(a){e.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+a.message),i(-1)}else i(-1)},t.prototype.loadFileFromDB=function(e,i,r,n,o){var s=this,a=t.ReturnFullUrlLocation(e),h=function(e){s._saveFileIntoDBAsync(a,i,r)};this._checkVersionFromDB(a,(function(e){e!==-1?s.mustUpdateRessources?s._saveFileIntoDBAsync(a,i,r,o):s._loadFileFromDBAsync(a,i,h,o):n()}))},t.prototype._loadFileFromDBAsync=function(t,i,r,n){if(this.isSupported){var o;o=t.indexOf(".babylon")!==-1?"scenes":"textures";var s,a=this.db.transaction([o]);a.oncomplete=function(e){s?i(s.data):r()},a.onabort=function(e){r()};var h=a.objectStore(o).get(t);h.onsuccess=function(e){s=e.target.result},h.onerror=function(i){e.Tools.Error("Error loading file "+t+" from DB."),r()}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.prototype._saveFileIntoDBAsync=function(t,i,r,n){var o=this;if(this.isSupported){var s;s=t.indexOf(".babylon")!==-1?"scenes":"textures";var a,h=new XMLHttpRequest;h.open("GET",t,!0),n&&(h.responseType="arraybuffer"),h.onprogress=r,h.addEventListener("load",(function(){if(200===h.status||e.Tools.ValidateXHRData(h,n?6:1))if(a=n?h.response:h.responseText,o.hasReachedQuota)i(a);else{var r=o.db.transaction([s],"readwrite");r.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(o.hasReachedQuota=!0)}catch(t){}i(a)},r.oncomplete=function(e){i(a)};var c;c="scenes"===s?{sceneUrl:t,data:a,version:o.manifestVersionFound}:{textureUrl:t,data:a};try{var l=r.objectStore(s).put(c);l.onsuccess=function(e){},l.onerror=function(t){e.Tools.Error("Error in DB add file request in BABYLON.Database.")}}catch(u){i(a)}}else i()}),!1),h.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),h.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t.parseURL=function(e){var t=document.createElement("a");t.href=e;var i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),n=e.substring(0,e.indexOf(r,0));return n},t.ReturnFullUrlLocation=function(e){return e.indexOf("http:/")===-1?t.parseURL(window.location.href)+e:e},t})();e.Database=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0,i={id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]};return i},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,h=!1,c=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:h=!0;break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:c=!0}var l,u,f=(15&o.flags,o.pixel_size>>3),d=o.width*o.height*f;if(a&&(u=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){l=new Uint8Array(d);for(var p,m,g,_=0,v=new Uint8Array(f);n<d&&_<d;)if(p=r[n++],m=(127&p)+1,128&p){for(g=0;g<f;++g)v[g]=r[n++];for(g=0;g<m;++g)l.set(v,_+g*f);_+=f*m}else{for(m*=f,g=0;g<m;++g)l[_+g]=r[n++];_+=m}}else l=r.subarray(n,n+=a?o.width*o.height:d);var y,x,b,A,T,E;switch((o.flags&t._ORIGIN_MASK)>>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:y=0,b=1,E=o.width,x=0,A=1,T=o.height;break;case t._ORIGIN_BL:y=0,b=1,E=o.width,x=o.height-1,A=-1,T=-1;break;case t._ORIGIN_UR:y=o.width-1,b=-1,E=-1,x=0,A=1,T=o.height;break;case t._ORIGIN_BR:y=o.width-1,b=-1,E=-1,x=o.height-1,A=-1,T=-1}var M="_getImageData"+(c?"Grey":"")+o.pixel_size+"bits",P=t[M](o,u,l,x,A,T,y,b,E);i.texImage2D(i.TEXTURE_2D,0,i.RGBA,o.width,o.height,0,i.RGBA,i.UNSIGNED_BYTE,P)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,f=i,d=t,p=e.width,m=e.height,g=0,_=new Uint8Array(p*m*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,g++)c=f[g],_[4*(l+p*u)+3]=255,_[4*(l+p*u)+2]=d[3*c+0],_[4*(l+p*u)+1]=d[3*c+1],_[4*(l+p*u)+0]=d[3*c+2];return _},t._getImageData16bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,f=i,d=e.width,p=e.height,m=0,g=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,m+=2)c=f[m+0]+(f[m+1]<<8),g[4*(l+d*u)+0]=(31744&c)>>7,g[4*(l+d*u)+1]=(992&c)>>2,g[4*(l+d*u)+2]=(31&c)>>3,g[4*(l+d*u)+3]=32768&c?0:255;return g},t._getImageData24bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=3)m[4*(c+f*l)+3]=255,m[4*(c+f*l)+2]=u[p+0],m[4*(c+f*l)+1]=u[p+1],m[4*(c+f*l)+0]=u[p+2];return m},t._getImageData32bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=4)m[4*(c+f*l)+2]=u[p+0],m[4*(c+f*l)+1]=u[p+1],m[4*(c+f*l)+0]=u[p+2],m[4*(c+f*l)+3]=u[p+3];return m},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,f=i,d=e.width,p=e.height,m=0,g=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,m++)c=f[m],g[4*(l+d*u)+0]=c,g[4*(l+d*u)+1]=c,g[4*(l+d*u)+2]=c,g[4*(l+d*u)+3]=255;return g},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,f=e.width,d=e.height,p=0,m=new Uint8Array(f*d*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=2)m[4*(c+f*l)+0]=u[p+0],m[4*(c+f*l)+1]=u[p+0],m[4*(c+f*l)+2]=u[p+0],m[4*(c+f*l)+3]=u[p+1];return m},t._TYPE_NO_DATA=0,t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();t.TGATools=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(t){this.length=0,this._duplicateId=0,this.data=new Array(t),this._id=e._GlobalId++}return e.prototype.push=function(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId},e.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},e.prototype.sort=function(e){this.data.sort(e)},e.prototype.reset=function(){this.length=0,this._duplicateId++},e.prototype.concat=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}},e.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++){var i=(e.data||e)[t];this.pushNoDuplicate(i)}}},e.prototype.indexOf=function(e){var t=this.data.indexOf(e);return t>=this.length?-1:t},e._GlobalId=0,e})();e.SmartArray=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._count=0,this._data={}}return e.prototype.copyFrom=function(e){var t=this;this.clear(),e.forEach((function(e,i){return t.add(e,i)}))},e.prototype.get=function(e){var t=this._data[e];if(void 0!==t)return t},e.prototype.getOrAddWithFactory=function(e,t){var i=this.get(e);return void 0!==i?i:(i=t(e),i&&this.add(e,i),i)},e.prototype.getOrAdd=function(e,t){var i=this.get(e);return void 0!==i?i:(this.add(e,t),t)},e.prototype.contains=function(e){return void 0!==this._data[e]},e.prototype.add=function(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)},e.prototype.set=function(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)},e.prototype.getAndRemove=function(e){var t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null},e.prototype.remove=function(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)},e.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(e.prototype,"count",{get:function(){return this._count},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e){for(var t in this._data){var i=this._data[t];e(t,i)}},e.prototype.first=function(e){for(var t in this._data){var i=this._data[t],r=e(t,i);if(r)return r}return null},e})();e.StringDictionary=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){function t(e,t){return function(i){i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}var i,r=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},n=(function(){function t(){}return t.Instantiate=function(e){for(var t=e.split("."),i=window||this,r=0,n=t.length;r<n;r++)i=i[t[r]];return"function"!=typeof i?null:i},t.SetImmediate=function(e){window.setImmediate?window.setImmediate(e):setTimeout(e,1)},t.IsExponentOfTwo=function(e){var t=1;do t*=2;while(t<e);return t===e},t.GetExponentOfTwo=function(e,t){var i=1;do i*=2;while(i<e);return i>t&&(i=t),i},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",l=0,u=new Uint8Array(e);l<u.length;)t=u[l++],i=l<u.length?u[l++]:Number.NaN,r=l<u.length?u[l++]:Number.NaN,n=t>>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),c+=h.charAt(n)+h.charAt(o)+h.charAt(s)+h.charAt(a);return"data:image/png;base64,"+c},t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null);for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE)),h=r;h<r+n;h++){var c=new e.Vector3(t[3*i[h]],t[3*i[h]+1],t[3*i[h]+2]);s=e.Vector3.Minimize(c,s),a=e.Vector3.Maximize(c,a)}return o&&(s.x-=s.x*o.x+o.y,s.y-=s.y*o.x+o.y,s.z-=s.z*o.x+o.y,a.x+=a.x*o.x+o.y,a.y+=a.y*o.x+o.y,a.z+=a.z*o.x+o.y),{minimum:s,maximum:a}},t.ExtractMinAndMax=function(t,i,r,n,o){void 0===n&&(n=null);var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE));o||(o=3);for(var h=i;h<i+r;h++){var c=new e.Vector3(t[h*o],t[h*o+1],t[h*o+2]);s=e.Vector3.Minimize(c,s),a=e.Vector3.Maximize(c,a)}return n&&(s.x-=s.x*n.x+n.y,s.y-=s.y*n.x+n.y,s.z-=s.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:s,maximum:a}},t.Vector2ArrayFeeder=function(t){return function(i){var r=void 0!==t.BYTES_PER_ELEMENT,n=r?t.length/2:t.length;if(i>=n)return null;if(r){var o=t;return new e.Vector2(o[2*i+0],o[2*i+1])}var s=t;return s[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2((-Number.MAX_VALUE),(-Number.MAX_VALUE)),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){if(t===!0||void 0!==e&&null!=e)return Array.isArray(e)?e:[e]},t.GetPointerPrefix=function(){var e="pointer";return window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,t){void 0===t&&(t=window),t.requestAnimationFrame?t.requestAnimationFrame(e):t.msRequestAnimationFrame?t.msRequestAnimationFrame(e):t.webkitRequestAnimationFrame?t.webkitRequestAnimationFrame(e):t.mozRequestAnimationFrame?t.mozRequestAnimationFrame(e):t.oRequestAnimationFrame?t.oRequestAnimationFrame(e):window.setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if(t.CorsBehavior)switch(typeof t.CorsBehavior){case"function":var r=t.CorsBehavior(e);if(r)return r;break;case"string":default:i.crossOrigin=t.CorsBehavior}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){i instanceof ArrayBuffer&&(i=t.EncodeArrayBufferTobase64(i)),i=t.CleanUrl(i);var s=new Image;"data:"!==i.substr(0,5)&&t.SetCorsBehavior(i,s),s.onload=function(){r(s)},s.onerror=function(e){t.Error("Error while trying to load texture: "+i),t.UseFallbackTexture?(s.src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",r(s)):n()};var a=function(){s.src=i},h=function(){o.loadImageFromDB(i,s)};if("data:"!==i.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(h,a);else if(i.indexOf("file:")===-1)a();else try{var c,l=i.substring(5).toLowerCase();try{c=URL.createObjectURL(e.FilesInput.FilesTextures[l],{oneTimeOnly:!0})}catch(u){c=URL.createObjectURL(e.FilesInput.FilesTextures[l])}s.src=c}catch(f){s.src=null}return s},t.LoadFile=function(i,r,n,o,s,a){i=t.CleanUrl(i);var h=function(){var e=new XMLHttpRequest,o=t.BaseUrl+i;e.open("GET",o,!0),s&&(e.responseType="arraybuffer"),e.onprogress=n,e.onreadystatechange=function(){if(4===e.readyState)if(e.onreadystatechange=null,e.status>=200&&e.status<300||navigator.isCocoonJS&&0===e.status)r(s?e.response:e.responseText);else{if(!a)throw new Error("Error status: "+e.status+" - Unable to load "+o);a()}},e.send(null)},c=function(){o.loadFileFromDB(i,r,n,h,s)};if(i.indexOf("file:")!==-1){var l=i.substring(5).toLowerCase();t.ReadFile(e.FilesInput.FilesToLoad[l],r,n,s)}else o&&o.enableSceneOffline?o.openAsync(c,h):h()},t.ReadFileAsDataURL=function(e,t,i){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onprogress=i,r.readAsDataURL(e)},t.ReadFile=function(e,i,r,n){var o=new FileReader;o.onerror=function(r){t.Log("Error while reading file: "+e.name),i(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},o.onload=function(e){i(e.target.result)},o.onprogress=r,n?o.readAsArrayBuffer(e):o.readAsText(e)},t.FileAsURL=function(e){var t=new Blob([e]),i=window.URL||window.webkitURL,r=i.createObjectURL(t);return r},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.x<t.x&&(t.x=e.x),e.y<t.y&&(t.y=e.y),e.z<t.z&&(t.z=e.z),e.x>i.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,n){for(var o in e)if(("_"!==o[0]||n&&n.indexOf(o)!==-1)&&(!i||i.indexOf(o)===-1)){var s=e[o],a=typeof s;if("function"!==a)if("object"===a)if(s instanceof Array){if(t[o]=[],s.length>0)if("object"==typeof s[0])for(var h=0;h<s.length;h++){var c=r(s[h],t);t[o].indexOf(c)===-1&&t[o].push(c)}else t[o]=s.slice(0)}else t[o]=r(s,t);else t[o]=s}},t.IsEmpty=function(e){for(var t in e)return!1;return!0},t.RegisterTopRootEvents=function(e){for(var t=0;t<e.length;t++){var i=e[t];window.addEventListener(i.name,i.handler,!1);try{window.parent&&window.parent.addEventListener(i.name,i.handler,!1)}catch(r){}}},t.UnregisterTopRootEvents=function(e){for(var t=0;t<e.length;t++){var i=e[t];window.removeEventListener(i.name,i.handler);try{window.parent&&window.parent.removeEventListener(i.name,i.handler)}catch(r){}}},t.DumpFramebuffer=function(e,r,n,o,s){void 0===s&&(s="image/png");for(var a=4*e,h=r/2,c=n.readPixels(0,0,e,r),l=0;l<h;l++)for(var u=0;u<a;u++){var f=u+l*a,d=r-l-1,p=u+d*a,m=c[f];c[f]=c[p],c[p]=m}i||(i=document.createElement("canvas")),i.width=e,i.height=r;var g=i.getContext("2d"),_=g.createImageData(e,r),v=_.data;v.set(c),g.putImageData(_,0,0),t.EncodeScreenshotCanvasData(o,s)},t.EncodeScreenshotCanvasData=function(e,t){void 0===t&&(t="image/png");var r=i.toDataURL(t);if(e)e(r);else if("download"in document.createElement("a")){var n=window.document.createElement("a");n.href=r;var o=new Date,s=(o.getFullYear()+"-"+(o.getMonth()+1)).slice(-2)+"-"+o.getDate()+"_"+o.getHours()+"-"+("0"+o.getMinutes()).slice(-2);n.setAttribute("download","screenshot_"+s+".png"),window.document.body.appendChild(n),n.addEventListener("click",(function(){n.parentElement.removeChild(n)})),n.click()}else{var a=window.open(""),h=a.document.createElement("img");h.src=r,a.document.body.appendChild(h)}},t.CreateScreenshot=function(e,r,n,o,s){void 0===s&&(s="image/png");var a,h;if(n.precision)a=Math.round(e.getRenderWidth()*n.precision),h=Math.round(a/e.getAspectRatio(r));else if(n.width&&n.height)a=n.width,h=n.height;else if(n.width&&!n.height)a=n.width,h=Math.round(a/e.getAspectRatio(r));else if(n.height&&!n.width)h=n.height,a=Math.round(h*e.getAspectRatio(r));else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");h=n,a=n}i||(i=document.createElement("canvas")),i.width=a,i.height=h;var c=i.getContext("2d");c.drawImage(e.getRenderingCanvas(),0,0,a,h),t.EncodeScreenshotCanvasData(o,s)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s){void 0===s&&(s="image/png");var a,h;if(n.precision)a=Math.round(i.getRenderWidth()*n.precision),h=Math.round(a/i.getAspectRatio(r)),n={width:a,height:h};else if(n.width&&n.height)a=n.width,h=n.height;else if(n.width&&!n.height)a=n.width,h=Math.round(a/i.getAspectRatio(r)),n={width:a,height:h};else if(n.height&&!n.width)h=n.height,a=Math.round(h*i.getAspectRatio(r)),n={width:a,height:h};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");h=n,a=n}var c=r.getScene(),l=null;c.activeCamera!==r&&(l=c.activeCamera,c.activeCamera=r);var u=new e.RenderTargetTexture("screenShot",n,c,(!1),(!1));u.renderList=c.meshes,u.onAfterRenderObservable.add((function(){t.DumpFramebuffer(a,h,i,o,s)})),c.incrementRenderId(),c.resetCachedMaterial(),u.render(!0),u.dispose(),l&&(c.activeCamera=l),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.Internals.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(o){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0,i="x"===e?t:3&t|8;return i.toString(16)}))},Object.defineProperty(t,"NoneLogLevel",{get:function(){return t._NoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MessageLogLevel",{get:function(){return t._MessageLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WarningLogLevel",{get:function(){return t._WarningLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ErrorLogLevel",{get:function(){return t._ErrorLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"AllLogLevel",{get:function(){return t._MessageLogLevel|t._WarningLogLevel|t._ErrorLogLevel},enumerable:!0,configurable:!0}),t._AddLogEntry=function(e){t._LogCache=e+t._LogCache,t.OnNewCacheEntry&&t.OnNewCacheEntry(e)},t._FormatMessage=function(e){var t=function(e){return e<10?"0"+e:""+e},i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e},t._LogDisabled=function(e){},t._LogEnabled=function(e){var i=t._FormatMessage(e);console.log("BJS - "+i);var r="<div style='color:white'>"+i+"</div><br>";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="<div style='color:orange'>"+i+"</div><br>";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="<div style='color:red'>"+i+"</div><br>";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return window.performance&&window.performance.now?window.performance.now():(new Date).getTime()},enumerable:!0,configurable:!0}),t.getClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i},t.first=function(e,t){for(var i=0,r=e;i<r.length;i++){var n=r[i];if(t(n))return n}},t.getFullClassName=function(e,t){void 0===t&&(t=!1);var i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,r=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null},t.arrayOrStringFeeder=function(e){return function(i){if(i>=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.BaseUrl="",t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t._performance=window.performance,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=n;var o=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(e,t){this._current+=e,t&&this._fetchResult()},e.prototype.beginMonitoring=function(){this._startMonitoringTime=n.Now},e.prototype.endMonitoring=function(e){void 0===e&&(e=!0),e&&this.fetchNewFrame();var t=n.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=n.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e})();e.PerfCounter=o,e.className=t;var s=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())},e.prototype.breakLoop=function(){this._done=!0,this._successCallback()},e.Run=function(t,i,r,n){void 0===n&&(n=0);var o=new e(t,i,r,n);return o.executeNext(),o},e.SyncAsyncForLoop=function(t,i,r,n,o,s){void 0===s&&(s=0),e.Run(Math.ceil(t/i),(function(e){o&&o()?e.breakLoop():setTimeout((function(){for(var n=0;n<i;++n){var s=e.index*i+n;if(s>=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._alphaBlend=!1,this._blendFunctionParameters=new Array(4),this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)},enumerable:!0,configurable:!0
}),e.prototype.setAlphaBlendFunctionParameters=function(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)},e.prototype.reset=function(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1))},e})();e._AlphaState=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,0)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1))},e})();e._DepthCullingState=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.reset()}return Object.defineProperty(t.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFunc",{get:function(){return this._stencilFunc},set:function(e){this._stencilFunc!==e&&(this._stencilFunc=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFuncRef",{get:function(){return this._stencilFuncRef},set:function(e){this._stencilFuncRef!==e&&(this._stencilFuncRef=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFuncMask",{get:function(){return this._stencilFuncMask},set:function(e){this._stencilFuncMask!==e&&(this._stencilFuncMask=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpStencilFail",{get:function(){return this._stencilOpStencilFail},set:function(e){this._stencilOpStencilFail!==e&&(this._stencilOpStencilFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpDepthFail",{get:function(){return this._stencilOpDepthFail},set:function(e){this._stencilOpDepthFail!==e&&(this._stencilOpDepthFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpStencilDepthPass",{get:function(){return this._stencilOpStencilDepthPass},set:function(e){this._stencilOpStencilDepthPass!==e&&(this._stencilOpStencilDepthPass=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilMask",{get:function(){return this._stencilMask},set:function(e){this._stencilMask!==e&&(this._stencilMask=e,this._isStencilMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilTest",{get:function(){return this._stencilTest},set:function(e){this._stencilTest!==e&&(this._stencilTest=e,this._isStencilTestDirty=!0)},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=e.Engine.ALWAYS,this._stencilFuncRef=1,this._stencilFuncMask=255,this._stencilOpStencilFail=e.Engine.KEEP,this._stencilOpDepthFail=e.Engine.KEEP,this._stencilOpStencilDepthPass=e.Engine.REPLACE,this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},t.prototype.apply=function(e){this.isDirty&&(this._isStencilTestDirty&&(this.stencilTest?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.stencilMask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.stencilFunc,this.stencilFuncRef,this.stencilFuncMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.stencilOpStencilFail,this.stencilOpDepthFail,this.stencilOpStencilDepthPass),this._isStencilOpDirty=!1))},t})();t._StencilState=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t,i,r){var n=e.createShader("vertex"===i?e.VERTEX_SHADER:e.FRAGMENT_SHADER);if(e.shaderSource(n,(r?r+"\n":"")+t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error(e.getShaderInfoLog(n));return n},i=36193,r=function(e,t){return t===l.TEXTURETYPE_FLOAT?e.FLOAT:t===l.TEXTURETYPE_HALF_FLOAT?i:e.UNSIGNED_BYTE},n=function(t,i,r){var n=r.NEAREST,o=r.NEAREST;return t===e.Texture.BILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=i?r.LINEAR_MIPMAP_NEAREST:r.LINEAR):t===e.Texture.TRILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=i?r.LINEAR_MIPMAP_LINEAR:r.LINEAR):t===e.Texture.NEAREST_SAMPLINGMODE&&(n=r.NEAREST,o=i?r.NEAREST_MIPMAP_LINEAR:r.NEAREST),{min:o,mag:n}},o=function(t,i,r,o,s,a,h,c,l,u){void 0===u&&(u=e.Texture.TRILINEAR_SAMPLINGMODE);var f=r.getEngine(),d=e.Tools.GetExponentOfTwo(o,f.getCaps().maxTextureSize),p=e.Tools.GetExponentOfTwo(s,f.getCaps().maxTextureSize);f._bindTextureDirectly(i.TEXTURE_2D,t),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,void 0===a?1:a?1:0),t._baseWidth=o,t._baseHeight=s,t._width=d,t._height=p,t.isReady=!0,l(d,p);var m=n(u,!h,i);i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,m.mag),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,m.min),h||c||i.generateMipmap(i.TEXTURE_2D),f._bindTextureDirectly(i.TEXTURE_2D,null),f.resetTextureCache(),r._removePendingData(t),t.onLoadedCallbacks.forEach((function(e){e()})),t.onLoadedCallbacks=[]},s=function(t,i,r,n,o,s){void 0===s&&(s=null);var a,h=function(){r[i]=a,r._internalCount++,n._removePendingData(a),6===r._internalCount&&o(r)},c=function(){n._removePendingData(a),s&&s()};a=e.Tools.LoadImage(t,h,c,n.database),n._addPendingData(a)},a=function(e,t,i,r,n){void 0===n&&(n=null);var o=[];o._internalCount=0;for(var a=0;a<6;a++)s(r[a],a,o,t,i,n)},h=(function(){function e(){}return e})();e.InstancingAttributeInfo=h;var c=(function(){function e(){}return e})();e.EngineCapabilities=c;var l=(function(){function s(t,i,r,n){var o=this;void 0===n&&(n=!0),this.isFullscreen=!1,this.isPointerLock=!1,this.cullBackFaces=!0,this.renderEvenInBackground=!0,this.enableOfflineSupport=!0,this.scenes=new Array,this._windowIsBackground=!1,this._webGLVersion="1.0",this._badOS=!1,this._drawCalls=new e.PerfCounter,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.fpsRange=60,this.previousFramesDuration=[],this.fps=60,this.deltaTime=0,this._depthCullingState=new e.Internals._DepthCullingState,this._stencilState=new e.Internals._StencilState,this._alphaState=new e.Internals._AlphaState,this._alphaMode=s.ALPHA_DISABLE,this._loadedTexturesCache=new Array,this._maxTextureChannels=16,this._activeTexturesCache=new Array(this._maxTextureChannels),this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentBufferPointers=[],this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._texturesSupported=new Array,this._onVRFullScreenTriggered=function(){if(o._vrDisplayEnabled&&o._vrDisplayEnabled.isPresenting){o._oldSize=new e.Size(o.getRenderWidth(),o.getRenderHeight()),o._oldHardwareScaleFactor=o.getHardwareScalingLevel();var t=o._vrDisplayEnabled.getEyeParameters("left");o.setHardwareScalingLevel(1),o.setSize(2*t.renderWidth,t.renderHeight)}else o.setHardwareScalingLevel(o._oldHardwareScaleFactor),o.setSize(o._oldSize.width,o._oldSize.height),o._vrDisplayEnabled=void 0},this._renderingCanvas=t,this._externalData=new e.StringDictionary,r=r||{},null!=i&&(r.antialias=i),void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1);var a=this._canRenderToFloatTexture(),h=this._canRenderToHalfFloatTexture();if(!this._gl){if(!t)throw new Error("The provided canvas is null or undefined.");try{this._gl=t.getContext("webgl",r)||t.getContext("experimental-webgl",r)}catch(l){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported");this._onBlur=function(){o._windowIsBackground=!0},this._onFocus=function(){o._windowIsBackground=!1},window.addEventListener("blur",this._onBlur),window.addEventListener("focus",this._onFocus);var u=r.limitDeviceRatio||window.devicePixelRatio||1;this._hardwareScalingLevel=n?1/Math.min(u,window.devicePixelRatio||1):1,this.resize(),this._isStencilEnable=r.stencil,this._caps=new c,this._caps.maxTexturesImageUnits=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),this._caps.maxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._caps.maxCubemapTextureSize=this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),this._caps.maxRenderTextureSize=this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),this._caps.maxVertexAttribs=this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),this._glVersion=this._gl.getParameter(this._gl.VERSION);var f=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=f&&(this._glRenderer=this._gl.getParameter(f.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(f.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor="Unknown vendor"),this._glRenderer||(this._glRenderer="Unknown renderer"),this._caps.standardDerivatives=null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureFloat=null!==this._gl.getExtension("OES_texture_float"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.instancedArrays=this._gl.getExtension("ANGLE_instanced_arrays"),this._caps.uintIndices=null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.drawBuffersExtension=this._gl.getExtension("WEBGL_draw_buffers"),this._caps.textureFloatLinearFiltering=this._gl.getExtension("OES_texture_float_linear"),this._caps.textureLOD=this._gl.getExtension("EXT_shader_texture_lod"),this._caps.textureFloatRender=a,this._caps.textureHalfFloat=null!==this._gl.getExtension("OES_texture_half_float"),this._caps.textureHalfFloatLinearFiltering=this._gl.getExtension("OES_texture_half_float_linear"),this._caps.textureHalfFloatRender=h,this._caps.astc&&this.texturesSupported.push(".astc"),this._caps.s3tc&&this.texturesSupported.push(".dds"),this._caps.pvrtc&&this.texturesSupported.push(".pvr"),this._caps.etc2&&this.texturesSupported.push(".etc2"),this._caps.etc1&&this.texturesSupported.push(".etc1"),this._gl.getShaderPrecisionFormat){var d=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);this._caps.highPrecisionShaderSupported=0!==d.precision}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._onFullscreenChange=function(){void 0!==document.fullscreen?o.isFullscreen=document.fullscreen:void 0!==document.mozFullScreen?o.isFullscreen=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o.isFullscreen=document.webkitIsFullScreen:void 0!==document.msIsFullScreen&&(o.isFullscreen=document.msIsFullScreen),o.isFullscreen&&o._pointerLockRequested&&(t.requestPointerLock=t.requestPointerLock||t.msRequestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock&&t.requestPointerLock())},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=function(){o.isPointerLock=document.mozPointerLockElement===t||document.webkitPointerLockElement===t||document.msPointerLockElement===t||document.pointerLockElement===t},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("mspointerlockchange",this._onPointerLockChange,!1),document.addEventListener("mozpointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1),e.AudioEngine&&!s.audioEngine&&(s.audioEngine=new e.AudioEngine),this._loadingScreen=new e.DefaultLoadingScreen(this._renderingCanvas),r.autoEnableWebVR&&this.initWebVR();var p=/AppleWebKit.*10.[\d] Mobile/;this._badOS=p.test(navigator.userAgent),e.Tools.Log("Babylon.js engine (v"+s.Version+") launched")}return Object.defineProperty(s,"NEVER",{get:function(){return s._NEVER},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALWAYS",{get:function(){return s._ALWAYS},enumerable:!0,configurable:!0}),Object.defineProperty(s,"LESS",{get:function(){return s._LESS},enumerable:!0,configurable:!0}),Object.defineProperty(s,"EQUAL",{get:function(){return s._EQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"LEQUAL",{get:function(){return s._LEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"GREATER",{get:function(){return s._GREATER},enumerable:!0,configurable:!0}),Object.defineProperty(s,"GEQUAL",{get:function(){return s._GEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"NOTEQUAL",{get:function(){return s._NOTEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"KEEP",{get:function(){return s._KEEP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"REPLACE",{get:function(){return s._REPLACE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INCR",{get:function(){return s._INCR},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DECR",{get:function(){return s._DECR},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INVERT",{get:function(){return s._INVERT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INCR_WRAP",{get:function(){return s._INCR_WRAP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DECR_WRAP",{get:function(){return s._DECR_WRAP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_DISABLE",{get:function(){return s._ALPHA_DISABLE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_ONEONE",{get:function(){return s._ALPHA_ONEONE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_ADD",{get:function(){return s._ALPHA_ADD},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_COMBINE",{get:function(){return s._ALPHA_COMBINE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_SUBTRACT",{get:function(){return s._ALPHA_SUBTRACT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_MULTIPLY",{get:function(){return s._ALPHA_MULTIPLY},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_MAXIMIZED",{get:function(){return s._ALPHA_MAXIMIZED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_NONE",{get:function(){return s._DELAYLOADSTATE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_LOADED",{get:function(){return s._DELAYLOADSTATE_LOADED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_LOADING",{get:function(){return s._DELAYLOADSTATE_LOADING},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_NOTLOADED",{get:function(){return s._DELAYLOADSTATE_NOTLOADED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_ALPHA",{get:function(){return s._TEXTUREFORMAT_ALPHA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_LUMINANCE",{get:function(){return s._TEXTUREFORMAT_LUMINANCE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_LUMINANCE_ALPHA",{get:function(){return s._TEXTUREFORMAT_LUMINANCE_ALPHA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_RGB",{get:function(){return s._TEXTUREFORMAT_RGB},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_RGBA",{get:function(){return s._TEXTUREFORMAT_RGBA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_UNSIGNED_INT",{get:function(){return s._TEXTURETYPE_UNSIGNED_INT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_FLOAT",{get:function(){return s._TEXTURETYPE_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_HALF_FLOAT",{get:function(){return s._TEXTURETYPE_HALF_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"Version",{get:function(){return"2.5"},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"webGLVersion",{get:function(){return this._webGLVersion},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"isStencilEnable",{get:function(){return this._isStencilEnable},enumerable:!0,configurable:!0}),s.prototype._prepareWorkingCanvas=function(){this._workingCanvas||(this._workingCanvas=document.createElement("canvas"),this._workingContext=this._workingCanvas.getContext("2d"))},s.prototype.resetTextureCache=function(){for(var e=0;e<this._maxTextureChannels;e++)this._activeTexturesCache[e]=null},s.prototype.getGlInfo=function(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}},s.prototype.getAspectRatio=function(e,t){void 0===t&&(t=!1);var i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},s.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget._width:this._renderingCanvas.width},s.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget._height:this._renderingCanvas.height},s.prototype.getRenderingCanvas=function(){return this._renderingCanvas},s.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas.getBoundingClientRect()},s.prototype.setHardwareScalingLevel=function(e){this._hardwareScalingLevel=e,this.resize()},s.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel},s.prototype.getLoadedTexturesCache=function(){return this._loadedTexturesCache},s.prototype.getCaps=function(){return this._caps},Object.defineProperty(s.prototype,"drawCalls",{get:function(){return this._drawCalls.current},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"drawCallsPerfCounter",{get:function(){return this._drawCalls},enumerable:!0,configurable:!0}),s.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},s.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},s.prototype.setDepthFunctionToGreater=function(){this._depthCullingState.depthFunc=this._gl.GREATER},s.prototype.setDepthFunctionToGreaterOrEqual=function(){this._depthCullingState.depthFunc=this._gl.GEQUAL},s.prototype.setDepthFunctionToLess=function(){this._depthCullingState.depthFunc=this._gl.LESS},s.prototype.setDepthFunctionToLessOrEqual=function(){this._depthCullingState.depthFunc=this._gl.LEQUAL},s.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},s.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},s.prototype.getStencilMask=function(){return this._stencilState.stencilMask},s.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},s.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},s.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},s.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},s.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},s.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},s.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},s.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},s.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},s.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},s.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},s.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},s.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},s.prototype.stopRenderLoop=function(e){if(!e)return void(this._activeRenderLoops=[]);var t=this._activeRenderLoops.indexOf(e);t>=0&&this._activeRenderLoops.splice(t,1)},s.prototype._renderLoop=function(){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i<this._activeRenderLoops.length;i++){var r=this._activeRenderLoops[i];r()}this.endFrame()}this._activeRenderLoops.length>0?e.Tools.QueueNewFrame(this._bindedRenderFunction,this._vrDisplayEnabled):this._renderingQueueLaunched=!1},s.prototype.runRenderLoop=function(t){this._activeRenderLoops.indexOf(t)===-1&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),e.Tools.QueueNewFrame(this._bindedRenderFunction)))},s.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,e.Tools.RequestFullscreen(this._renderingCanvas))},s.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},s.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),s===!0?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},s.prototype.setViewport=function(e,t,i){var r=t||(navigator.isCocoonJS?window.innerWidth:this._renderingCanvas.width),n=i||(navigator.isCocoonJS?window.innerHeight:this._renderingCanvas.height),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._gl.viewport(o*r,s*n,r*e.width,n*e.height)},s.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._gl.viewport(e,t,i,r),n},s.prototype.beginFrame=function(){this._measureFps()},s.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplayEnabled&&this._vrDisplayEnabled.isPresenting&&this._vrDisplayEnabled.submitFrame()},s.prototype.resize=function(){var t=navigator.isCocoonJS?window.innerWidth:this._renderingCanvas.clientWidth,i=navigator.isCocoonJS?window.innerHeight:this._renderingCanvas.clientHeight;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel);for(var r=0;r<this.scenes.length;r++){var n=this.scenes[r];e.DebugLayer&&n.debugLayer.isVisible()&&n.debugLayer._syncPositions()}},s.prototype.setSize=function(e,t){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i<this.scenes.length;i++)for(var r=this.scenes[i],n=0;n<r.cameras.length;n++){var o=r.cameras[n];o._currentRenderId=0}},s.prototype.initWebVR=function(){this.vrDisplaysPromise||this._getVRDisplays()},s.prototype.enableVR=function(e){this._vrDisplayEnabled=e,this._vrDisplayEnabled.requestPresent([{source:this.getRenderingCanvas()}]).then(this._onVRFullScreenTriggered)},s.prototype.disableVR=function(){this._vrDisplayEnabled&&this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered)},s.prototype._getVRDisplays=function(){var e=this,t=function(t){var i=(t.length,0);return e._vrDisplays=t.filter((function(e){return t[i]instanceof VRDisplay})),e._vrDisplays};navigator.getVRDisplays&&(this.vrDisplaysPromise=navigator.getVRDisplays().then(t))},s.prototype.bindFramebuffer=function(e,t,i,r){this._currentRenderTarget=e,this.bindUnboundFramebuffer(e._framebuffer);var n=this._gl;e.isCube&&n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0),n.viewport(0,0,i||e._width,r||e._height),this.wipeCaches()},s.prototype.bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)},s.prototype.unBindFramebuffer=function(e,t){if(void 0===t&&(t=!1),this._currentRenderTarget=null,e.generateMipMaps&&!t){var i=this._gl;this._bindTextureDirectly(i.TEXTURE_2D,e),i.generateMipmap(i.TEXTURE_2D),this._bindTextureDirectly(i.TEXTURE_2D,null)}this.bindUnboundFramebuffer(null)},s.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){var t=this._gl;this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,e),t.generateMipmap(t.TEXTURE_CUBE_MAP),this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)}},s.prototype.flushFramebuffer=function(){this._gl.flush()},s.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget=null,this.bindUnboundFramebuffer(null),this.setViewport(this._cachedViewport),this.wipeCaches()},s.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},s.prototype.createVertexBuffer=function(e){var t=this._gl.createBuffer();return this.bindArrayBuffer(t),e instanceof Float32Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this._resetVertexBufferBinding(),t.references=1,t},s.prototype.createDynamicVertexBuffer=function(e){var t=this._gl.createBuffer();return this.bindArrayBuffer(t),e instanceof Float32Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this._resetVertexBufferBinding(),t.references=1,t},s.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this._resetVertexBufferBinding()},s.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},s.prototype.createIndexBuffer=function(e){var t=this._gl.createBuffer();this.bindIndexBuffer(t);var i,r=!1;if(this._caps.uintIndices){for(var n=0;n<e.length;n++)if(e[n]>65535){r=!0;break}i=r?new Uint32Array(e):new Uint16Array(e)}else i=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),t.references=1,t.is32Bits=r,t},s.prototype.bindArrayBuffer=function(e){this.bindBuffer(e,this._gl.ARRAY_BUFFER)},s.prototype.bindIndexBuffer=function(e){this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},s.prototype.bindBuffer=function(e,t){this._currentBoundBuffer[t]!==e&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},s.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},s.prototype.vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],h=!1;a?(a.buffer!==e&&(a.buffer=e,h=!0),a.size!==i&&(a.size=i,h=!0),a.type!==r&&(a.type=r,h=!0),a.normalized!==n&&(a.normalized=n,h=!0),a.stride!==o&&(a.stride=o,h=!0),a.offset!==s&&(a.offset=s,h=!0)):(h=!0,this._currentBufferPointers[t]={indx:t,size:i,type:r,normalized:n,stride:o,offset:s,buffer:e}),h&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},s.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;for(var o=n.getAttributesCount(),s=0,a=0;a<o;a++)if(a<i.length){var h=n.getAttributeLocation(a);h>=0&&(this._vertexAttribArraysEnabled[h]||(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0),this.vertexAttribPointer(e,h,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}else{var h=n.getAttributeLocation(a);this._vertexAttribArraysEnabled[h]&&(this._gl.disableVertexAttribArray(h),
this._vertexAttribArraysEnabled[h]=!1)}}this._cachedIndexBuffer!==t&&(this._cachedIndexBuffer=t,this.bindIndexBuffer(t),this._uintIndicesCurrentlySet=t.is32Bits)},s.prototype.bindBuffers=function(e,t,i){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i;for(var r=i.getAttributesNames(),n=0;n<r.length;n++){var o=i.getAttributeLocation(n);if(o>=0){var s=e[r[n]];if(!s){this._vertexAttribArraysEnabled[o]&&(this._gl.disableVertexAttribArray(o),this._vertexAttribArraysEnabled[o]=!1);continue}this._vertexAttribArraysEnabled[o]||(this._gl.enableVertexAttribArray(o),this._vertexAttribArraysEnabled[o]=!0);var a=s.getBuffer();this.vertexAttribPointer(a,o,s.getSize(),this._gl.FLOAT,!1,4*s.getStrideSize(),4*s.getOffset()),s.getIsInstanced()&&(this._caps.instancedArrays.vertexAttribDivisorANGLE(o,1),this._currentInstanceLocations.push(o),this._currentInstanceBuffers.push(a))}}}null!=t&&this._cachedIndexBuffer!==t&&(this._cachedIndexBuffer=t,this.bindIndexBuffer(t),this._uintIndicesCurrentlySet=t.is32Bits)},s.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t<i;t++){var r=this._currentInstanceBuffers[t];e!=r&&(e=r,this.bindArrayBuffer(r));var n=this._currentInstanceLocations[t];this._caps.instancedArrays.vertexAttribDivisorANGLE(n,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0},s.prototype._releaseBuffer=function(e){return e.references--,0===e.references&&(this._gl.deleteBuffer(e),!0)},s.prototype.createInstancesBuffer=function(e){var t=this._gl.createBuffer();return t.capacity=e,this.bindArrayBuffer(t),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),t},s.prototype.deleteInstancesBuffer=function(e){this._gl.deleteBuffer(e)},s.prototype.updateAndBindInstancesBuffer=function(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index){for(var r=0,n=0;n<i.length;n++){var o=i[n];r+=4*o.attributeSize}for(var n=0;n<i.length;n++){var o=i[n];this._vertexAttribArraysEnabled[o.index]||(this._gl.enableVertexAttribArray(o.index),this._vertexAttribArraysEnabled[o.index]=!0),this.vertexAttribPointer(e,o.index,o.attributeSize,o.attribyteType||this._gl.FLOAT,o.normalized||!1,r,o.offset),this._caps.instancedArrays.vertexAttribDivisorANGLE(o.index,1),this._currentInstanceLocations.push(o.index),this._currentInstanceBuffers.push(e)}}else for(var s=0;s<4;s++){var a=i[s];this._vertexAttribArraysEnabled[a]||(this._gl.enableVertexAttribArray(a),this._vertexAttribArraysEnabled[a]=!0),this.vertexAttribPointer(e,a,4,this._gl.FLOAT,!1,64,16*s),this._caps.instancedArrays.vertexAttribDivisorANGLE(a,1),this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(e)}},s.prototype.applyStates=function(){this._depthCullingState.apply(this._gl),this._stencilState.apply(this._gl),this._alphaState.apply(this._gl)},s.prototype.draw=function(e,t,i,r){this.applyStates(),this._drawCalls.addCount(1,!1);var n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,o=this._uintIndicesCurrentlySet?4:2;return r?void this._caps.instancedArrays.drawElementsInstancedANGLE(e?this._gl.TRIANGLES:this._gl.LINES,i,n,t*o,r):void this._gl.drawElements(e?this._gl.TRIANGLES:this._gl.LINES,i,n,t*o)},s.prototype.drawPointClouds=function(e,t,i){return this.applyStates(),this._drawCalls.addCount(1,!1),i?void this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS,e,t,i):void this._gl.drawArrays(this._gl.POINTS,e,t)},s.prototype.drawUnIndexed=function(e,t,i,r){return this.applyStates(),this._drawCalls.addCount(1,!1),r?void this._caps.instancedArrays.drawArraysInstancedANGLE(e?this._gl.TRIANGLES:this._gl.LINES,t,i,r):void this._gl.drawArrays(e?this._gl.TRIANGLES:this._gl.LINES,t,i)},s.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],e.getProgram()&&this._gl.deleteProgram(e.getProgram()))},s.prototype.createEffect=function(t,i,r,n,o,s,a,h,c){var l=t.vertexElement||t.vertex||t,u=t.fragmentElement||t.fragment||t,f=l+"+"+u+"@"+o;if(this._compiledEffects[f])return this._compiledEffects[f];var d=new e.Effect(t,i,r,n,this,o,s,a,h,c);return d._key=f,this._compiledEffects[f]=d,d},s.prototype.createEffectForParticles=function(e,t,i,r,n,o,s){return void 0===t&&(t=[]),void 0===i&&(i=[]),void 0===r&&(r=""),this.createEffect({vertex:"particles",fragmentElement:e},["position","color","options"],["view","projection"].concat(t),["diffuseSampler"].concat(i),r,n,o,s)},s.prototype.createShaderProgram=function(e,i,r,n){n=n||this._gl;var o=t(n,e,"vertex",r),s=t(n,i,"fragment",r),a=n.createProgram();n.attachShader(a,o),n.attachShader(a,s),n.linkProgram(a);var h=n.getProgramParameter(a,n.LINK_STATUS);if(!h){var c=n.getProgramInfoLog(a);if(c)throw new Error(c)}return n.deleteShader(o),n.deleteShader(s),a},s.prototype.getUniforms=function(e,t){for(var i=[],r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(e,t[r]));return i},s.prototype.getAttributes=function(e,t){for(var i=[],r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(e,t[r]))}catch(n){i.push(-1)}return i},s.prototype.enableEffect=function(e){this.setProgram(e.getProgram()),this._currentEffect=e,e.onBind&&e.onBind(e)},s.prototype.setIntArray=function(e,t){e&&this._gl.uniform1iv(e,t)},s.prototype.setIntArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2iv(e,t)},s.prototype.setIntArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3iv(e,t)},s.prototype.setIntArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4iv(e,t)},s.prototype.setFloatArray=function(e,t){e&&this._gl.uniform1fv(e,t)},s.prototype.setFloatArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2fv(e,t)},s.prototype.setFloatArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3fv(e,t)},s.prototype.setFloatArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4fv(e,t)},s.prototype.setArray=function(e,t){e&&this._gl.uniform1fv(e,t)},s.prototype.setArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2fv(e,t)},s.prototype.setArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3fv(e,t)},s.prototype.setArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4fv(e,t)},s.prototype.setMatrices=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t)},s.prototype.setMatrix=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t.toArray())},s.prototype.setMatrix3x3=function(e,t){e&&this._gl.uniformMatrix3fv(e,!1,t)},s.prototype.setMatrix2x2=function(e,t){e&&this._gl.uniformMatrix2fv(e,!1,t)},s.prototype.setFloat=function(e,t){e&&this._gl.uniform1f(e,t)},s.prototype.setFloat2=function(e,t,i){e&&this._gl.uniform2f(e,t,i)},s.prototype.setFloat3=function(e,t,i,r){e&&this._gl.uniform3f(e,t,i,r)},s.prototype.setBool=function(e,t){e&&this._gl.uniform1i(e,t)},s.prototype.setFloat4=function(e,t,i,r,n){e&&this._gl.uniform4f(e,t,i,r,n)},s.prototype.setColor3=function(e,t){e&&this._gl.uniform3f(e,t.r,t.g,t.b)},s.prototype.setColor4=function(e,t,i){e&&this._gl.uniform4f(e,t.r,t.g,t.b,i)},s.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1);var n=r?this._gl.FRONT:this._gl.BACK,o=r?this._gl.BACK:this._gl.FRONT,s=this.cullBackFaces?n:o;(this._depthCullingState.cull!==e||i||this._depthCullingState.cullFace!==s)&&(e?(this._depthCullingState.cullFace=s,this._depthCullingState.cull=!0):this._depthCullingState.cull=!1),this._depthCullingState.zOffset=t},s.prototype.setDepthBuffer=function(e){this._depthCullingState.depthTest=e},s.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},s.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},s.prototype.setColorWrite=function(e){this._gl.colorMask(e,e,e,e)},s.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode!==e){switch(e){case s.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case s.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0}t||this.setDepthWrite(e===s.ALPHA_DISABLE),this._alphaMode=e}},s.prototype.getAlphaMode=function(){return this._alphaMode},s.prototype.setAlphaTesting=function(e){this._alphaTest=e},s.prototype.getAlphaTesting=function(){return this._alphaTest},s.prototype.wipeCaches=function(){this.resetTextureCache(),this._currentEffect=null,this._stencilState.reset(),this._depthCullingState.reset(),this.setDepthFunctionToLessOrEqual(),this._alphaState.reset(),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null},s.prototype.setSamplingMode=function(t,i){var r=this._gl;this._bindTextureDirectly(r.TEXTURE_2D,t);var n=r.NEAREST,o=r.NEAREST;i===e.Texture.BILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=r.LINEAR):i===e.Texture.TRILINEAR_SAMPLINGMODE&&(n=r.LINEAR,o=r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,o),this._bindTextureDirectly(r.TEXTURE_2D,null),t.samplingMode=i},s.prototype.setTextureFormatToUse=function(e){for(var t=0,i=this.texturesSupported.length;t<i;t++)if(".astc"!==this._texturesSupported[t]&&".pvr"!==this._texturesSupported[t]&&".etc1"!==this._texturesSupported[t]&&".etc2"!==this._texturesSupported[t])for(var r=0,n=e.length;r<n;r++)if(this._texturesSupported[t]===e[r].toLowerCase())return this._textureFormatInUse=this._texturesSupported[t];return this._textureFormatInUse=null},s.prototype.createTexture=function(t,i,r,n,s,a,h,c){var l=this;void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===h&&(h=null),void 0===c&&(c=null);var u,f=this._gl.createTexture(),d=!1;if("data:"===t.substr(0,5)&&(d=!0),d){var p=t;d=p.split(":"),t=p,u=d[1].substr(d[1].length-4,4).toLowerCase()}else{var m=t.lastIndexOf(".");u=t.substring(m).toLowerCase(),!this._textureFormatInUse||d||n.database||(u=this._textureFormatInUse,t=t.substring(0,m)+this._textureFormatInUse)}var g=".dds"===u,_=".tga"===u;n._addPendingData(f),f.url=t,f.noMipmap=i,f.references=1,f.samplingMode=s,f.onLoadedCallbacks=[a],this._loadedTexturesCache.push(f);var v,y=function(){n._removePendingData(f),h&&h()};if(_)v=function(t){var a=new Uint8Array(t),h=e.Internals.TGATools.GetTGAHeader(a);o(f,l._gl,n,h.width,h.height,r,i,!1,(function(){e.Internals.TGATools.UploadContent(l._gl,a)}),s)},d instanceof Array?v(c):e.Tools.LoadFile(t,(function(e){v(e)}),null,n.database,!0,y);else if(g)v=function(t){var a=e.Internals.DDSTools.GetDDSInfo(t),h=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&!i&&a.width>>a.mipmapCount-1===1;o(f,l._gl,n,a.width,a.height,r,!h,a.isFourCC,(function(){e.Internals.DDSTools.UploadDDSLevels(l._gl,l.getCaps().s3tc,t,a,h,1)}),s)},d instanceof Array?v(c):e.Tools.LoadFile(t,(function(e){v(e)}),null,n.database,!0,y);else{var x=function(t){o(f,l._gl,n,t.width,t.height,r,i,!1,(function(i,r){var n=t.width===i&&t.height===r;n||(l._prepareWorkingCanvas(),l._workingCanvas.width=i,l._workingCanvas.height=r,s===e.Texture.NEAREST_SAMPLINGMODE&&(l._workingContext.imageSmoothingEnabled=!1,l._workingContext.mozImageSmoothingEnabled=!1,l._workingContext.oImageSmoothingEnabled=!1,l._workingContext.webkitImageSmoothingEnabled=!1,l._workingContext.msImageSmoothingEnabled=!1),l._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s===e.Texture.NEAREST_SAMPLINGMODE&&(l._workingContext.imageSmoothingEnabled=!0,l._workingContext.mozImageSmoothingEnabled=!0,l._workingContext.oImageSmoothingEnabled=!0,l._workingContext.webkitImageSmoothingEnabled=!0,l._workingContext.msImageSmoothingEnabled=!0)),l._gl.texImage2D(l._gl.TEXTURE_2D,0,l._gl.RGBA,l._gl.RGBA,l._gl.UNSIGNED_BYTE,n?t:l._workingCanvas)}),s)};d instanceof Array?e.Tools.LoadImage(c,x,y,n.database):e.Tools.LoadImage(t,x,y,n.database)}return f},s.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case s.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case s.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case s.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case s.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case s.TEXTUREFORMAT_RGBA:t=this._gl.RGBA}return t},s.prototype.updateRawTexture=function(e,t,i,r,n){void 0===n&&(n=null);var o=this._getInternalFormat(i);this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,void 0===r?1:r?1:0),e._width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[n],e._width,e._height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e._width,e._height,0,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this.resetTextureCache(),e.isReady=!0},s.prototype.createRawTexture=function(e,t,i,r,o,s,a,h){void 0===h&&(h=null);var c=this._gl.createTexture();c._baseWidth=t,c._baseHeight=i,c._width=t,c._height=i,c.references=1,this.updateRawTexture(c,e,r,s,h),this._bindTextureDirectly(this._gl.TEXTURE_2D,c);var l=n(a,o,this._gl);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,l.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,l.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),c.samplingMode=a,this._loadedTexturesCache.push(c),c},s.prototype.createDynamicTexture=function(t,i,r,n){var o=this._gl.createTexture();return o._baseWidth=t,o._baseHeight=i,r&&(t=e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize),i=e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize)),this.resetTextureCache(),o._width=t,o._height=i,o.isReady=!1,o.generateMipMaps=r,o.references=1,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._loadedTexturesCache.push(o),o},s.prototype.updateTextureSamplingMode=function(e,t){var i=n(e,t.generateMipMaps,this._gl);t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null))},s.prototype.updateDynamicTexture=function(e,t,i,r){void 0===r&&(r=!1),this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?1:0),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this.resetTextureCache(),e.isReady=!0},s.prototype.updateVideoTexture=function(e,t,i){if(!e._isDisabled){this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?0:1);try{void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported?this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t):(e._workingCanvas||(e._workingCanvas=document.createElement("canvas"),e._workingContext=e._workingCanvas.getContext("2d"),e._workingCanvas.width=e._width,e._workingCanvas.height=e._height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e._width,e._height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this.resetTextureCache(),e.isReady=!0}catch(r){e._isDisabled=!0}}},s.prototype.createRenderTargetTexture=function(t,i){var o=!1,a=!0,h=!1,c=s.TEXTURETYPE_UNSIGNED_INT,l=e.Texture.TRILINEAR_SAMPLINGMODE;void 0!==i&&(o=void 0===i.generateMipMaps?i:i.generateMipMaps,a=void 0===i.generateDepthBuffer||i.generateDepthBuffer,h=a&&i.generateStencilBuffer,c=void 0===i.type?c:i.type,void 0!==i.samplingMode&&(l=i.samplingMode),c!==s.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?c!==s.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(l=e.Texture.NEAREST_SAMPLINGMODE):l=e.Texture.NEAREST_SAMPLINGMODE);var u=this._gl,f=u.createTexture();this._bindTextureDirectly(u.TEXTURE_2D,f);var d=t.width||t,p=t.height||t,m=n(l,o,u);c!==s.TEXTURETYPE_FLOAT||this._caps.textureFloat||(c=s.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,m.mag),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,m.min),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,d,p,0,u.RGBA,r(u,c),null);var g;h?(g=u.createRenderbuffer(),u.bindRenderbuffer(u.RENDERBUFFER,g),u.renderbufferStorage(u.RENDERBUFFER,u.DEPTH_STENCIL,d,p)):a&&(g=u.createRenderbuffer(),u.bindRenderbuffer(u.RENDERBUFFER,g),u.renderbufferStorage(u.RENDERBUFFER,u.DEPTH_COMPONENT16,d,p));var _=u.createFramebuffer();return this.bindUnboundFramebuffer(_),h?u.framebufferRenderbuffer(u.FRAMEBUFFER,u.DEPTH_STENCIL_ATTACHMENT,u.RENDERBUFFER,g):a&&u.framebufferRenderbuffer(u.FRAMEBUFFER,u.DEPTH_ATTACHMENT,u.RENDERBUFFER,g),u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,f,0),o&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(u.TEXTURE_2D,null),u.bindRenderbuffer(u.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),f._framebuffer=_,a&&(f._depthBuffer=g),f._baseWidth=d,f._baseHeight=p,f._width=d,f._height=p,f.isReady=!0,f.generateMipMaps=o,f.references=1,f.samplingMode=l,f.type=c,this.resetTextureCache(),this._loadedTexturesCache.push(f),f},s.prototype.createRenderTargetCubeTexture=function(t,i){var r=this._gl,o=r.createTexture(),s=!0,a=!0,h=!1,c=e.Texture.TRILINEAR_SAMPLINGMODE;void 0!==i&&(s=void 0===i.generateMipMaps?i:i.generateMipMaps,a=void 0===i.generateDepthBuffer||i.generateDepthBuffer,h=a&&i.generateStencilBuffer,void 0!==i.samplingMode&&(c=i.samplingMode)),o.isCube=!0,o.references=1,o.generateMipMaps=s,o.references=1,o.samplingMode=c;var l=n(c,s,r);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,o);for(var u=0;u<6;u++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+u,0,r.RGBA,t,t,0,r.RGBA,r.UNSIGNED_BYTE,null);r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,l.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,l.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);var f;h?(f=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,f),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,t)):a&&(f=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,f),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT16,t,t));var d=r.createFramebuffer();return this.bindUnboundFramebuffer(d),h?r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,f):a&&r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,f),o.generateMipMaps&&(this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,o),r.generateMipmap(r.TEXTURE_CUBE_MAP)),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),r.bindRenderbuffer(r.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),o._framebuffer=d,a&&(o._depthBuffer=f),o._width=t,o._height=t,o.isReady=!0,this.resetTextureCache(),this._loadedTexturesCache.push(o),o},s.prototype.createCubeTexture=function(t,i,r,n,o,s){var h=this;void 0===o&&(o=null),void 0===s&&(s=null);var c=this._gl,l=c.createTexture();l.isCube=!0,l.url=t,l.references=1,l.onLoadedCallbacks=[];var u=t.substr(t.length-4,4).toLowerCase(),f=this.getCaps().s3tc&&".dds"===u;return f?e.Tools.LoadFile(t,(function(t){var i=e.Internals.DDSTools.GetDDSInfo(t),r=(i.isRGB||i.isLuminance||i.mipmapCount>1)&&!n;h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l),c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,1),e.Internals.DDSTools.UploadDDSLevels(h._gl,h.getCaps().s3tc,t,i,r,6),n||i.isFourCC||1!==i.mipmapCount||c.generateMipmap(c.TEXTURE_CUBE_MAP),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,r?c.LINEAR_MIPMAP_LINEAR:c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),h.resetTextureCache(),l._width=i.width,l._height=i.height,l.isReady=!0}),null,null,!0,s):a(t,i,(function(t){var i=e.Tools.GetExponentOfTwo(t[0].width,h._caps.maxCubemapTextureSize),r=i;h._prepareWorkingCanvas(),h._workingCanvas.width=i,h._workingCanvas.height=r;var s=[c.TEXTURE_CUBE_MAP_POSITIVE_X,c.TEXTURE_CUBE_MAP_POSITIVE_Y,c.TEXTURE_CUBE_MAP_POSITIVE_Z,c.TEXTURE_CUBE_MAP_NEGATIVE_X,c.TEXTURE_CUBE_MAP_NEGATIVE_Y,c.TEXTURE_CUBE_MAP_NEGATIVE_Z];h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l),c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,0);for(var a=0;a<s.length;a++)h._workingContext.drawImage(t[a],0,0,t[a].width,t[a].height,0,0,i,r),c.texImage2D(s[a],0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,h._workingCanvas);n||c.generateMipmap(c.TEXTURE_CUBE_MAP),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,n?c.LINEAR:c.LINEAR_MIPMAP_LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),h.resetTextureCache(),l._width=i,l._height=r,l.isReady=!0,l.onLoadedCallbacks.forEach((function(e){e()})),o&&o()}),r,s),this._loadedTexturesCache.push(l),l},s.prototype.updateTextureSize=function(e,t,i){e._width=t,e._height=i,e._size=t*i,e._baseWidth=t,e._baseHeight=i},s.prototype.createRawCubeTexture=function(t,r,n,o,a,h,c,l){var u=this,f=this._gl,d=f.createTexture();r._addPendingData(d),d.isCube=!0,d.references=1,d.url=t;var p=this._getInternalFormat(o),m=f.UNSIGNED_BYTE;a===s.TEXTURETYPE_FLOAT&&(m=f.FLOAT);var g=n,_=g,v=e.Tools.IsExponentOfTwo(g)&&e.Tools.IsExponentOfTwo(_);d._width=g,d._height=_;var y=function(){r._removePendingData(d)},x=function(t){var n=c(t),o=[f.TEXTURE_CUBE_MAP_POSITIVE_X,f.TEXTURE_CUBE_MAP_POSITIVE_Y,f.TEXTURE_CUBE_MAP_POSITIVE_Z,f.TEXTURE_CUBE_MAP_NEGATIVE_X,f.TEXTURE_CUBE_MAP_NEGATIVE_Y,f.TEXTURE_CUBE_MAP_NEGATIVE_Z];if(g=d._width,_=d._height,v=e.Tools.IsExponentOfTwo(g)&&e.Tools.IsExponentOfTwo(_),u._bindTextureDirectly(f.TEXTURE_CUBE_MAP,d),f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,0),!h&&v)if(l){var s=[];s.push(n[0]),s.push(n[3]),s.push(n[1]),s.push(n[4]),s.push(n[2]),s.push(n[5]);for(var a=l(s),y=0;y<a.length;y++){var x=g>>y;f.texImage2D(o[0],y,p,x,x,0,p,m,a[y][0]),f.texImage2D(o[1],y,p,x,x,0,p,m,a[y][2]),f.texImage2D(o[2],y,p,x,x,0,p,m,a[y][4]),f.texImage2D(o[3],y,p,x,x,0,p,m,a[y][1]),f.texImage2D(o[4],y,p,x,x,0,p,m,a[y][3]),f.texImage2D(o[5],y,p,x,x,0,p,m,a[y][5])}}else{for(var b=0;b<o.length;b++){var A=n[b];f.texImage2D(o[b],0,p,g,_,0,p,m,A)}if(f.generateMipmap(f.TEXTURE_CUBE_MAP),m===f.FLOAT&&p===f.RGB&&1282===f.getError()){e.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");for(var b=0;b<o.length;b++){for(var A=n[b],T=new Float32Array(g*_*4),E=0;E<g;E++)for(var M=0;M<_;M++){var P=3*(M*g+E),S=4*(M*g+E);T[S+0]=A[P+0],T[S+1]=A[P+1],T[S+2]=A[P+2],T[S+3]=1}f.texImage2D(o[b],0,f.RGBA,g,_,0,f.RGBA,m,T)}f.generateMipmap(f.TEXTURE_CUBE_MAP)}}else h=!0;(m!==f.FLOAT||u._caps.textureFloatLinearFiltering)&&(m!==i||u._caps.textureHalfFloatLinearFiltering)?(f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_MAG_FILTER,f.LINEAR),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_MIN_FILTER,h?f.LINEAR:f.LINEAR_MIPMAP_LINEAR)):(f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_MAG_FILTER,f.NEAREST),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_MIN_FILTER,f.NEAREST)),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_CUBE_MAP,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),u._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null),d.isReady=!0,u.resetTextureCache(),r._removePendingData(d)};return e.Tools.LoadFile(t,(function(e){x(e)}),y,r.database,!0),d},s.prototype._releaseTexture=function(e){var t=this._gl;e._framebuffer&&t.deleteFramebuffer(e._framebuffer),e._depthBuffer&&t.deleteRenderbuffer(e._depthBuffer),t.deleteTexture(e),this.unbindAllTextures();var i=this._loadedTexturesCache.indexOf(e);i!==-1&&this._loadedTexturesCache.splice(i,1)},s.prototype.setProgram=function(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)},s.prototype.bindSamplers=function(e){this.setProgram(e.getProgram());for(var t=e.getSamplers(),i=0;i<t.length;i++){var r=e.getUniform(t[i]);this._gl.uniform1i(r,i)}this._currentEffect=null},s.prototype.activateTexture=function(e){this._activeTexture!==e&&(this._gl.activeTexture(e),this._activeTexture=e)},s.prototype._bindTextureDirectly=function(e,t){this._activeTexturesCache[this._activeTexture]!==t&&(this._gl.bindTexture(e,t),this._activeTexturesCache[this._activeTexture]=t)},s.prototype._bindTexture=function(e,t){e<0||(this.activateTexture(this._gl["TEXTURE"+e]),this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},s.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t._textures.data[t._currentRenderTextureInd])},s.prototype.unbindAllTextures=function(){for(var e=0;e<this._caps.maxTexturesImageUnits;e++)this.activateTexture(this._gl["TEXTURE"+e]),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)},s.prototype.setTexture=function(e,t,i){e<0||(this._gl.uniform1i(t,e),this._setTexture(e,i))},s.prototype._setTexture=function(t,i){if(!i||!i.isReady())return void(null!=this._activeTexturesCache[t]&&(this.activateTexture(this._gl["TEXTURE"+t]),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)));var r=!1;if(i instanceof e.VideoTexture)this.activateTexture(this._gl["TEXTURE"+t]),r=!0,i.update();else if(i.delayLoadState===s.DELAYLOADSTATE_NOTLOADED)return void i.delayLoad();var n=i.getInternalTexture();if(this._activeTexturesCache[t]!==n)if(r||this.activateTexture(this._gl["TEXTURE"+t]),n.isCube){if(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,n),n._cachedCoordinatesMode!==i.coordinatesMode){n._cachedCoordinatesMode=i.coordinatesMode;var o=i.coordinatesMode!==e.Texture.CUBIC_MODE&&i.coordinatesMode!==e.Texture.SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,o),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,o)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,i)}else{if(this._bindTextureDirectly(this._gl.TEXTURE_2D,n),n._cachedWrapU!==i.wrapU)switch(n._cachedWrapU=i.wrapU,i.wrapU){case e.Texture.WRAP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.REPEAT);break;case e.Texture.CLAMP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE);break;case e.Texture.MIRROR_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.MIRRORED_REPEAT)}if(n._cachedWrapV!==i.wrapV)switch(n._cachedWrapV=i.wrapV,i.wrapV){case e.Texture.WRAP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.REPEAT);break;case e.Texture.CLAMP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);break;case e.Texture.MIRROR_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.MIRRORED_REPEAT)}this._setAnisotropicLevel(this._gl.TEXTURE_2D,i)}},s.prototype.setTextureArray=function(e,t,i){if(!(e<0)){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r<i.length;r++)this._textureUnits[r]=e+r;this._gl.uniform1iv(t,this._textureUnits);for(var n=0;n<i.length;n++)this._setTexture(e+n,i[n])}},s.prototype._setAnisotropicLevel=function(t,i){var r=this._caps.textureAnisotropicFilterExtension,n=i.anisotropicFilteringLevel;i.getInternalTexture().samplingMode===e.Texture.NEAREST_SAMPLINGMODE&&(n=1),r&&i._cachedAnisotropicFilteringLevel!==n&&(this._gl.texParameterf(t,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n,this._caps.maxAnisotropy)),i._cachedAnisotropicFilteringLevel=n)},s.prototype.readPixels=function(e,t,i,r){var n=new Uint8Array(r*i*4);return this._gl.readPixels(e,t,i,r,this._gl.RGBA,this._gl.UNSIGNED_BYTE,n),n},s.prototype.addExternalData=function(e,t){return this._externalData.add(e,t)},s.prototype.getExternalData=function(e){return this._externalData.get(e)},s.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData.getOrAddWithFactory(e,t)},s.prototype.removeExternalData=function(e){return this._externalData.remove(e)},s.prototype.releaseInternalTexture=function(e){if(e&&(e.references--,0===e.references)){var t=this.getLoadedTexturesCache(),i=t.indexOf(e);i>-1&&t.splice(i,1),this._releaseTexture(e)}},s.prototype.unbindAllAttributes=function(){for(var e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1)},s.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.scenes.length;)this.scenes[0].dispose();s.audioEngine.dispose();for(var e in this._compiledEffects)this._gl.deleteProgram(this._compiledEffects[e]._program);this.unbindAllAttributes(),this._gl=null,this.disableVR(),window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)},s.prototype.displayLoadingUI=function(){this._loadingScreen.displayLoadingUI()},s.prototype.hideLoadingUI=function(){this._loadingScreen.hideLoadingUI()},Object.defineProperty(s.prototype,"loadingScreen",{get:function(){return this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"loadingUIText",{set:function(e){this._loadingScreen.loadingUIText=e;
},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"loadingUIBackgroundColor",{set:function(e){this._loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),s.prototype.attachContextLostEvent=function(e){this._renderingCanvas.addEventListener("webglcontextlost",e,!1)},s.prototype.attachContextRestoredEvent=function(e){this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)},s.prototype.getVertexShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return this._gl.getShaderSource(t[0])},s.prototype.getFragmentShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return this._gl.getShaderSource(t[1])},s.prototype.getFps=function(){return this.fps},s.prototype.getDeltaTime=function(){return this.deltaTime},s.prototype._measureFps=function(){this.previousFramesDuration.push(e.Tools.Now);var t=this.previousFramesDuration.length;if(t>=2&&(this.deltaTime=this.previousFramesDuration[t-1]-this.previousFramesDuration[t-2]),t>=this.fpsRange){t>this.fpsRange&&(this.previousFramesDuration.splice(0,1),t=this.previousFramesDuration.length);for(var i=0,r=0;r<t-1;r++)i+=this.previousFramesDuration[r+1]-this.previousFramesDuration[r];this.fps=1e3/(i/(t-1))}},s.prototype._canRenderToFloatTexture=function(){return this._canRenderToTextureOfType(e.Engine.TEXTURETYPE_FLOAT,"OES_texture_float")},s.prototype._canRenderToHalfFloatTexture=function(){return this._canRenderToTextureOfType(e.Engine.TEXTURETYPE_HALF_FLOAT,"OES_texture_half_float")},s.prototype._canRenderToTextureOfType=function(t,i){var n=document.createElement("canvas");n.height=16,n.width=16;var o=n.getContext("webgl")||n.getContext("experimental-webgl"),s=o.getExtension(i);if(!s)return!1;var a="attribute vec4 a_position;\n                void main() {\n                    gl_Position = a_position;\n                }",h="precision mediump float;\n                uniform vec4 u_color;\n                uniform sampler2D u_texture;\n\n                void main() {\n                    gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n                }",c=this.createShaderProgram(a,h,null,o);o.useProgram(c);var l=o.getAttribLocation(c,"a_position"),u=o.getUniformLocation(c,"u_color"),f=o.createBuffer();o.bindBuffer(o.ARRAY_BUFFER,f),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),o.STATIC_DRAW),o.enableVertexAttribArray(l),o.vertexAttribPointer(l,2,o.FLOAT,!1,0,0);var d=o.createTexture();o.bindTexture(o.TEXTURE_2D,d),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));var p=o.createTexture();o.bindTexture(o.TEXTURE_2D,p),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,r(o,t),null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST);var m=o.createFramebuffer();o.bindFramebuffer(o.FRAMEBUFFER,m),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,p,0);var g=function(){o.deleteProgram(c),o.disableVertexAttribArray(l),o.deleteBuffer(f),o.deleteFramebuffer(m),o.deleteTexture(d),o.deleteTexture(p)},_=o.checkFramebufferStatus(o.FRAMEBUFFER);if(_!==o.FRAMEBUFFER_COMPLETE)return e.Tools.Log("GL Support: can **NOT** render to "+t+" texture"),g(),!1;o.bindTexture(o.TEXTURE_2D,d),o.uniform4fv(u,[0,10,20,1]),o.drawArrays(o.TRIANGLES,0,6),o.bindTexture(o.TEXTURE_2D,p),o.bindFramebuffer(o.FRAMEBUFFER,null),o.clearColor(1,0,0,1),o.clear(o.COLOR_BUFFER_BIT),o.uniform4fv(u,[0,.1,.05,1]),o.drawArrays(o.TRIANGLES,0,6);var v=new Uint8Array(4);return o.readPixels(0,0,1,1,o.RGBA,o.UNSIGNED_BYTE,v),0!==v[0]||v[1]<248||v[2]<248||v[3]<254?(e.Tools.Log("GL Support: Was not able to actually render to "+t+" texture"),g(),!1):(g(),!0)},s.isSupported=function(){try{if(navigator.isCocoonJS)return!0;var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");return null!=t&&!!window.WebGLRenderingContext}catch(i){return!1}},s._ALPHA_DISABLE=0,s._ALPHA_ADD=1,s._ALPHA_COMBINE=2,s._ALPHA_SUBTRACT=3,s._ALPHA_MULTIPLY=4,s._ALPHA_MAXIMIZED=5,s._ALPHA_ONEONE=6,s._DELAYLOADSTATE_NONE=0,s._DELAYLOADSTATE_LOADED=1,s._DELAYLOADSTATE_LOADING=2,s._DELAYLOADSTATE_NOTLOADED=4,s._TEXTUREFORMAT_ALPHA=0,s._TEXTUREFORMAT_LUMINANCE=1,s._TEXTUREFORMAT_LUMINANCE_ALPHA=2,s._TEXTUREFORMAT_RGB=4,s._TEXTUREFORMAT_RGBA=5,s._TEXTURETYPE_UNSIGNED_INT=0,s._TEXTURETYPE_FLOAT=1,s._TEXTURETYPE_HALF_FLOAT=2,s._NEVER=512,s._ALWAYS=519,s._LESS=513,s._EQUAL=514,s._LEQUAL=515,s._GREATER=516,s._GEQUAL=518,s._NOTEQUAL=517,s._KEEP=7680,s._REPLACE=7681,s._INCR=7682,s._DECR=7683,s._INVERT=5386,s._INCR_WRAP=34055,s._DECR_WRAP=34056,s.CollisionsEpsilon=.001,s.CodeRepository="src/",s.ShadersRepository="src/Shaders/",s})();e.Engine=l})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.state="",this.metadata=null,this.doNotSerialize=!1,this.animations=new Array,this._ranges={},this._childrenFlag=-1,this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this.onDisposeObservable=new e.Observable,this.name=t,this.id=t,this._scene=i,this._initCache()}return Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode){var t=this._parentNode._children.indexOf(this);t!==-1&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.getWorldMatrix=function(){return e.Matrix.Identity()},t.prototype._initCache=function(){this._cache={},this._cache.parent=void 0},t.prototype.updateCache=function(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())},t.prototype._updateCache=function(e){},t.prototype._isSynchronized=function(){return!0},t.prototype._markSyncedWithParent=function(){this._parentRenderId=this.parent._currentRenderId},t.prototype.isSynchronizedWithParent=function(){return!this.parent||this._parentRenderId===this.parent._currentRenderId&&this.parent.isSynchronized()},t.prototype.isSynchronized=function(e){var t=this.hasNewParent();return t=t||!this.isSynchronizedWithParent(),t=t||!this._isSynchronized(),e&&this.updateCache(!0),!t},t.prototype.hasNewParent=function(e){return this._cache.parent!==this.parent&&(e&&(this._cache.parent=this.parent),!0)},t.prototype.isReady=function(){return this._isReady},t.prototype.isEnabled=function(){return!!this._isEnabled&&(!this.parent||this.parent.isEnabled())},t.prototype.setEnabled=function(e){this._isEnabled=e},t.prototype.isDescendantOf=function(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))},t.prototype._getDescendants=function(e,t,i){if(void 0===t&&(t=!1),this._children)for(var r=0;r<this._children.length;r++){var n=this._children[r];i&&!i(n)||e.push(n),t||n._getDescendants(e,!1,i)}},t.prototype.getDescendants=function(e,t){var i=[];return this._getDescendants(i,e,t),i},t.prototype.getChildren=function(e){return this.getDescendants(!0,e)},t.prototype.getChildMeshes=function(t,i){var r=[];return this._getDescendants(r,t,(function(t){return(!i||i(t))&&t instanceof e.AbstractMesh})),r},t.prototype._setReady=function(e){if(e!==this._isReady){if(!e)return void(this._isReady=!1);this._isReady=!0,this.onReady&&this.onReady(this)}},t.prototype.getAnimationByName=function(e){for(var t=0;t<this.animations.length;t++){var i=this.animations[t];if(i.name===e)return i}return null},t.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=new e.AnimationRange(t,i,r);for(var n=0,o=this.animations.length;n<o;n++)this.animations[n]&&this.animations[n].createRange(t,i,r)}},t.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=void 0},t.prototype.getAnimationRange=function(e){return this._ranges[e]},t.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?void this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},t.prototype.serializeAnimationRanges=function(){var e=[];for(var t in this._ranges){var i={};i.name=t,i.from=this._ranges[t].from,i.to=this._ranges[t].to,e.push(i)}return e},t.prototype.dispose=function(){this.parent=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.ParseAnimationRanges=function(e,t,i){if(t.ranges)for(var r=0;r<t.ranges.length;r++){var n=t.ranges[r];e.createAnimationRange(n.name,n.from,n.to)}},__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"id",void 0),__decorate([e.serialize()],t.prototype,"uniqueId",void 0),__decorate([e.serialize()],t.prototype,"state",void 0),__decorate([e.serialize()],t.prototype,"metadata",void 0),t})();e.Node=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o,s,a){this._engine=e,this._canvas=i,this._currentScene=t,this._sceneLoadedCallback=r,this._progressCallback=n,this._additionnalRenderLoopLogicCallback=o,this._textureLoadingCallback=s,this._startingProcessingFilesCallback=a}return t.prototype.monitorElementForDragNDrop=function(e){var t=this;e&&(this._elementToMonitor=e,this._elementToMonitor.addEventListener("dragenter",(function(e){t.drag(e)}),!1),this._elementToMonitor.addEventListener("dragover",(function(e){t.drag(e)}),!1),this._elementToMonitor.addEventListener("drop",(function(e){t.drop(e)}),!1))},t.prototype.renderFunction=function(){if(this._additionnalRenderLoopLogicCallback&&this._additionnalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){var e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype.loadFiles=function(e){if(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(),e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&this._filesToLoad.length>0){for(var i=0;i<this._filesToLoad.length;i++)switch(this._filesToLoad[i].type){case"image/jpeg":case"image/png":case"image/bmp":t.FilesTextures[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i];break;case"image/targa":case"image/vnd.ms-dds":case"audio/wav":case"audio/x-wav":case"audio/mp3":case"audio/mpeg":case"audio/mpeg3":case"audio/x-mpeg-3":case"audio/ogg":t.FilesToLoad[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i];break;default:this._filesToLoad[i].name.indexOf(".mtl")!==-1?t.FilesToLoad[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i]:this._filesToLoad[i].name.indexOf(".babylon")===-1&&this._filesToLoad[i].name.indexOf(".stl")===-1&&this._filesToLoad[i].name.indexOf(".obj")===-1||this._filesToLoad[i].name.indexOf(".manifest")!==-1||this._filesToLoad[i].name.indexOf(".incremental")!==-1||this._filesToLoad[i].name.indexOf(".babylonmeshdata")!==-1||this._filesToLoad[i].name.indexOf(".babylongeometrydata")!==-1||this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata")!==-1||this._filesToLoad[i].name.indexOf(".binary.babylon")!==-1||(this._sceneFileToLoad=this._filesToLoad[i])}this.reload()}},t.prototype.reload=function(){var t=this,i=this;this._sceneFileToLoad?(this._currentScene&&(e.Tools.errorsCount>0&&(e.Tools.ClearLogCache(),e.Tools.Log("Babylon.js engine (v"+e.Engine.Version+") launched")),this._engine.stopRenderLoop(),this._currentScene.dispose()),e.SceneLoader.Load("file:",this._sceneFileToLoad,this._engine,(function(e){i._currentScene=e,i._currentScene.executeWhenReady((function(){i._currentScene.activeCamera&&0!==i._currentScene.lights.length||i._currentScene.createDefaultCameraOrLight(),i._currentScene.activeCamera.attachControl(i._canvas),i._sceneLoadedCallback&&i._sceneLoadedCallback(t._sceneFileToLoad,i._currentScene),i._engine.runRenderLoop((function(){i.renderFunction()}))}))}),(function(e){t._progressCallback&&t._progressCallback(e)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesTextures=new Array,t.FilesToLoad=new Array,t})();e.FilesInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}return e})();e.IntersectionInfo=t;var i=(function(){function t(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshId=0,this.pickedSprite=null}return t.prototype.getNormal=function(t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!0),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e.VertexBuffer.NormalKind))return null;var r,n=this.pickedMesh.getIndices();if(i){var o=this.pickedMesh.getVerticesData(e.VertexBuffer.NormalKind),s=e.Vector3.FromArray(o,3*n[3*this.faceId]),a=e.Vector3.FromArray(o,3*n[3*this.faceId+1]),h=e.Vector3.FromArray(o,3*n[3*this.faceId+2]);s=s.scale(this.bu),a=a.scale(this.bv),h=h.scale(1-this.bu-this.bv),r=new e.Vector3(s.x+a.x+h.x,s.y+a.y+h.y,s.z+a.z+h.z)}else{var c=this.pickedMesh.getVerticesData(e.VertexBuffer.PositionKind),l=e.Vector3.FromArray(c,3*n[3*this.faceId]),u=e.Vector3.FromArray(c,3*n[3*this.faceId+1]),f=e.Vector3.FromArray(c,3*n[3*this.faceId+2]),d=l.subtract(u),p=f.subtract(u);r=e.Vector3.Cross(d,p)}return t&&(r=e.Vector3.TransformNormal(r,this.pickedMesh.getWorldMatrix())),e.Vector3.Normalize(r)},t.prototype.getTextureCoordinates=function(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e.VertexBuffer.UVKind))return null;var t=this.pickedMesh.getIndices(),i=this.pickedMesh.getVerticesData(e.VertexBuffer.UVKind),r=e.Vector2.FromArray(i,2*t[3*this.faceId]),n=e.Vector2.FromArray(i,2*t[3*this.faceId+1]),o=e.Vector2.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(1-this.bu-this.bv),n=n.scale(this.bu),o=o.scale(this.bv),new e.Vector2(r.x+n.x+o.x,r.y+n.y+o.y)},t})();e.PickingInfo=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._tempRadiusVector=e.Vector3.Zero();var r=e.Vector3.Distance(t,i);this.center=e.Vector3.Lerp(t,i,.5),this.radius=.5*r,this.centerWorld=e.Vector3.Zero(),this._update(e.Matrix.Identity())}return t.prototype._update=function(t){e.Vector3.TransformCoordinatesToRef(this.center,t,this.centerWorld),e.Vector3.TransformNormalFromFloatsToRef(1,1,1,t,this._tempRadiusVector),this.radiusWorld=Math.max(Math.abs(this._tempRadiusVector.x),Math.abs(this._tempRadiusVector.y),Math.abs(this._tempRadiusVector.z))*this.radius},t.prototype.isInFrustum=function(e){for(var t=0;t<6;t++)if(e[t].dotCoordinate(this.centerWorld)<=-this.radiusWorld)return!1;return!0},t.prototype.intersectsPoint=function(t){var i=this.centerWorld.x-t.x,r=this.centerWorld.y-t.y,n=this.centerWorld.z-t.z,o=Math.sqrt(i*i+r*r+n*n);return!(Math.abs(this.radiusWorld-o)<e.Epsilon)},t.Intersects=function(e,t){var i=e.centerWorld.x-t.centerWorld.x,r=e.centerWorld.y-t.centerWorld.y,n=e.centerWorld.z-t.centerWorld.z,o=Math.sqrt(i*i+r*r+n*n);return!(e.radiusWorld+t.radiusWorld<o)},t})();e.BoundingSphere=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.minimum=t,this.maximum=i,this.vectors=new Array,this.vectorsWorld=new Array,this.vectors.push(this.minimum.clone()),this.vectors.push(this.maximum.clone()),this.vectors.push(this.minimum.clone()),this.vectors[2].x=this.maximum.x,this.vectors.push(this.minimum.clone()),this.vectors[3].y=this.maximum.y,this.vectors.push(this.minimum.clone()),this.vectors[4].z=this.maximum.z,this.vectors.push(this.maximum.clone()),this.vectors[5].z=this.minimum.z,this.vectors.push(this.maximum.clone()),this.vectors[6].x=this.minimum.x,this.vectors.push(this.maximum.clone()),this.vectors[7].y=this.minimum.y,this.center=this.maximum.add(this.minimum).scale(.5),this.extendSize=this.maximum.subtract(this.minimum).scale(.5),this.directions=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()];for(var r=0;r<this.vectors.length;r++)this.vectorsWorld[r]=e.Vector3.Zero();this.minimumWorld=e.Vector3.Zero(),this.maximumWorld=e.Vector3.Zero(),this._update(e.Matrix.Identity())}return t.prototype.getWorldMatrix=function(){return this._worldMatrix},t.prototype.setWorldMatrix=function(e){return this._worldMatrix.copyFrom(e),this},t.prototype._update=function(t){e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this.minimumWorld),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this.maximumWorld);for(var i=0;i<this.vectors.length;i++){var r=this.vectorsWorld[i];e.Vector3.TransformCoordinatesToRef(this.vectors[i],t,r),r.x<this.minimumWorld.x&&(this.minimumWorld.x=r.x),r.y<this.minimumWorld.y&&(this.minimumWorld.y=r.y),r.z<this.minimumWorld.z&&(this.minimumWorld.z=r.z),r.x>this.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.addToRef(this.minimumWorld,this.center),this.center.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.x<i||i>t.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.y<i||i>t.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.z<i||i>t.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)},t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.x<e.x||this.minimumWorld.x>t.x)&&(!(this.maximumWorld.y<e.y||this.minimumWorld.y>t.y)&&!(this.maximumWorld.z<e.z||this.minimumWorld.z>t.z))},t.Intersects=function(e,t){return!(e.maximumWorld.x<t.minimumWorld.x||e.minimumWorld.x>t.maximumWorld.x)&&(!(e.maximumWorld.y<t.minimumWorld.y||e.minimumWorld.y>t.maximumWorld.y)&&!(e.maximumWorld.z<t.minimumWorld.z||e.minimumWorld.z>t.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i),s=e.Vector3.DistanceSquared(r,o);return s<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.center,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i){void 0===i&&(i=Number.MAX_VALUE),this.origin=e,this.direction=t,this.length=i,this._show=!1}return t.prototype.intersectsBoxMinMax=function(e,t){var i,r,n,o,s=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<e.x||this.origin.x>t.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<e.y||this.origin.y>t.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<e.z||this.origin.z>t.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;if(s<0)return!1;var a=n-s*s;return a<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var h=e.Vector3.Dot(this._edge2,this._qvec)*o;return h>this.length?null:new e.IntersectionInfo(s,a,h)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.show=function(t,i){this._show||(this._renderFunction=this._render.bind(this),this._show=!0,this._scene=t,this._renderPoints=[this.origin,this.origin.add(this.direction.scale(this.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._scene.registerBeforeRender(this._renderFunction)),i&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._show&&(this._show=!1,this._scene.unregisterBeforeRender(this._renderFunction)),this._renderLine&&(this._renderLine.dispose(),this._renderLine=null,this._renderPoints=null)},t.prototype._render=function(){var t=this._renderPoints[1];t.copyFrom(this.direction),t.scaleInPlace(this.length),t.addInPlace(this.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,h,c=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),l=r.subtract(i),u=c.subtract(this.origin),f=i.subtract(this.origin),d=e.Vector3.Dot(l,l),p=e.Vector3.Dot(l,u),m=e.Vector3.Dot(u,u),g=e.Vector3.Dot(l,f),_=e.Vector3.Dot(u,f),v=d*m-p*p,y=v,x=v;v<t.smallnum?(s=0,y=1,h=_,x=m):(s=p*_-m*g,h=d*_-p*g,s<0?(s=0,h=_,x=m):s>y&&(s=y,h=_+p,x=m)),h<0?(h=0,-g<0?s=0:-g>d?s=y:(s=-g,y=d)):h>x&&(h=x,-g+p<0?s=0:-g+p>d?s=y:(s=-g+p,y=d)),o=Math.abs(s)<t.smallnum?0:s/y,a=Math.abs(h)<t.smallnum?0:h/x;var b=u.multiplyByFloats(a,a,a),A=f.add(l.multiplyByFloats(o,o,o)).subtract(b),T=a>0&&a<=this.length&&A.lengthSquared()<n*n;return T?b.length():-1},t.CreateNew=function(i,r,n,o,s,a,h){var c=e.Vector3.Unproject(new e.Vector3(i,r,0),n,o,s,a,h),l=e.Vector3.Unproject(new e.Vector3(i,r,1),n,o,s,a,h),u=l.subtract(c);return u.normalize(),new t(c,u)},t.CreateNewFromTo=function(i,r,n){void 0===n&&(n=e.Matrix.Identity());var o=r.subtract(i),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),t.Transform(new t(i,o,s),n)},t.Transform=function(i,r){var n=e.Vector3.TransformCoordinates(i.origin,r),o=e.Vector3.TransformNormal(i.direction,r);return o.normalize(),new t(n,o,i.length)},t.TransformToRef=function(t,i,r){e.Vector3.TransformCoordinatesToRef(t.origin,i,r.origin),e.Vector3.TransformNormalToRef(t.direction,i,r.direction),t.direction.normalize()},t.smallnum=1e-8,t.rayl=1e9,t})();e.Ray=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n){var o=this;t.call(this,r,n),this.onCollideObservable=new e.Observable,this.onCollisionPositionChangeObservable=new e.Observable,this.onAfterWorldMatrixUpdateObservable=new e.Observable,this.definedFacingForward=!0,this.position=new e.Vector3(0,0,0),this._rotation=new e.Vector3(0,0,0),this._scaling=new e.Vector3(1,1,1),this.billboardMode=i.BILLBOARDMODE_NONE,this.visibility=1,this.alphaIndex=Number.MAX_VALUE,this.infiniteDistance=!1,this.isVisible=!0,this.isPickable=!0,this.showBoundingBox=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.renderingGroupId=0,this.receiveShadows=!1,this.renderOutline=!1,this.outlineColor=e.Color3.Red(),this.outlineWidth=.02,this.renderOverlay=!1,this.overlayColor=e.Color3.Red(),this.overlayAlpha=.5,this.hasVertexAlpha=!1,this.useVertexColors=!0,this.applyFog=!0,this.computeBonesUsingShaders=!0,this.scalingDeterminant=1,this.numBoneInfluencers=4,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.layerMask=268435455,this.alwaysSelectAsActiveMesh=!1,this._checkCollisions=!1,this.ellipsoid=new e.Vector3(.5,1,.5),this.ellipsoidOffset=new e.Vector3(0,0,0),this._collider=new e.Collider,this._oldPositionForCollisions=new e.Vector3(0,0,0),this._diffPositionForCollisions=new e.Vector3(0,0,0),this._newPositionForCollisions=new e.Vector3(0,0,0),this.edgesWidth=1,this.edgesColor=new e.Color4(1,0,0,1),this._localWorld=e.Matrix.Zero(),this._worldMatrix=e.Matrix.Zero(),this._rotateYByPI=e.Matrix.RotationY(Math.PI),this._absolutePosition=e.Vector3.Zero(),this._collisionsTransformMatrix=e.Matrix.Zero(),this._collisionsScalingMatrix=e.Matrix.Zero(),this._isDirty=!1,this._pivotMatrix=e.Matrix.Identity(),this._isDisposed=!1,this._renderId=0,this._intersectionsInProgress=new Array,this._isWorldMatrixFrozen=!1,this._unIndexed=!1,this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),o.getScene().workerCollisions&&i.multiplyInPlace(o._collider.radius),i.subtractToRef(o._oldPositionForCollisions,o._diffPositionForCollisions),o._diffPositionForCollisions.length()>e.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},n.addMesh(this)}return __extends(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return i._BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return i._BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return i._BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return i._BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return i._BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null)},enumerable:!0,configurable:!0}),i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this.physicsImpostor&&this.physicsImpostor.forceUpdate()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){this._poseMatrix.copyFrom(e)},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype.disableEdgesRendering=function(){void 0!==this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=void 0)},i.prototype.enableEdgesRendering=function(t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.disableEdgesRendering(),this._edgesRenderer=new e.EdgesRenderer(this,t,i)},Object.defineProperty(i.prototype,"isBlocked",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.getLOD=function(e){
return this},i.prototype.getTotalVertices=function(){return 0},i.prototype.getIndices=function(){return null},i.prototype.getVerticesData=function(e){return null},i.prototype.isVerticesDataPresent=function(e){return!1},i.prototype.getBoundingInfo=function(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfo||this._updateBoundingInfo(),this._boundingInfo)},i.prototype.setBoundingInfo=function(e){this._boundingInfo=e},Object.defineProperty(i.prototype,"useBones",{get:function(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)},enumerable:!0,configurable:!0}),i.prototype._preActivate=function(){},i.prototype._preActivateForIntermediateRendering=function(e){},i.prototype._activate=function(e){this._renderId=e},i.prototype.getWorldMatrix=function(){return this._masterMesh?this._masterMesh.getWorldMatrix():(this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix)},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.freezeWorldMatrix=function(){this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0},i.prototype.unfreezeWorldMatrix=function(){this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion)},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}},i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(t){var i,r,n;if(void 0===t.x){if(arguments.length<3)return;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n}},i.prototype.movePOV=function(e,t,i){this.position.addInPlace(this.calcMovePOV(e,t,i))},i.prototype.calcMovePOV=function(t,i,r){var n=new e.Matrix,o=this.rotationQuaternion?this.rotationQuaternion:e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);o.toRotationMatrix(n);var s=e.Vector3.Zero(),a=this.definedFacingForward?-1:1;return e.Vector3.TransformCoordinatesFromFloatsToRef(t*a,i,r*a,n,s),s},i.prototype.rotatePOV=function(e,t,i){this.rotation.addInPlace(this.calcRotatePOV(e,t,i))},i.prototype.calcRotatePOV=function(t,i,r){var n=this.definedFacingForward?1:-1;return new e.Vector3(t*n,i,r*n)},i.prototype.setPivotMatrix=function(e){this._pivotMatrix=e,this._cache.pivotMatrixUpdated=!0},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0},i.prototype._updateBoundingInfo=function(){this._boundingInfo=this._boundingInfo||new e.BoundingInfo(this.absolutePosition,this.absolutePosition),this._boundingInfo.update(this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)},i.prototype._updateSubMeshesBoundingInfo=function(e){if(this.subMeshes)for(var t=0;t<this.subMeshes.length;t++){var i=this.subMeshes[t];i.IsGlobal||i.updateBoundingInfo(e)}},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&(this._currentRenderId===this.getScene().getRenderId()||this.isSynchronized(!0)))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){var r=this.rotation.length();r&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}if(this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation)),this.infiniteDistance&&!this.parent){var n=this.getScene().activeCamera;if(n){var o=n.getWorldMatrix(),s=new e.Vector3(o.m[12],o.m[13],o.m[14]);e.Matrix.TranslationToRef(this.position.x+s.x,this.position.y+s.y,this.position.z+s.z,e.Tmp.Matrix[2])}}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&this.getScene().activeCamera){e.Tmp.Vector3[0].copyFrom(this.position);var a=e.Tmp.Vector3[0];if(this.parent&&this.parent.getWorldMatrix){this._markSyncedWithParent();var h;this._meshToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),h=e.Tmp.Matrix[6]):h=this.parent.getWorldMatrix(),e.Vector3.TransformNormalToRef(a,h,e.Tmp.Vector3[1]),a=e.Tmp.Vector3[1]}var c=this.getScene().activeCamera.globalPosition.clone();this.parent&&this.parent.position&&(a.addInPlace(this.parent.position),e.Matrix.TranslationToRef(a.x,a.y,a.z,e.Tmp.Matrix[2])),(this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL&&(this.billboardMode&i.BILLBOARDMODE_X&&(c.x=a.x+e.Epsilon),this.billboardMode&i.BILLBOARDMODE_Y&&(c.y=a.y+e.Epsilon),this.billboardMode&i.BILLBOARDMODE_Z&&(c.z=a.z+e.Epsilon)),e.Matrix.LookAtLHToRef(a,c,e.Vector3.Up(),e.Tmp.Matrix[3]),e.Tmp.Matrix[3].m[12]=e.Tmp.Matrix[3].m[13]=e.Tmp.Matrix[3].m[14]=0,e.Tmp.Matrix[3].invert(),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[3],this._localWorld),this._rotateYByPI.multiplyToRef(this._localWorld,e.Tmp.Matrix[5])}return e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix&&this.billboardMode===i.BILLBOARDMODE_NONE?(this._markSyncedWithParent(),this._meshToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix)):this._worldMatrix.copyFrom(this._localWorld),this._updateBoundingInfo(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrix},i.prototype.registerAfterWorldMatrixUpdate=function(e){this.onAfterWorldMatrixUpdateObservable.add(e)},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){this.onAfterWorldMatrixUpdateObservable.removeCallback(e)},i.prototype.setPositionWithLocalVector=function(t){this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld)},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld)},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,h=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(h,a);var c=-Math.atan2(a.z,a.x)-Math.PI/2,l=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,l);this.rotationQuaternion=this.rotationQuaternion||new e.Quaternion,e.Quaternion.RotationYawPitchRollToRef(c+r,u+n,o,this.rotationQuaternion)},i.prototype.attachToBone=function(e,t){this._meshToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1)},i.prototype.detachFromBone=function(){this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._meshToBoneReferal=null,this.parent=null},i.prototype.isInFrustum=function(e){return this._boundingInfo.isInFrustum(e)},i.prototype.isCompletelyInFrustum=function(e){return this._boundingInfo.isCompletelyInFrustum(e)},i.prototype.intersectsMesh=function(e,t){return!(!this._boundingInfo||!e._boundingInfo)&&this._boundingInfo.intersects(e._boundingInfo,t)},i.prototype.intersectsPoint=function(e){return!!this._boundingInfo&&this._boundingInfo.intersectsPoint(e)},i.prototype.setPhysicsState=function(t,i){return t.impostor&&(i=t,t=t.impostor),this.physicsImpostor=new e.PhysicsImpostor(this,t,i,this.getScene()),this.physicsImpostor.physicsBody},i.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},i.prototype.getPhysicsMass=function(){return this.physicsImpostor.getParam("mass")},i.prototype.getPhysicsFriction=function(){return this.physicsImpostor.getParam("friction")},i.prototype.getPhysicsRestitution=function(){return this.physicsImpostor.getParam("restitution")},i.prototype.getPositionInCameraSpace=function(t){return t||(t=this.getScene().activeCamera),e.Vector3.TransformCoordinates(this.absolutePosition,t.getViewMatrix())},i.prototype.getDistanceToCamera=function(e){return e||(e=this.getScene().activeCamera),this.absolutePosition.subtract(e.position).length()},i.prototype.applyImpulse=function(e,t){this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t)},i.prototype.setPhysicsLinkWith=function(t,i,r,n){this.physicsImpostor&&t.physicsImpostor&&this.physicsImpostor.createJoint(t.physicsImpostor,e.PhysicsJoint.HingeJoint,{mainPivot:i,connectedPivot:r,nativeParams:n})},i.prototype.updatePhysicsBodyPosition=function(){e.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()"),this.updatePhysicsBody()},i.prototype.updatePhysicsBody=function(){},Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return this._checkCollisions},set:function(e){this._checkCollisions=e,this.getScene().workerCollisions&&this.getScene().collisionCoordinator.onMeshUpdated(this)},enumerable:!0,configurable:!0}),i.prototype.moveWithCollisions=function(e){var t=this.getAbsolutePosition();t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPositionForCollisions),this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset),this._collider.radius=this.ellipsoid,this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions,e,this._collider,3,this,this._onCollisionPositionChange,this.uniqueId)},i.prototype.createOrUpdateSubmeshesOctree=function(t,i){void 0===t&&(t=64),void 0===i&&(i=2),this._submeshesOctree||(this._submeshesOctree=new e.Octree(e.Octree.CreationFuncForSubMeshes,t,i)),this.computeWorldMatrix(!0);var r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree},i.prototype._collideForSubMesh=function(t,i,r){if(this._generatePointsArray(),!t._lastColliderWorldVertices||!t._lastColliderTransformMatrix.equals(i)){t._lastColliderTransformMatrix=i.clone(),t._lastColliderWorldVertices=[],t._trianglePlanes=[];for(var n=t.verticesStart,o=t.verticesStart+t.verticesCount,s=n;s<o;s++)t._lastColliderWorldVertices.push(e.Vector3.TransformCoordinates(this._positions[s],i))}r._collide(t._trianglePlanes,t._lastColliderWorldVertices,this.getIndices(),t.indexStart,t.indexStart+t.indexCount,t.verticesStart,!!t.getMaterial()),r.collisionFound&&(r.collidedMesh=this)},i.prototype._processCollisionsForSubMeshes=function(e,t){var i,r;if(this._submeshesOctree&&this.useOctreeForCollisions){var n=e.velocityWorldLength+Math.max(e.radius.x,e.radius.y,e.radius.z),o=this._submeshesOctree.intersects(e.basePointWorld,n);r=o.length,i=o.data}else i=this.subMeshes,r=i.length;for(var s=0;s<r;s++){var a=i[s];r>1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}},i.prototype._checkCollision=function(t){this._boundingInfo._checkCollision(t)&&(e.Matrix.ScalingToRef(1/t.radius.x,1/t.radius.y,1/t.radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix))},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),h=this._submeshesOctree.intersectsRay(a);o=h.length,n=h.data}else n=this.subMeshes,o=n.length;for(var c=0;c<o;c++){var l=n[c];if(!(o>1)||l.canIntersects(t)){var u=l.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance<s.distance)&&(s=u,s.subMeshId=c,i))break}}if(s){var f=this.getWorldMatrix(),d=e.Vector3.TransformCoordinates(t.origin,f),p=t.direction.clone();p=p.scale(s.distance);var m=e.Vector3.TransformNormal(p,f),g=d.add(m);return r.hit=!0,r.distance=e.Vector3.Distance(d,g),r.pickedPoint=g,r.pickedMesh=this,r.bu=s.bu,r.bv=s.bv,r.faceId=s.faceId,r.subMeshId=s.subMeshId,r}return r},i.prototype.clone=function(e,t,i){return null},i.prototype.releaseSubMeshes=function(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array},i.prototype.dispose=function(e){var i,r=this;for(this.actionManager&&(this.actionManager.dispose(),this.actionManager=null),this.skeleton=null,this.getScene().stopAnimation(this),this.physicsImpostor&&this.physicsImpostor.dispose(),i=0;i<this._intersectionsInProgress.length;i++){var n=this._intersectionsInProgress[i],o=n._intersectionsInProgress.indexOf(this);n._intersectionsInProgress.splice(o,1)}this._intersectionsInProgress=[];var s=this.getScene().lights;if(s.forEach((function(e){var t=e.includedOnlyMeshes.indexOf(r);t!==-1&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(r),t!==-1&&e.excludedMeshes.splice(t,1);var i=e.getShadowGenerator();i&&(t=i.getShadowMap().renderList.indexOf(r),t!==-1&&i.getShadowMap().renderList.splice(t,1))})),this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this.releaseSubMeshes(),this.getScene().getEngine().unbindAllAttributes(),this.getScene().removeMesh(this),e){var a=this.getChildMeshes(!0);for(i=0;i<a.length;i++){var h=a[i];h.parent=null,h.computeWorldMatrix(!0)}}else{for(i=0;i<this.getScene().particleSystems.length;i++)this.getScene().particleSystems[i].emitter===this&&(this.getScene().particleSystems[i].dispose(),i--);var c=this.getDescendants(!0);for(i=0;i<c.length;i++)c[i].dispose()}this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this._isDisposed=!0,t.prototype.dispose.call(this)},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i)},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}e.Vector3.TransformCoordinatesToRef(t,r,this.position),this._pivotMatrix.m[12]=-t.x,this._pivotMatrix.m[13]=-t.y,this._pivotMatrix.m[14]=-t.z,this._cache.pivotMatrixUpdated=!0},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14]},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t)},i._BILLBOARDMODE_NONE=0,i._BILLBOARDMODE_X=1,i._BILLBOARDMODE_Y=2,i._BILLBOARDMODE_Z=4,i._BILLBOARDMODE_ALL=7,i._rotationAxisCache=new e.Quaternion,i._lookAtVectorCache=new e.Vector3(0,0,0),i})(e.Node);e.AbstractMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,i,r),this.diffuse=new e.Color3(1,1,1),this.specular=new e.Color3(1,1,1),this.intensity=1,this.range=Number.MAX_VALUE,this.includeOnlyWithLayerMask=0,this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this.excludeWithLayerMask=0,this.lightmapMode=0,this.radius=1e-5,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,r.addLight(this)}return __extends(i,t),Object.defineProperty(i,"LIGHTMAP_DEFAULT",{get:function(){return i._LIGHTMAP_DEFAULT},enumerable:!0,configurable:!0}),Object.defineProperty(i,"LIGHTMAP_SPECULAR",{get:function(){return i._LIGHTMAP_SPECULAR},enumerable:!0,configurable:!0}),Object.defineProperty(i,"LIGHTMAP_SHADOWSONLY",{get:function(){return i._LIGHTMAP_SHADOWSONLY},enumerable:!0,configurable:!0}),i.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},i.prototype.getShadowGenerator=function(){return this._shadowGenerator},i.prototype.getAbsolutePosition=function(){return e.Vector3.Zero()},i.prototype.transferToEffect=function(e,t,i){},i.prototype._getWorldMatrix=function(){return e.Matrix.Identity()},i.prototype.canAffectMesh=function(e){return!e||!(this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1)&&(!(this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1)&&((0===this.includeOnlyWithLayerMask||0!==(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId();var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.prototype.dispose=function(){this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this),this.getScene().removeLight(this),t.prototype.dispose.call(this)},i.prototype.getTypeID=function(){return 0},i.prototype.clone=function(t){return e.SerializationHelper.Clone(i.GetConstructorFromName(this.getTypeID(),t,this.getScene()),this)},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.type=this.getTypeID(),this.parent&&(t.parentId=this.parent.id),this.excludedMeshes.length>0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){switch(t){case 0:return function(){return new e.PointLight(i,e.Vector3.Zero(),r)};case 1:return function(){return new e.DirectionalLight(i,e.Vector3.Zero(),r)};case 2:return function(){return new e.SpotLight(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)};case 3:return function(){return new e.HemisphericLight(i,e.Vector3.Zero(),r)}}},i.Parse=function(t,r){var n=e.SerializationHelper.Parse(i.GetConstructorFromName(t.type,t.name,r),t,r);if(t.excludedMeshesIds&&(n._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(n._waitingParentId=t.parentId),t.animations){for(var o=0;o<t.animations.length;o++){var s=t.animations[o];n.animations.push(e.Animation.Parse(s))}e.Node.ParseAnimationRanges(n,t,r)}return t.autoAnimate&&r.beginAnimation(n,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),n},i._LIGHTMAP_DEFAULT=0,i._LIGHTMAP_SPECULAR=1,i._LIGHTMAP_SHADOWSONLY=2,__decorate([e.serializeAsColor3()],i.prototype,"diffuse",void 0),__decorate([e.serializeAsColor3()],i.prototype,"specular",void 0),__decorate([e.serialize()],i.prototype,"intensity",void 0),__decorate([e.serialize()],i.prototype,"range",void 0),__decorate([e.serialize()],i.prototype,"includeOnlyWithLayerMask",void 0),__decorate([e.serialize()],i.prototype,"excludeWithLayerMask",void 0),__decorate([e.serialize()],i.prototype,"lightmapMode",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),i})(e.Node);e.Light=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r){t.call(this,e,r),this.position=i}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(e,t){return this.parent&&this.parent.getWorldMatrix?(this.computeTransformedPosition(),void e.setFloat4(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0)):void e.setFloat4(t,this.position.x,this.position.y,this.position.z,0)},i.prototype.needCube=function(){return!0},i.prototype.supportsVSM=function(){return!1},i.prototype.needRefreshPerFrame=function(){return!1},i.prototype.getShadowDirection=function(t){switch(t){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3((-1),0,0);case 2:return new e.Vector3(0,(-1),0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,(-1))}return e.Vector3.Zero()},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;e.Matrix.PerspectiveFovLHToRef(Math.PI/2,1,n.minZ,n.maxZ,t)},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 0},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),i})(e.Light);e.PointLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){t.call(this,e,s),this.position=i,this.direction=r,this.angle=n,this.exponent=o}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;e.Matrix.PerspectiveFovLHToRef(this.angle,1,n.minZ,n.maxZ,t)},i.prototype.needCube=function(){return!1},i.prototype.supportsVSM=function(){return!0},i.prototype.needRefreshPerFrame=function(){return!1},i.prototype.getShadowDirection=function(e){return this.direction},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(t,i,r){var n;this.parent&&this.parent.getWorldMatrix?(this._transformedDirection||(this._transformedDirection=e.Vector3.Zero()),this.computeTransformedPosition(),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection),t.setFloat4(i,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent),n=e.Vector3.Normalize(this._transformedDirection)):(t.setFloat4(i,this.position.x,this.position.y,this.position.z,this.exponent),n=e.Vector3.Normalize(this.direction)),t.setFloat4(r,n.x,n.y,n.z,Math.cos(.5*this.angle))},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 2},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),__decorate([e.serialize()],i.prototype,"angle",void 0),__decorate([e.serialize()],i.prototype,"exponent",void 0),i})(e.Light);e.SpotLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,n),this.groundColor=new e.Color3(0,0,0),this.direction=r}return __extends(i,t),i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i,r){var n=e.Vector3.Normalize(this.direction);t.setFloat4(i,n.x,n.y,n.z,0),t.setColor3(r,this.groundColor.scale(this.intensity))},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return 3},__decorate([e.serializeAsColor3()],i.prototype,"groundColor",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r){t.call(this,e,r),this.shadowOrthoScale=.5,this.autoUpdateExtends=!0,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=i.scale(-1),this.direction=i}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;s<r.length;s++){var a=r[s];if(a){var h=a.getBoundingInfo();if(h)for(var c=h.boundingBox,l=0;l<c.vectorsWorld.length;l++)e.Vector3.TransformCoordinatesToRef(c.vectorsWorld[l],i,o),o.x<this._orthoLeft&&(this._orthoLeft=o.x),o.y<this._orthoBottom&&(this._orthoBottom=o.y),o.x>this._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}}var u=this._orthoRight-this._orthoLeft,f=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-f*this.shadowOrthoScale,this._orthoTop+f*this.shadowOrthoScale,-n.maxZ,n.maxZ,t)},i.prototype.supportsVSM=function(){return!0},i.prototype.needRefreshPerFrame=function(){return!0},i.prototype.needCube=function(){return!1},i.prototype.getShadowDirection=function(e){return this.direction},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(t,i){return this.parent&&this.parent.getWorldMatrix?(this._transformedDirection||(this._transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection),void t.setFloat4(i,this._transformedDirection.x,this._transformedDirection.y,this._transformedDirection.z,1)):void t.setFloat4(i,this.direction.x,this.direction.y,this.direction.z,1)},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 1},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),__decorate([e.serialize()],i.prototype,"shadowOrthoScale",void 0),__decorate([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.Light);e.DirectionalLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(i,r){var n=this;this._filter=t.FILTER_NONE,this.blurScale=2,this._blurBoxOffset=0,this._bias=5e-5,this._lightDirection=e.Vector3.Zero(),this.forceBackFacesOnly=!1,this._darkness=0,this._transparencyShadow=!1,this._viewMatrix=e.Matrix.Zero(),this._projectionMatrix=e.Matrix.Zero(),this._transformMatrix=e.Matrix.Zero(),this._worldViewProjection=e.Matrix.Zero(),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._useFullFloat=!0,this._light=r,this._scene=r.getScene(),this._mapSize=i,r._shadowGenerator=this;var o,s=this._scene.getEngine().getCaps();s.textureFloat&&s.textureFloatLinearFiltering&&s.textureFloatRender?(this._useFullFloat=!0,o=e.Engine.TEXTURETYPE_FLOAT):(this._useFullFloat=!1,o=e.Engine.TEXTURETYPE_UNSIGNED_INT),this._shadowMap=new e.RenderTargetTexture(r.name+"_shadowMap",i,this._scene,(!1),(!0),o,r.needCube()),
this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.NEAREST_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.onBeforeRenderObservable.add((function(e){n._currentFaceIndex=e})),this._shadowMap.onAfterUnbindObservable.add((function(){n.useBlurVarianceShadowMap&&(n._shadowMap2||(n._shadowMap2=new e.RenderTargetTexture(r.name+"_shadowMap",i,n._scene,(!1),(!0),o),n._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,n._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,n._shadowMap2.updateSamplingMode(e.Texture.TRILINEAR_SAMPLINGMODE),n._downSamplePostprocess=new e.PassPostProcess("downScale",1/n.blurScale,null,e.Texture.BILINEAR_SAMPLINGMODE,n._scene.getEngine()),n._downSamplePostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",n._shadowMap)})),n.blurBoxOffset=1),n._scene.postProcessManager.directRender([n._downSamplePostprocess,n._boxBlurPostprocess],n._shadowMap2.getInternalTexture()))}));var a=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id]&&void 0!==s.visibleInstances[t._id];if(n.isReady(t,a)){o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode);var h=t.getMaterial();if(n._effect.setMatrix("viewProjection",n.getTransformMatrix()),n._effect.setVector3("lightPosition",n.getLight().position),n.getLight().needCube()&&n._effect.setFloat2("depthValues",r.activeCamera.minZ,r.activeCamera.maxZ),h&&h.needAlphaTesting()){var c=h.getAlphaTestTexture();n._effect.setTexture("diffuseSampler",c),n._effect.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),n.forceBackFacesOnly&&o.setState(!0,0,!1,!0),i._processRendering(t,n._effect,e.Material.TriangleFillMode,s,a,(function(e,t){return n._effect.setMatrix("world",t)})),n.forceBackFacesOnly&&o.setState(!0,0,!1,!1)}else n._shadowMap.resetRefreshCounter()}};this._shadowMap.customRenderFunction=function(e,t,i){var r;for(r=0;r<e.length;r++)a(e.data[r]);for(r=0;r<t.length;r++)a(t.data[r]);if(n._transparencyShadow)for(r=0;r<i.length;r++)a(i.data[r])},this._shadowMap.onClearObservable.add((function(t){n.useBlurVarianceShadowMap||n.useVarianceShadowMap?t.clear(new e.Color4(0,0,0,0),!0,!0,!0):t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}))}return Object.defineProperty(t,"FILTER_NONE",{get:function(){return t._FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_VARIANCESHADOWMAP",{get:function(){return t._FILTER_VARIANCESHADOWMAP},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_POISSONSAMPLING",{get:function(){return t._FILTER_POISSONSAMPLING},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_BLURVARIANCESHADOWMAP",{get:function(){return t._FILTER_BLURVARIANCESHADOWMAP},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bias",{get:function(){return this._bias},set:function(e){this._bias=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(t){var i=this;this._blurBoxOffset!==t&&(this._blurBoxOffset=t,this._boxBlurPostprocess&&this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=new e.PostProcess("DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1/this.blurScale,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define OFFSET "+t),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",i._mapSize/i.blurScale,i._mapSize/i.blurScale)})))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"filter",{get:function(){return this._filter},set:function(t){this._filter!==t&&(this._filter=t,this.useVarianceShadowMap||this.useBlurVarianceShadowMap||this.usePoissonSampling?(this._shadowMap.anisotropicFilteringLevel=16,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)):(this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.NEAREST_SAMPLINGMODE)))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useVarianceShadowMap",{get:function(){return this.filter===t.FILTER_VARIANCESHADOWMAP&&this._light.supportsVSM()},set:function(e){this.filter=e?t.FILTER_VARIANCESHADOWMAP:t.FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"usePoissonSampling",{get:function(){return this.filter===t.FILTER_POISSONSAMPLING||!this._light.supportsVSM()&&(this.filter===t.FILTER_VARIANCESHADOWMAP||this.filter===t.FILTER_BLURVARIANCESHADOWMAP)},set:function(e){this.filter=e?t.FILTER_POISSONSAMPLING:t.FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBlurVarianceShadowMap",{get:function(){return this.filter===t.FILTER_BLURVARIANCESHADOWMAP&&this._light.supportsVSM()},set:function(e){this.filter=e?t.FILTER_BLURVARIANCESHADOWMAP:t.FILTER_NONE},enumerable:!0,configurable:!0}),t.prototype.isReady=function(t,i){var r=[];this._useFullFloat&&r.push("#define FULLFLOAT"),(this.useVarianceShadowMap||this.useBlurVarianceShadowMap)&&r.push("#define VSM"),this.getLight().needCube()&&r.push("#define CUBEMAP");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(s&&s.needAlphaTesting()&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind))){var a=s.getAlphaTestTexture();1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2"))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var h=r.join("\n");return this._cachedDefines!==h&&(this._cachedDefines=h,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightPosition","depthValues"],["diffuseSampler"],h)),this._effect.isReady()},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.getLight=function(){return this._light},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;return e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.computeTransformedPosition()&&(i=this._light.transformedPosition),!this._light.needRefreshPerFrame()&&this._cachedPosition&&this._cachedDirection&&i.equals(this._cachedPosition)&&this._lightDirection.equals(this._cachedDirection)||(this._cachedPosition=i.clone(),this._cachedDirection=this._lightDirection.clone(),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix),this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,this.getShadowMap().renderList),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)),this._transformMatrix},t.prototype.getDarkness=function(){return this._darkness},t.prototype.setDarkness=function(e){e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e},t.prototype.setTransparencyShadow=function(e){this._transparencyShadow=e},t.prototype._packHalf=function(t){var i=255*t,r=i-Math.floor(i);return new e.Vector2(t-r/255,r)},t.prototype.dispose=function(){this._shadowMap.dispose(),this._shadowMap2&&this._shadowMap2.dispose(),this._downSamplePostprocess&&this._downSamplePostprocess.dispose(),this._boxBlurPostprocess&&this._boxBlurPostprocess.dispose()},t.prototype.serialize=function(){var e={};e.lightId=this._light.id,e.mapSize=this.getShadowMap().getRenderSize(),e.useVarianceShadowMap=this.useVarianceShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.renderList=[];for(var t=0;t<this.getShadowMap().renderList.length;t++){var i=this.getShadowMap().renderList[t];e.renderList.push(i.id)}return e},t.Parse=function(e,i){for(var r=i.getLightByID(e.lightId),n=new t(e.mapSize,r),o=0;o<e.renderList.length;o++){var s=i.getMeshesByID(e.renderList[o]);s.forEach((function(e){n.getShadowMap().renderList.push(e)}))}return e.usePoissonSampling?n.usePoissonSampling=!0:e.useVarianceShadowMap?n.useVarianceShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurVarianceShadowMap=!0,e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset)),void 0!==e.bias&&(n.bias=e.bias),n.forceBackFacesOnly=e.forceBackFacesOnly,n},t._FILTER_NONE=0,t._FILTER_VARIANCESHADOWMAP=1,t._FILTER_POISSONSAMPLING=2,t._FILTER_BLURVARIANCESHADOWMAP=3,t})();e.ShadowGenerator=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t,i,r){return!(e.x>i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),h=(-i+s)/(2*t);if(a>h){var c=h;h=a,a=c}return a>0&&a<n?(e.root=a,e.found=!0,e):h>0&&h<n?(e.root=h,e.found=!0,e):e}})(),r=(function(){function r(){this.radius=new e.Vector3(1,1,1),this.retry=0,this.basePointWorld=e.Vector3.Zero(),this.velocityWorld=e.Vector3.Zero(),this.normalizedVelocity=e.Vector3.Zero(),this._collisionPoint=e.Vector3.Zero(),this._planeIntersectionPoint=e.Vector3.Zero(),this._tempVector=e.Vector3.Zero(),this._tempVector2=e.Vector3.Zero(),this._tempVector3=e.Vector3.Zero(),this._tempVector4=e.Vector3.Zero(),this._edge=e.Vector3.Zero(),this._baseToVertex=e.Vector3.Zero(),this._destinationPoint=e.Vector3.Zero(),this._slidePlaneNormal=e.Vector3.Zero(),this._displacementVector=e.Vector3.Zero()}return r.prototype._initialize=function(t,i,r){this.velocity=i,e.Vector3.NormalizeToRef(i,this.normalizedVelocity),this.basePoint=t,t.multiplyToRef(this.radius,this.basePointWorld),i.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=r,this.collisionFound=!1},r.prototype._checkPointInTriangle=function(t,i,r,n,o){i.subtractToRef(t,this._tempVector),r.subtractToRef(t,this._tempVector2),e.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var s=e.Vector3.Dot(this._tempVector4,o);return!(s<0)&&(n.subtractToRef(t,this._tempVector3),e.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),s=e.Vector3.Dot(this._tempVector4,o),!(s<0)&&(e.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),s=e.Vector3.Dot(this._tempVector4,o),s>=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this.basePointWorld,i),a=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(s>this.velocityWorldLength+a+r)&&!!t(n,o,this.basePointWorld,this.velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var h,c=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var l=r[t];if(a||l.isFrontFacingTo(this.normalizedVelocity,0)){var u=l.signedDistanceTo(this.basePoint),f=e.Vector3.Dot(l.normal,this.velocity);if(0==f){if(Math.abs(u)>=1)return;c=!0,h=0}else{h=(-1-u)/f;var d=(1-u)/f;if(h>d){var p=d;d=h,h=p}if(h>1||d<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var m=!1,g=1;if(c||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,l.normal)&&(m=!0,g=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!m){var _=this.velocity.lengthSquared(),v=_;this.basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,g);b.found&&(g=b.root,m=!0,this._collisionPoint.copyFrom(n)),this.basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,g),b.found&&(g=b.root,m=!0,this._collisionPoint.copyFrom(o)),this.basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,g),b.found&&(g=b.root,m=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex);var A=this._edge.lengthSquared(),T=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=A*-_+T*T,y=A*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*T*E,x=A*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,g),b.found){var M=(T*b.root-E)/A;M>=0&&M<=1&&(g=b.root,m=!0,this._edge.scaleInPlace(M),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this.basePoint,this._baseToVertex),A=this._edge.lengthSquared(),T=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex),v=A*-_+T*T,y=A*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*T*E,x=A*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,g),b.found&&(M=(T*b.root-E)/A,M>=0&&M<=1&&(g=b.root,m=!0,this._edge.scaleInPlace(M),o.addToRef(this._edge,this._collisionPoint))),n.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex),A=this._edge.lengthSquared(),T=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex),v=A*-_+T*T,y=A*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*T*E,x=A*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,g),b.found&&(M=(T*b.root-E)/A,M>=0&&M<=1&&(g=b.root,m=!0,this._edge.scaleInPlace(M),s.addToRef(this._edge,this._collisionPoint)))}if(m){var P=g*this.velocity.length();(!this.collisionFound||P<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=P,this.collisionFound=!0)}}},r.prototype._collide=function(e,t,i,r,n,o,s){for(var a=r;a<n;a+=3){var h=t[i[a]-o],c=t[i[a+1]-o],l=t[i[a+2]-o];this._testTriangle(a,e,l,c,h,s)}},r.prototype._getResponse=function(t,i){t.addToRef(i,this._destinationPoint),i.scaleInPlace(this.nearestDistance/i.length()),this.basePoint.addToRef(i,t),t.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),t.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(e.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,i)},r})();e.Collider=r})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){e.CollisionWorker="",(function(e){e[e.INIT=0]="INIT",e[e.UPDATE=1]="UPDATE",e[e.COLLIDE=2]="COLLIDE"})(e.WorkerTaskType||(e.WorkerTaskType={}));var t=e.WorkerTaskType;!(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.UNKNOWN_ERROR=1]="UNKNOWN_ERROR"})(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,r=(function(){function r(){var n=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){n._addUpdateMeshesList[e.uniqueId]=r.SerializeMesh(e)},this.onGeometryUpdated=function(e){n._addUpdateGeometriesList[e.id]=r.SerializeGeometry(e)},this._afterRender=function(){if(n._init&&!(0==n._toRemoveGeometryArray.length&&0==n._toRemoveMeshesArray.length&&0==Object.keys(n._addUpdateGeometriesList).length&&0==Object.keys(n._addUpdateMeshesList).length||n._runningUpdated>4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList,removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:n._runningCollisionTask=!1;var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;n._collisionsCallbackArray[s.collisionId](s.collisionId,e.Vector3.FromArray(s.newPosition),n._scene.getMeshByUniqueID(s.collidedMeshUniqueId)),n._collisionsCallbackArray[s.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r.radius,this._scaledPosition),i.divideToRef(r.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var h={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r.radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},c={payload:h,taskType:t.COLLIDE};this._worker.postMessage(c)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}})));var r=null;return t instanceof e.Mesh?r=t.geometry?t.geometry.id:null:t instanceof e.InstancedMesh&&(r=t.sourceMesh&&t.sourceMesh.geometry?t.sourceMesh.geometry.id:null),{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:t.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:t.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:t.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:t.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i.radius,this._scaledPosition),t.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i.radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r.retry>=n)return void o.copyFrom(t);r._initialize(t,i,a);for(var h=0;h<this._scene.meshes.length;h++){var c=this._scene.meshes[h];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==s&&c._checkCollision(r)}return r.collisionFound?(0===i.x&&0===i.y&&0===i.z||r._getResponse(t,i),i.length()<=a?void o.copyFrom(t):(r.retry++,void this._collideWithWorld(t,i,r,n,o,s))):void t.addToRef(i,o)},t})();e.CollisionCoordinatorLegacy=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o){t.call(this,r,o),this.upVector=e.Vector3.Up(),this.orthoLeft=null,this.orthoRight=null,this.orthoBottom=null,this.orthoTop=null,this.fov=.8,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this.mode=i.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new e.Viewport(0,0,1,1),this.layerMask=268435455,this.fovMode=i.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=i.RIG_MODE_NONE,this._rigCameras=new Array,this._computedViewMatrix=e.Matrix.Identity(),this._projectionMatrix=new e.Matrix,this._doNotComputeProjectionMatrix=!1,this._postProcesses=new Array,this._transformMatrix=e.Matrix.Zero(),this._webvrViewMatrix=e.Matrix.Identity(),this._activeMeshes=new e.SmartArray(256),this._globalPosition=e.Vector3.Zero(),this._refreshFrustumPlanes=!0,o.addCamera(this),o.activeCamera||(o.activeCamera=this),this.position=n}return __extends(i,t),Object.defineProperty(i,"PERSPECTIVE_CAMERA",{get:function(){return i._PERSPECTIVE_CAMERA},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ORTHOGRAPHIC_CAMERA",{get:function(){return i._ORTHOGRAPHIC_CAMERA},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOVMODE_VERTICAL_FIXED",{get:function(){return i._FOVMODE_VERTICAL_FIXED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOVMODE_HORIZONTAL_FIXED",{get:function(){return i._FOVMODE_HORIZONTAL_FIXED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_NONE",{get:function(){return i._RIG_MODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_ANAGLYPH",{get:function(){return i._RIG_MODE_STEREOSCOPIC_ANAGLYPH},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL",{get:function(){return i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED",{get:function(){return i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_OVERUNDER",{get:function(){return i._RIG_MODE_STEREOSCOPIC_OVERUNDER},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_VR",{get:function(){return i._RIG_MODE_VR},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_WEBVR",{get:function(){return i._RIG_MODE_WEBVR},enumerable:!0,configurable:!0}),i.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+this.getTypeName(),this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},Object.defineProperty(i.prototype,"globalPosition",{get:function(){return this._globalPosition},enumerable:!0,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.position=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this.getEngine();this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector),this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()},i.prototype._updateFromScene=function(){this.updateCache(),this.update()},i.prototype._isSynchronized=function(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronized.call(this)&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())},i.prototype._isSynchronizedProjectionMatrix=function(){var e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;var t=this.getEngine();return e=this.mode===i.PERSPECTIVE_CAMERA?this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this):this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight()},i.prototype.attachControl=function(e,t){},i.prototype.detachControl=function(e){},i.prototype.update=function(){this.cameraRigMode!==i.RIG_MODE_NONE&&this._updateRigCameras(),this._checkInputs()},i.prototype._checkInputs=function(){},i.prototype._cascadePostProcessesToRigCams=function(){this._postProcesses.length>0&&this._postProcesses[0].markTextureDirty();for(var t=0,i=this._rigCameras.length;t<i;t++){var r=this._rigCameras[t],n=r._rigPostProcess;if(n){var o=n instanceof e.PassPostProcess;o&&(r.isIntermediate=0===this._postProcesses.length),r._postProcesses=this._postProcesses.slice(0).concat(n),n.markTextureDirty()}else r._postProcesses=this._postProcesses.slice(0)}},i.prototype.attachPostProcess=function(t,i){return void 0===i&&(i=null),!t.isReusable()&&this._postProcesses.indexOf(t)>-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e,t){void 0===t&&(t=null);var i,r,n=[];if(t)for(t=t instanceof Array?t:[t],i=t.length-1;i>=0;i--)this._postProcesses[t[i]]===e?this._postProcesses.splice(r,1):n.push(i);else{var o=this._postProcesses.indexOf(e);o!==-1&&this._postProcesses.splice(o,1)}return this._cascadePostProcessesToRigCams(),n},i.prototype.getWorldMatrix=function(){this._worldMatrix||(this._worldMatrix=e.Matrix.Identity());var t=this.getViewMatrix();return t.invertToRef(this._worldMatrix),this._worldMatrix},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(t){return this._computedViewMatrix=this._computeViewMatrix(t),!t&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._refreshFrustumPlanes=!0,this.parent&&this.parent.getWorldMatrix?(this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._computedViewMatrix),this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12],this._computedViewMatrix.m[13],this._computedViewMatrix.m[14]),this._computedViewMatrix.invert(),this._markSyncedWithParent()):this._globalPosition.copyFrom(this.position),this._currentRenderId=this.getScene().getRenderId(),this._computedViewMatrix)},i.prototype._computeViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)return this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED),this._projectionMatrix;var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;return n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._projectionMatrix},i.prototype.getTranformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTranformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.dispose=function(){for(this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;)this._rigCameras.pop().dispose();
for(var e=0;e<this._postProcesses.length;++e)this._postProcesses[e].dispose(this);t.prototype.dispose.call(this)},i.prototype.setCameraRigMode=function(t,r){for(;this._rigCameras.length>0;)this._rigCameras.pop().dispose();switch(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE&&(this._rigCameras.push(this.createRigCamera(this.name+"_L",0)),this._rigCameras.push(this.createRigCamera(this.name+"_R",1))),this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var n=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,n);break;case i.RIG_MODE_VR:var o=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=o,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=o.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=o.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=o,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=o.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=o.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,o.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],(!1),o),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],(!0),o));break;case i.RIG_MODE_WEBVR:r.vrDisplay&&(this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix)}this._cascadePostProcessesToRigCams(),this.update()},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._getWebVRProjectionMatrix=function(){var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return[8,9,10,11].forEach((function(e){t[e]*=-1})),e.Matrix.FromArrayToRef(t,0,this._projectionMatrix),this._projectionMatrix},i.prototype._getWebVRViewMatrix=function(){var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return[8,9,10,11].forEach((function(e){t[e]*=-1})),e.Matrix.FromArrayToRef(t,0,this._webvrViewMatrix),this._webvrViewMatrix},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov;this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)},i.prototype._setupInputs=function(){},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.type=this.getTypeName(),this.parent&&(t.parentId=this.parent.id),this.inputs&&this.inputs.serialize(t),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.prototype.getTypeName=function(){return"Camera"},i.prototype.clone=function(t){return e.SerializationHelper.Clone(i.GetConstructorFromName(this.getTypeName(),t,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this)},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i)},i.GetConstructorFromName=function(t,i,r,n,o){switch(void 0===n&&(n=0),void 0===o&&(o=!0),t){case"ArcRotateCamera":return function(){return new e.ArcRotateCamera(i,0,0,1,e.Vector3.Zero(),r)};case"DeviceOrientationCamera":return function(){return new e.DeviceOrientationCamera(i,e.Vector3.Zero(),r)};case"FollowCamera":return function(){return new e.FollowCamera(i,e.Vector3.Zero(),r)};case"ArcFollowCamera":return function(){return new e.ArcFollowCamera(i,0,0,1,null,r)};case"GamepadCamera":return function(){return new e.GamepadCamera(i,e.Vector3.Zero(),r)};case"TouchCamera":return function(){return new e.TouchCamera(i,e.Vector3.Zero(),r)};case"VirtualJoysticksCamera":return function(){return new e.VirtualJoysticksCamera(i,e.Vector3.Zero(),r)};case"WebVRFreeCamera":return function(){return new e.WebVRFreeCamera(i,e.Vector3.Zero(),r)};case"VRDeviceOrientationFreeCamera":return function(){return new e.VRDeviceOrientationFreeCamera(i,e.Vector3.Zero(),r)};case"AnaglyphArcRotateCamera":return function(){return new e.AnaglyphArcRotateCamera(i,0,0,1,e.Vector3.Zero(),n,r)};case"AnaglyphFreeCamera":return function(){return new e.AnaglyphFreeCamera(i,e.Vector3.Zero(),n,r)};case"AnaglyphGamepadCamera":return function(){return new e.AnaglyphGamepadCamera(i,e.Vector3.Zero(),n,r)};case"AnaglyphUniversalCamera":return function(){return new e.AnaglyphUniversalCamera(i,e.Vector3.Zero(),n,r)};case"StereoscopicArcRotateCamera":return function(){return new e.StereoscopicArcRotateCamera(i,0,0,1,e.Vector3.Zero(),n,o,r)};case"StereoscopicFreeCamera":return function(){return new e.StereoscopicFreeCamera(i,e.Vector3.Zero(),n,o,r)};case"StereoscopicGamepadCamera":return function(){return new e.StereoscopicGamepadCamera(i,e.Vector3.Zero(),n,o,r)};case"StereoscopicUniversalCamera":return function(){return new e.StereoscopicUniversalCamera(i,e.Vector3.Zero(),n,o,r)};case"FreeCamera":return function(){return new e.UniversalCamera(i,e.Vector3.Zero(),r)};default:return function(){return new e.UniversalCamera(i,e.Vector3.Zero(),r)}}},i.Parse=function(t,r){var n=t.type,o=i.GetConstructorFromName(n,t.name,r,t.interaxial_distance,t.isStereoscopicSideBySide),s=e.SerializationHelper.Parse(o,t,r);if(t.parentId&&(s._waitingParentId=t.parentId),s.inputs&&(s.inputs.parse(t),s._setupInputs()),t.target&&s.setTarget&&s.setTarget(e.Vector3.FromArray(t.target)),t.cameraRigMode){var a=t.interaxial_distance?{interaxialDistance:t.interaxial_distance}:{};s.setCameraRigMode(t.cameraRigMode,a)}if(t.animations){for(var h=0;h<t.animations.length;h++){var c=t.animations[h];s.animations.push(e.Animation.Parse(c))}e.Node.ParseAnimationRanges(s,t,r)}return t.autoAnimate&&r.beginAnimation(s,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),s},i._PERSPECTIVE_CAMERA=0,i._ORTHOGRAPHIC_CAMERA=1,i._FOVMODE_VERTICAL_FIXED=0,i._FOVMODE_HORIZONTAL_FIXED=1,i._RIG_MODE_NONE=0,i._RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,i._RIG_MODE_STEREOSCOPIC_OVERUNDER=13,i._RIG_MODE_VR=20,i._RIG_MODE_WEBVR=21,i.ForceAttachControlToAlwaysPreventDefault=!1,__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"upVector",void 0),__decorate([e.serialize()],i.prototype,"orthoLeft",void 0),__decorate([e.serialize()],i.prototype,"orthoRight",void 0),__decorate([e.serialize()],i.prototype,"orthoBottom",void 0),__decorate([e.serialize()],i.prototype,"orthoTop",void 0),__decorate([e.serialize()],i.prototype,"fov",void 0),__decorate([e.serialize()],i.prototype,"minZ",void 0),__decorate([e.serialize()],i.prototype,"maxZ",void 0),__decorate([e.serialize()],i.prototype,"inertia",void 0),__decorate([e.serialize()],i.prototype,"mode",void 0),__decorate([e.serialize()],i.prototype,"layerMask",void 0),__decorate([e.serialize()],i.prototype,"fovMode",void 0),__decorate([e.serialize()],i.prototype,"cameraRigMode",void 0),__decorate([e.serialize()],i.prototype,"interaxialDistance",void 0),__decorate([e.serialize()],i.prototype,"isStereoscopicSideBySide",void 0),i})(e.Node);e.Camera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();return this.attached[i]?void e.Tools.Warn("camera input of type "+i+" already exists on camera"):(this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),void(this.attachedElement&&t.attachControl(this.attachedElement)))},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getTypeName()===e&&(i.detachControl(this.attachedElement),delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached){this.attached[r];this.attached[r].attachControl(t,i)}}},t.prototype.detachElement=function(e){if(this.attachedElement===e){for(var t in this.attached){this.attached[t];this.attached[t].detachControl(e)}this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getTypeName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getTypeName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){void 0===e&&(e=!0),this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getEngine();this._pointerInput||(this._pointerInput=function(o,s){var a=o.event;if((r.touchEnabled||"touch"!==a.pointerType)&&(o.type===e.PointerEventTypes.POINTERMOVE||r.buttons.indexOf(a.button)!==-1))if(o.type===e.PointerEventTypes.POINTERDOWN){try{a.srcElement.setPointerCapture(a.pointerId)}catch(h){}r.previousPosition={x:a.clientX,y:a.clientY},i||(a.preventDefault(),t.focus())}else if(o.type===e.PointerEventTypes.POINTERUP){try{a.srcElement.releasePointerCapture(a.pointerId)}catch(h){}r.previousPosition=null,i||a.preventDefault()}else if(o.type===e.PointerEventTypes.POINTERMOVE){if(!r.previousPosition||n.isPointerLock)return;var c=a.clientX-r.previousPosition.x,l=a.clientY-r.previousPosition.y;r.camera.getScene().useRightHandedSystem?r.camera.cameraRotation.y-=c/r.angularSensibility:r.camera.cameraRotation.y+=c/r.angularSensibility,r.camera.cameraRotation.x+=l/r.angularSensibility,r.previousPosition={x:a.clientX,y:a.clientY},i||a.preventDefault()}}),this._onMouseMove=function(e){if(n.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,o=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;r.camera.getScene().useRightHandedSystem?r.camera.cameraRotation.y-=t/r.angularSensibility:r.camera.cameraRotation.y+=t/r.angularSensibility,r.camera.cameraRotation.x+=o/r.angularSensibility,r.previousPosition=null,i||e.preventDefault()}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),t.addEventListener("mousemove",this._onMouseMove,!1)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),e.removeEventListener("mousemove",this._onMouseMove),this._observer=null,this._onMouseMove=null,this.previousPosition=null)},t.prototype.getTypeName=function(){return"FreeCameraMouseInput"},t.prototype.getSimpleName=function(){return"mouse"},__decorate([e.serialize()],t.prototype,"buttons",void 0),__decorate([e.serialize()],t.prototype,"angularSensibility",void 0),t})();e.FreeCameraMouseInput=t,e.CameraInputTypes.FreeCameraMouseInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._keys=[],this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39]}return t.prototype.attachControl=function(t,i){var r=this;this._onKeyDown||(t.tabIndex=1,this._onKeyDown=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t===-1&&r._keys.push(e.keyCode),i||e.preventDefault()}},this._onKeyUp=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t>=0&&r._keys.splice(t,1),i||e.preventDefault()}},t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]))},t.prototype.detachControl=function(t){this._onKeyDown&&(t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),this._keys=[],this._onKeyDown=null,this._onKeyUp=null)},t.prototype.checkInputs=function(){if(this._onKeyDown)for(var t=this.camera,i=0;i<this._keys.length;i++){var r=this._keys[i],n=t._computeLocalCameraSpeed();this.keysLeft.indexOf(r)!==-1?t._localDirection.copyFromFloats(-n,0,0):this.keysUp.indexOf(r)!==-1?t._localDirection.copyFromFloats(0,0,n):this.keysRight.indexOf(r)!==-1?t._localDirection.copyFromFloats(n,0,0):this.keysDown.indexOf(r)!==-1&&t._localDirection.copyFromFloats(0,0,-n),t.getScene().useRightHandedSystem&&(t._localDirection.z*=-1),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),e.Vector3.TransformNormalToRef(t._localDirection,t._cameraTransformMatrix,t._transformedDirection),t.cameraDirection.addInPlace(t._transformedDirection)}},t.prototype.getTypeName=function(){return"FreeCameraKeyboardMoveInput"},t.prototype._onLostFocus=function(e){this._keys=[]},t.prototype.getSimpleName=function(){return"keyboard"},__decorate([e.serialize()],t.prototype,"keysUp",void 0),__decorate([e.serialize()],t.prototype,"keysDown",void 0),__decorate([e.serialize()],t.prototype,"keysLeft",void 0),__decorate([e.serialize()],t.prototype,"keysRight",void 0),t})();e.FreeCameraKeyboardMoveInput=t,e.CameraInputTypes.FreeCameraKeyboardMoveInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerCount=0,this._pointerPressed=[],this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r,n=this;void 0===this._pointerInput&&(this._onLostFocus=function(e){n._offsetX=null,n._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),n._pointerPressed.push(s.pointerId),1!==n._pointerPressed.length)return;r={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=n._pointerPressed.indexOf(s.pointerId);if(a===-1)return;if(n._pointerPressed.splice(a,1),0!=a)return;r=null,n._offsetX=null,n._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!r)return;var a=n._pointerPressed.indexOf(s.pointerId);if(0!=a)return;n._offsetX=s.clientX-r.x,n._offsetY=-(s.clientY-r.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null,this._pointerPressed=[],this._offsetX=null,this._offsetY=null,this._pointerCount=0)},t.prototype.checkInputs=function(){if(this._offsetX){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getTypeName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},__decorate([e.serialize()],t.prototype,"touchAngularSensibility",void 0),__decorate([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){var t=this;this._screenOrientationAngle=0,this._screenQuaternion=new e.Quaternion,this._alpha=0,this._beta=0,this._gamma=0,this._orientationChanged=function(){t._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,t._screenOrientationAngle=-e.Tools.ToRadians(t._screenOrientationAngle/2),t._screenQuaternion.copyFromFloats(0,Math.sin(t._screenOrientationAngle),0,Math.cos(t._screenOrientationAngle))},this._deviceOrientation=function(e){t._alpha=e.alpha,t._beta=e.beta,t._gamma=e.gamma},this._constantTranform=new e.Quaternion((-Math.sqrt(.5)),0,0,Math.sqrt(.5)),this._orientationChanged()}return Object.defineProperty(t.prototype,"camera",{get:function(){return this._camera},set:function(t){this._camera=t,this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new e.Quaternion)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){window.addEventListener("orientationchange",this._orientationChanged),window.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()},t.prototype.detachControl=function(e){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation)},t.prototype.checkInputs=function(){this._alpha&&(e.Quaternion.RotationYawPitchRollToRef(e.Tools.ToRadians(this._alpha),e.Tools.ToRadians(this._beta),-e.Tools.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)},t.prototype.getTypeName=function(){return"FreeCameraDeviceOrientationInput"},t.prototype.getSimpleName=function(){return"deviceOrientation"},t})();e.FreeCameraDeviceOrientationInput=t,e.CameraInputTypes.FreeCameraDeviceOrientationInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this;this._gamepads=new e.Gamepads(function(e){r._onNewGameConnected(e)})},t.prototype.detachControl=function(e){this._gamepads&&this._gamepads.dispose(),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var t=this.camera,i=this.gamepad.leftStick,r=i.x/this.gamepadMoveSensibility,n=i.y/this.gamepadMoveSensibility;i.x=Math.abs(r)>.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick,s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0;var h=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),c=50*t._computeLocalCameraSpeed(),l=e.Vector3.TransformCoordinates(new e.Vector3(i.x*c,0,-i.y*c),h);t.cameraDirection=t.cameraDirection.add(l),t.cameraRotation=t.cameraRotation.add(new e.Vector2(o.y,o.x))}},t.prototype._onNewGameConnected=function(e){0===e.index&&(this.gamepad=e)},t.prototype.getTypeName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},__decorate([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),__decorate([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._keys=[],this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39]}return t.prototype.attachControl=function(t,i){var r=this;t.tabIndex=1,this._onKeyDown=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t===-1&&r._keys.push(e.keyCode),e.preventDefault&&(i||e.preventDefault())}},this._onKeyUp=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t>=0&&r._keys.splice(t,1),e.preventDefault&&(i||e.preventDefault())}},this._onLostFocus=function(){r._keys=[]},t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){t&&(t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp)),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),this._keys=[],this._onKeyDown=null,this._onKeyUp=null,this._onLostFocus=null},t.prototype.checkInputs=function(){if(this._onKeyDown)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t];this.keysLeft.indexOf(i)!==-1?e.inertialAlphaOffset-=.01:this.keysUp.indexOf(i)!==-1?e.inertialBetaOffset-=.01:this.keysRight.indexOf(i)!==-1?e.inertialAlphaOffset+=.01:this.keysDown.indexOf(i)!==-1&&(e.inertialBetaOffset+=.01)}},t.prototype.getTypeName=function(){return"ArcRotateCameraKeyboardMoveInput"},t.prototype.getSimpleName=function(){return"keyboard"},__decorate([e.serialize()],t.prototype,"keysUp",void 0),__decorate([e.serialize()],t.prototype,"keysDown",void 0),__decorate([e.serialize()],t.prototype,"keysLeft",void 0),__decorate([e.serialize()],t.prototype,"keysRight",void 0),t})();e.ArcRotateCameraKeyboardMoveInput=t,e.CameraInputTypes.ArcRotateCameraKeyboardMoveInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.wheelPrecision=3}return t.prototype.attachControl=function(t,i){var r=this;this._wheel=function(t,n){if(t.type===e.PointerEventTypes.POINTERWHEEL){var o=t.event,s=0;o.wheelDelta?s=o.wheelDelta/(40*r.wheelPrecision):o.detail&&(s=-o.detail/r.wheelPrecision),s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getTypeName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},__decorate([e.serialize()],t.prototype,"wheelPrecision",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(e.Tools.GetPointerPrefix(),(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=6,this.panningSensibility=50,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n,o,s=this,a=this.camera.getEngine(),h=0;this._pointerInput=function(a,c){var l=a.event;if(a.type===e.PointerEventTypes.POINTERMOVE||s.buttons.indexOf(l.button)!==-1)if(a.type===e.PointerEventTypes.POINTERDOWN){try{l.srcElement.setPointerCapture(l.pointerId)}catch(u){}s._isPanClick=l.button===s.camera._panningMouseButton,r={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType},void 0===n?n=r:void 0===o&&(o=r),i||(l.preventDefault(),t.focus())}else if(a.type===e.PointerEventTypes.POINTERUP){try{l.srcElement.releasePointerCapture(l.pointerId)}catch(u){}r=null,h=0,n=o=void 0,i||l.preventDefault()}else if(a.type===e.PointerEventTypes.POINTERMOVE)if(i||l.preventDefault(),n&&void 0===o){if(0!==s.panningSensibility&&(l.ctrlKey&&s.camera._useCtrlForPanning||!s.camera._useCtrlForPanning&&s._isPanClick))s.camera.inertialPanningX+=-(l.clientX-r.x)/s.panningSensibility,s.camera.inertialPanningY+=(l.clientY-r.y)/s.panningSensibility;else{var f=l.clientX-r.x,d=l.clientY-r.y;s.camera.inertialAlphaOffset-=f/s.angularSensibilityX,s.camera.inertialBetaOffset-=d/s.angularSensibilityY}r.x=l.clientX,r.y=l.clientY}else if(n&&o){var p=n.pointerId===l.pointerId?n:o;p.x=l.clientX,p.y=l.clientY;var m=s.pinchInwards?1:-1,g=n.x-o.x,_=n.y-o.y,v=g*g+_*_;if(0===h)return void(h=v);v!==h&&(s.camera.inertialRadiusOffset+=(v-h)/(s.pinchPrecision*((s.angularSensibilityX+s.angularSensibilityY)/2)*m),h=v)}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){n=o=void 0,h=0,r=null},this._onMouseMove=function(e){if(a.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;s.camera.inertialAlphaOffset-=t/s.angularSensibilityX,s.camera.inertialBetaOffset-=r/s.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(s._MSGestureHandler||(s._MSGestureHandler=new MSGesture,s._MSGestureHandler.target=t),s._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){s.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,t.removeEventListener("contextmenu",this._onContextMenu),t.removeEventListener("mousemove",this._onMouseMove),t.removeEventListener("MSPointerDown",this._onGestureStart),t.removeEventListener("MSGestureChange",this._onGesture),t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),this._isPanClick=!1,this.pinchInwards=!0,this._onKeyDown=null,this._onKeyUp=null,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.getTypeName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},__decorate([e.serialize()],t.prototype,"buttons",void 0),__decorate([e.serialize()],t.prototype,"angularSensibilityX",void 0),__decorate([e.serialize()],t.prototype,"angularSensibilityY",void 0),__decorate([e.serialize()],t.prototype,"pinchPrecision",void 0),__decorate([e.serialize()],t.prototype,"panningSensibility",void 0),t})());e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this;this._gamepads=new e.Gamepads(function(e){r._onNewGameConnected(e)})},t.prototype.detachControl=function(e){this._gamepads&&this._gamepads.dispose(),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}var n=this.gamepad.leftStick;if(0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype._onNewGameConnected=function(e){0===e.index&&(this.gamepad=e)},t.prototype.getTypeName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},__decorate([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),__decorate([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.alphaCorrection=1,this.betaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._beta=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}return e.prototype.attachControl=function(e,t){this.camera.attachControl(e,t),window.addEventListener("deviceorientation",this._deviceOrientationHandler);
},e.prototype._onOrientationEvent=function(e){this.camera;this._alpha=0|+e.alpha,this._beta=0|+e.beta,this._gamma=0|+e.gamma,this._dirty=!0},e.prototype.checkInputs=function(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)},e.prototype.detachControl=function(e){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype.getTypeName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"VRDeviceOrientation"},e})();e.ArcRotateCameraVRDeviceOrientationInput=t,e.CameraInputTypes.ArcRotateCameraVRDeviceOrientationInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,r,n),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0),this.rotation=new e.Vector3(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.lockedTarget=null,this._currentTarget=e.Vector3.Zero(),this._viewMatrix=e.Matrix.Zero(),this._camMatrix=e.Matrix.Zero(),this._cameraTransformMatrix=e.Matrix.Zero(),this._cameraRotationMatrix=e.Matrix.Zero(),this._referencePoint=new e.Vector3(0,0,1),this._defaultUpVector=new e.Vector3(0,1,0),this._transformedReferencePoint=e.Vector3.Zero(),this._lookAtTemp=e.Matrix.Zero(),this._tempMatrix=e.Matrix.Zero()}return __extends(i,t),i.prototype.getFrontPosition=function(e){var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this._defaultUpVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r&&(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,!this.noRotationConstraint)){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}i&&(Math.abs(this.cameraDirection.x)<e.Epsilon&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<e.Epsilon&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<e.Epsilon&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),r&&(Math.abs(this.cameraRotation.x)<e.Epsilon&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<e.Epsilon&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),t.prototype._checkInputs.call(this)},i.prototype._updateCameraRotationMatrix=function(){this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix),e.Vector3.TransformNormalToRef(this._defaultUpVector,this._cameraRotationMatrix,this.upVector)):e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)},i.prototype._getViewMatrix=function(){return this.lockedTarget?this._currentTarget.copyFrom(this._getLockedTargetPosition()):(this._updateCameraRotationMatrix(),e.Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget)),this.getScene().useRightHandedSystem?e.Matrix.LookAtRHToRef(this.position,this._currentTarget,this.upVector,this._viewMatrix):e.Matrix.LookAtLHToRef(this.position,this._currentTarget,this.upVector,this._viewMatrix),this._viewMatrix},i.prototype.createRigCamera=function(t,r){if(this.cameraRigMode!==e.Camera.RIG_MODE_NONE){var n=new i(t,this.position.clone(),this.getScene());return this.cameraRigMode!==e.Camera.RIG_MODE_VR&&this.cameraRigMode!==e.Camera.RIG_MODE_WEBVR||(this.rotationQuaternion||(this.rotationQuaternion=new e.Quaternion),n._cameraRigParams={},n.rotationQuaternion=new e.Quaternion),n}return null},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:var n=this.cameraRigMode===e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,o=this.cameraRigMode===e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle*n,i.position),this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle*o,r.position),i.setTarget(this.getTarget()),r.setTarget(this.getTarget());break;case e.Camera.RIG_MODE_VR:case e.Camera.RIG_MODE_WEBVR:i.rotationQuaternion?(i.rotationQuaternion.copyFrom(this.rotationQuaternion),r.rotationQuaternion.copyFrom(this.rotationQuaternion)):(i.rotation.copyFrom(this.rotation),r.rotation.copyFrom(this.rotation)),i.position.copyFrom(this.position),r.position.copyFrom(this.position)}t.prototype._updateRigCameras.call(this)},i.prototype._getRigCamPosition=function(t,i){this._rigCamTransformMatrix||(this._rigCamTransformMatrix=new e.Matrix);var r=this.getTarget();e.Matrix.Translation(-r.x,-r.y,-r.z).multiplyToRef(e.Matrix.RotationY(t),this._rigCamTransformMatrix),this._rigCamTransformMatrix=this._rigCamTransformMatrix.multiply(e.Matrix.Translation(r.x,r.y,r.z)),e.Vector3.TransformCoordinatesToRef(this.position,this._rigCamTransformMatrix,i)},i.prototype.getTypeName=function(){return"TargetCamera"},__decorate([e.serializeAsVector3()],i.prototype,"rotation",void 0),__decorate([e.serialize()],i.prototype,"speed",void 0),__decorate([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.Camera);e.TargetCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){var o=this;t.call(this,i,r,n),this.ellipsoid=new e.Vector3(.5,1,.5),this.checkCollisions=!1,this.applyGravity=!1,this._collider=new e.Collider,this._needMoveForGravity=!1,this._oldPosition=e.Vector3.Zero(),this._diffPosition=e.Vector3.Zero(),this._newPosition=e.Vector3.Zero(),this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),o.getScene().workerCollisions&&i.multiplyInPlace(o._collider.radius);var n=function(t){o._newPosition.copyFrom(t),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition);o.position.clone();o._diffPosition.length()>e.Engine.CollisionsEpsilon&&(o.position.addInPlace(o._diffPosition),o.onCollide&&r&&o.onCollide(r))};n(i)},this.inputs=new e.FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}return __extends(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;if(e)return e.angularSensibility},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysUp},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysDown},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysLeft},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysRight},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._collider.radius=this.ellipsoid;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):this.position.addInPlace(this.cameraDirection)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getTypeName=function(){return"FreeCamera"},__decorate([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),__decorate([e.serialize()],i.prototype,"checkCollisions",void 0),__decorate([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e){t.call(this,e)}return __extends(i,t),i.prototype.addKeyboard=function(){return this.add(new e.FreeCameraKeyboardMoveInput),this},i.prototype.addMouse=function(t){return void 0===t&&(t=!0),this.add(new e.FreeCameraMouseInput(t)),this},i.prototype.addGamepad=function(){return this.add(new e.FreeCameraGamepadInput),this},i.prototype.addDeviceOrientation=function(){return this.add(new e.FreeCameraDeviceOrientationInput),this},i.prototype.addTouch=function(){return this.add(new e.FreeCameraTouchInput),this},i.prototype.addVirtualJoystick=function(){return this.add(new e.FreeCameraVirtualJoystickInput),this},i})(e.CameraInputsManager);e.FreeCameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n){t.call(this,e,i,r),this.radius=12,this.rotationOffset=0,this.heightOffset=4,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=n}return __extends(i,t),i.prototype.getRadians=function(e){return e*Math.PI/180},i.prototype.follow=function(t){if(t){var i;if(t.rotationQuaternion){var r=new e.Matrix;t.rotationQuaternion.toRotationMatrix(r),i=Math.atan2(r.m[8],r.m[10])}else i=t.rotation.y;var n=this.getRadians(this.rotationOffset)+i,o=t.position.x+Math.sin(n)*this.radius,s=t.position.z+Math.cos(n)*this.radius,a=o-this.position.x,h=t.position.y+this.heightOffset-this.position.y,c=s-this.position.z,l=a*this.cameraAcceleration*2,u=h*this.cameraAcceleration,f=c*this.cameraAcceleration*2;(l>this.maxCameraSpeed||l<-this.maxCameraSpeed)&&(l=l<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+l,this.position.y+u,this.position.z+f),this.setTarget(t.position)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow(this.lockedTarget)},i.prototype.getTypeName=function(){return"FollowCamera"},__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serialize()],i.prototype,"rotationOffset",void 0),__decorate([e.serialize()],i.prototype,"heightOffset",void 0),__decorate([e.serialize()],i.prototype,"cameraAcceleration",void 0),__decorate([e.serialize()],i.prototype,"maxCameraSpeed",void 0),__decorate([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){t.call(this,i,e.Vector3.Zero(),a),this.alpha=r,this.beta=n,this.radius=o,this.target=s,this._cartesianCoordinates=e.Vector3.Zero(),this.follow()}return __extends(i,t),i.prototype.follow=function(){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta),this.position=this.target.position.add(this._cartesianCoordinates),this.setTarget(this.target.position)},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getTypeName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addTouch(),this._setupInputs()}return __extends(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;if(e)return e.touchAngularSensibility},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;if(e)return e.touchMoveSensibility},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getTypeName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;t.call(this,i,e.Vector3.Zero(),a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.zoomOnFactor=1,this.targetScreenOffset=e.Vector2.Zero(),this.allowUpsideDown=!0,this._viewMatrix=new e.Matrix,this.panningAxis=new e.Vector3(1,1,0),this.checkCollisions=!1,this.collisionRadius=new e.Vector3(.5,.5,.5),this._collider=new e.Collider,this._previousPosition=e.Vector3.Zero(),this._collisionVelocity=e.Vector3.Zero(),this._newPosition=e.Vector3.Zero(),this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),h.getScene().workerCollisions&&h.checkCollisions&&i.multiplyInPlace(h._collider.radius),r?(h.setPosition(i),h.onCollide&&h.onCollide(r)):h._previousPosition.copyFrom(h.position);var n=Math.cos(h.alpha),o=Math.sin(h.alpha),s=Math.cos(h.beta),a=Math.sin(h.beta);0===a&&(a=1e-4);var c=h._getTargetPosition();c.addToRef(new e.Vector3(h.radius*n*a,h.radius*s,h.radius*o*a),h._newPosition),h.position.copyFrom(h._newPosition);var l=h.upVector;h.allowUpsideDown&&h.beta<0&&(l=l.clone(),l=l.negate()),e.Matrix.LookAtLHToRef(h.position,c,l,h._viewMatrix),h._viewMatrix.m[12]+=h.targetScreenOffset.x,h._viewMatrix.m[13]+=h.targetScreenOffset.y,h._collisionTriggered=!1},s?this.target=s:this.target=e.Vector3.Zero(),this.alpha=r,this.beta=n,this.radius=o,this.getViewMatrix(),this.inputs=new e.ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad()}return __extends(i,t),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.angularSensibilityX},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.angularSensibilityY},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.pinchPrecision},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.panningSensibility},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysUp},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysDown},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysLeft},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysRight},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;if(e)return e.wheelPrecision},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache.target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this.target.getAbsolutePosition){var e=this.target.getAbsolutePosition();return this._targetBoundingCenter?e.add(this._targetBoundingCenter):e}return this.target},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache.target.equals(this.target)&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){this._collisionTriggered||(this.inputs.checkInputs(),0===this.inertialAlphaOffset&&0===this.inertialBetaOffset&&0===this.inertialRadiusOffset||(this.getScene().useRightHandedSystem?this.alpha-=this.beta<=0?-this.inertialAlphaOffset:this.inertialAlphaOffset:this.alpha+=this.beta<=0?-this.inertialAlphaOffset:this.inertialAlphaOffset,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<e.Epsilon&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<e.Epsilon&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<e.Epsilon&&(this.inertialRadiusOffset=0)),0===this.inertialPanningX&&0===this.inertialPanningY||(this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inertialPanningX*=this.inertia,this.inertialPanningY*=this.inertia,Math.abs(this.inertialPanningX)<e.Epsilon&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<e.Epsilon&&(this.inertialPanningY=0),this._localDirection.copyFromFloats(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY),this._localDirection.multiplyInPlace(this.panningAxis),this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.Vector3.TransformNormalToRef(this._localDirection,this._cameraTransformMatrix,this._transformedDirection),this.panningAxis.y||(this._transformedDirection.y=0),this.target.getAbsolutePosition||this.target.addInPlace(this._transformedDirection)),this._checkLimits(),t.prototype._checkInputs.call(this))},i.prototype._checkLimits=function(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){var e=this.position.subtract(this._getTargetPosition());this.radius=e.length(),this.alpha=Math.acos(e.x/Math.sqrt(Math.pow(e.x,2)+Math.pow(e.z,2))),e.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(e.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t){void 0===t&&(t=!1),this._getTargetPosition().equals(e)||(t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.center.clone():this._targetBoundingCenter=null,this.target=e,this.rebuildAnglesAndRadius())},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(o.addToRef(new e.Vector3(this.radius*t*n,this.radius*r,this.radius*i*n),this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider.radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0,this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&this.beta<0&&(s=s.clone(),s=s.negate()),this.getScene().useRightHandedSystem?e.Matrix.LookAtRHToRef(this.position,o,s,this._viewMatrix):e.Matrix.LookAtLHToRef(this.position,o,s,this._viewMatrix),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;void 0===t.min?(r=t||this.getScene().meshes,r=e.Mesh.MinMax(r),n=e.Vector3.Distance(r.min,r.max)):(r=t,n=t.distance),this.target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this.target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getTypeName=function(){return"ArcRotateCamera"},__decorate([e.serialize()],i.prototype,"alpha",void 0),__decorate([e.serialize()],i.prototype,"beta",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serializeAsVector3()],i.prototype,"target",void 0),__decorate([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),__decorate([e.serialize()],i.prototype,"inertialBetaOffset",void 0),__decorate([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),__decorate([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),__decorate([e.serialize()],i.prototype,"upperAlphaLimit",void 0),__decorate([e.serialize()],i.prototype,"lowerBetaLimit",void 0),__decorate([e.serialize()],i.prototype,"upperBetaLimit",void 0),__decorate([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),__decorate([e.serialize()],i.prototype,"upperRadiusLimit",void 0),__decorate([e.serialize()],i.prototype,"inertialPanningX",void 0),__decorate([e.serialize()],i.prototype,"inertialPanningY",void 0),__decorate([e.serialize()],i.prototype,"zoomOnFactor",void 0),__decorate([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e){t.call(this,e)}return __extends(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addGamepad=function(){return this.add(new e.ArcRotateCameraGamepadInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderinGroupInfo=null,this._scene=e;for(var i=t.MIN_RENDERINGGROUPS;i<t.MAX_RENDERINGGROUPS;i++)this._autoClearDepthStencil[i]=!0}return t.prototype._renderParticles=function(e,t){if(0!==this._scene._activeParticleSystems.length){var i=this._scene.activeCamera;this._scene._particlesDuration.beginMonitoring();for(var r=0;r<this._scene._activeParticleSystems.length;r++){var n=this._scene._activeParticleSystems.data[r];n.renderingGroupId===e&&0!==(i.layerMask&n.layerMask)&&(this._clearDepthStencilBuffer(),n.emitter.position&&t&&t.indexOf(n.emitter)===-1||this._scene._activeParticles.addCount(n.render(),!1))}this._scene._particlesDuration.endMonitoring(!1)}},t.prototype._renderSprites=function(e){if(this._scene.spritesEnabled&&0!==this._scene.spriteManagers.length){var t=this._scene.activeCamera;this._scene._spritesDuration.beginMonitoring();for(var i=0;i<this._scene.spriteManagers.length;i++){var r=this._scene.spriteManagers[i];r.renderingGroupId===e&&0!==(t.layerMask&r.layerMask)&&(this._clearDepthStencilBuffer(),r.render())}this._scene._spritesDuration.endMonitoring(!1)}},t.prototype._clearDepthStencilBuffer=function(){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(0,!1,!0,!0),this._depthStencilBufferAlreadyCleaned=!0)},t.prototype._renderSpritesAndParticles=function(){this._currentRenderSprites&&this._renderSprites(this._currentIndex),this._currentRenderParticles&&this._renderParticles(this._currentIndex,this._currentActiveMeshes)},t.prototype.render=function(i,r,n,o){var s=this._scene.onRenderingGroupObservable.hasObservers()?this._scene.onRenderingGroupObservable:null,a=null;s&&(this._renderinGroupInfo||(this._renderinGroupInfo=new e.RenderingGroupInfo),a=this._renderinGroupInfo,a.scene=this._scene,a.camera=this._scene.activeCamera),this._currentActiveMeshes=r,this._currentRenderParticles=n,this._currentRenderSprites=o;for(var h=t.MIN_RENDERINGGROUPS;h<t.MAX_RENDERINGGROUPS;h++){this._depthStencilBufferAlreadyCleaned=h===t.MIN_RENDERINGGROUPS;var c=this._renderingGroups[h],l=!1;if(this._currentIndex=h,c){var u=0;s&&(u=Math.pow(2,h),a.renderStage=e.RenderingGroupInfo.STAGE_PRECLEAR,a.renderingGroupId=h,s.notifyObservers(a,u)),this._autoClearDepthStencil[h]&&this._clearDepthStencilBuffer(),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_PREOPAQUE,s.notifyObservers(a,u)),c.onBeforeTransparentRendering||(c.onBeforeTransparentRendering=this._renderSpritesAndParticles.bind(this)),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_PRETRANSPARENT,s.notifyObservers(a,u)),c.render(i)||(this._renderingGroups.splice(h,1),l=!0,this._renderSpritesAndParticles()),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_POSTTRANSPARENT,s.notifyObservers(a,u))}else if(this._renderSpritesAndParticles(),s){var u=Math.pow(2,h);a.renderStage=e.RenderingGroupInfo.STAGE_PRECLEAR,
a.renderingGroupId=h,s.notifyObservers(a,u),a.renderStage=e.RenderingGroupInfo.STAGE_POSTTRANSPARENT,s.notifyObservers(a,u)}l&&h--}},t.prototype.reset=function(){for(var e=t.MIN_RENDERINGGROUPS;e<t.MAX_RENDERINGGROUPS;e++){var i=this._renderingGroups[e];i&&i.prepare()}},t.prototype.dispatch=function(t){var i=t.getMesh(),r=i.renderingGroupId||0;this._renderingGroups[r]||(this._renderingGroups[r]=new e.RenderingGroup(r,this._scene,this._customOpaqueSortCompareFn[r],this._customAlphaTestSortCompareFn[r],this._customTransparentSortCompareFn[r])),this._renderingGroups[r].dispatch(t)},t.prototype.setRenderingOrder=function(e,t,i,r){if(void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){var n=this._renderingGroups[e];n.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],n.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],n.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}},t.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._autoClearDepthStencil[e]=t},t.MAX_RENDERINGGROUPS=4,t.MIN_RENDERINGGROUPS=0,t})();e.RenderingManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=null),this.index=t,this._opaqueSubMeshes=new e.SmartArray(256),this._transparentSubMeshes=new e.SmartArray(256),this._alphaTestSubMeshes=new e.SmartArray(256),this._scene=i,this.opaqueSortCompareFn=r,this.alphaTestSortCompareFn=n,this.transparentSortCompareFn=o}return Object.defineProperty(t.prototype,"opaqueSortCompareFn",{set:function(e){this._opaqueSortCompareFn=e,e?this._renderOpaque=this.renderOpaqueSorted:this._renderOpaque=t.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"alphaTestSortCompareFn",{set:function(e){this._alphaTestSortCompareFn=e,e?this._renderAlphaTest=this.renderAlphaTestSorted:this._renderAlphaTest=t.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transparentSortCompareFn",{set:function(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=t.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!0,configurable:!0}),t.prototype.render=function(t){if(t)return t(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes),!0;if(0===this._opaqueSubMeshes.length&&0===this._alphaTestSubMeshes.length&&0===this._transparentSubMeshes.length)return this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),!1;var i=this._scene.getEngine();return this._renderOpaque(this._opaqueSubMeshes),i.setAlphaTesting(!0),this._renderAlphaTest(this._alphaTestSubMeshes),i.setAlphaTesting(!1),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),this._renderTransparent(this._transparentSubMeshes),i.setAlphaMode(e.Engine.ALPHA_DISABLE),!0},t.prototype.renderOpaqueSorted=function(e){return t.renderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera.globalPosition,!1)},t.prototype.renderAlphaTestSorted=function(e){return t.renderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera.globalPosition,!1)},t.prototype.renderTransparentSorted=function(e){return t.renderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera.globalPosition,!0)},t.renderSorted=function(e,t,i,r){for(var n,o=0;o<e.length;o++)n=e.data[o],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=n.getBoundingInfo().boundingSphere.centerWorld.subtract(i).length();var s=e.data.slice(0,e.length);for(s.sort(t),o=0;o<s.length;o++)n=s[o],n.render(r)},t.renderUnsorted=function(e){for(var t=0;t<e.length;t++){var i=e.data[t];i.render(!1)}},t.defaultTransparentSortCompare=function(e,i){return e._alphaIndex>i._alphaIndex?1:e._alphaIndex<i._alphaIndex?-1:t.backToFrontSortCompare(e,i)},t.backToFrontSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset()},t.prototype.dispatch=function(e){var t=e.getMaterial(),i=e.getMesh();t.needAlphaBlending()||i.visibility<1||i.hasVertexAlpha?this._transparentSubMeshes.push(e):t.needAlphaTesting()?this._alphaTestSubMeshes.push(e):this._opaqueSubMeshes.push(e)},t})();e.RenderingGroup=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return Object.defineProperty(e,"POINTERDOWN",{get:function(){return e._POINTERDOWN},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERUP",{get:function(){return e._POINTERUP},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERMOVE",{get:function(){return e._POINTERMOVE},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERWHEEL",{get:function(){return e._POINTERWHEEL},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERPICK",{get:function(){return e._POINTERPICK},enumerable:!0,configurable:!0}),e._POINTERDOWN=1,e._POINTERUP=2,e._POINTERMOVE=4,e._POINTERWHEEL=8,e._POINTERPICK=16,e})();e.PointerEventTypes=t;var i=(function(){function e(e,t){this.type=e,this.event=t}return e})();e.PointerInfoBase=i;var r=(function(t){function i(i,r,n,o){t.call(this,i,r),this.skipOnPointerObservable=!1,this.localPosition=new e.Vector2(n,o)}return __extends(i,t),i})(i);e.PointerInfoPre=r;var n=(function(e){function t(t,i,r){e.call(this,t,i),this.pickInfo=r}return __extends(t,e),t})(i);e.PointerInfo=n;var o=(function(){function e(){}return e.STAGE_PRECLEAR=1,e.STAGE_PREOPAQUE=2,e.STAGE_PRETRANSPARENT=3,e.STAGE_POSTTRANSPARENT=4,e})();e.RenderingGroupInfo=o;var s=(function(){function i(t){this.autoClear=!0,this.clearColor=new e.Color3(.2,.2,.3),this.ambientColor=new e.Color3(0,0,0),this.forceWireframe=!1,this.forcePointsCloud=!1,this.forceShowBoundingBoxes=!1,this.animationsEnabled=!0,this.constantlyUpdateMeshUnderPointer=!1,this.useRightHandedSystem=!1,this.hoverCursor="pointer",this.metadata=null,this.onDisposeObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onReadyObservable=new e.Observable,this.onBeforeCameraRenderObservable=new e.Observable,this.onAfterCameraRenderObservable=new e.Observable,this.onNewCameraAddedObservable=new e.Observable,this.onCameraRemovedObservable=new e.Observable,this.onNewLightAddedObservable=new e.Observable,this.onLightRemovedObservable=new e.Observable,this.onNewGeometryAddedObservable=new e.Observable,this.onGeometryRemovedObservable=new e.Observable,this.onNewMeshAddedObservable=new e.Observable,this.onMeshRemovedObservable=new e.Observable,this.onRenderingGroupObservable=new e.Observable,this.animations=[],this.onPrePointerObservable=new e.Observable,this.onPointerObservable=new e.Observable,this.cameraToUseForPointers=null,this._startingPointerPosition=new e.Vector2(0,0),this._startingPointerTime=0,this.fogEnabled=!0,this.fogMode=i.FOGMODE_NONE,this.fogColor=new e.Color3(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.shadowsEnabled=!0,this.lightsEnabled=!0,this.lights=new Array,this.cameras=new Array,this.activeCameras=new Array,this.meshes=new Array,this._geometries=new Array,this.materials=new Array,this.multiMaterials=new Array,this.texturesEnabled=!0,this.textures=new Array,this.particlesEnabled=!0,this.particleSystems=new Array,this.spritesEnabled=!0,this.spriteManagers=new Array,this.layers=new Array,this.highlightLayers=new Array,this.skeletonsEnabled=!0,this.skeletons=new Array,this.lensFlaresEnabled=!0,this.lensFlareSystems=new Array,this.collisionsEnabled=!0,this.gravity=new e.Vector3(0,(-9.807),0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this.reflectionProbes=new Array,this._actionManagers=new Array,this._meshesForIntersections=new e.SmartArray(256),this.proceduralTexturesEnabled=!0,this._proceduralTextures=new Array,this.soundTracks=new Array,this._audioEnabled=!0,this._headphone=!1,this._totalMeshesCounter=new e.PerfCounter,this._totalLightsCounter=new e.PerfCounter,this._totalMaterialsCounter=new e.PerfCounter,this._totalTexturesCounter=new e.PerfCounter,this._totalVertices=new e.PerfCounter,this._activeIndices=new e.PerfCounter,this._activeParticles=new e.PerfCounter,this._lastFrameDuration=new e.PerfCounter,this._evaluateActiveMeshesDuration=new e.PerfCounter,this._renderTargetsDuration=new e.PerfCounter,this._particlesDuration=new e.PerfCounter,this._renderDuration=new e.PerfCounter,this._spritesDuration=new e.PerfCounter,this._activeBones=new e.PerfCounter,this._renderId=0,this._executeWhenReadyTimeoutId=-1,this._intermediateRendering=!1,this._toBeDisposed=new e.SmartArray(256),this._pendingData=[],this._activeMeshes=new e.SmartArray(256),this._processedMaterials=new e.SmartArray(256),this._renderTargets=new e.SmartArray(256),this._activeParticleSystems=new e.SmartArray(256),this._activeSkeletons=new e.SmartArray(32),this._softwareSkinnedMeshes=new e.SmartArray(32),this._activeAnimatables=new Array,this._transformMatrix=e.Matrix.Zero(),this._edgesRenderers=new e.SmartArray(16),this._uniqueIdCounter=0,this._engine=t,t.scenes.push(this),this._externalData=new e.StringDictionary,this._uid=null,this._renderingManager=new e.RenderingManager(this),this.postProcessManager=new e.PostProcessManager(this),this.postProcessRenderPipelineManager=new e.PostProcessRenderPipelineManager,this._boundingBoxRenderer=new e.BoundingBoxRenderer(this),e.OutlineRenderer&&(this._outlineRenderer=new e.OutlineRenderer(this)),this.attachControl(),e.SoundTrack&&(this.mainSoundTrack=new e.SoundTrack(this,{mainTrack:!0})),e.SimplificationQueue&&(this.simplificationQueue=new e.SimplificationQueue),this.workerCollisions=!1}return Object.defineProperty(i,"FOGMODE_NONE",{get:function(){return i._FOGMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_EXP",{get:function(){return i._FOGMODE_EXP},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_EXP2",{get:function(){return i._FOGMODE_EXP2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_LINEAR",{get:function(){return i._FOGMODE_LINEAR},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"beforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"afterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"beforeCameraRender",{set:function(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"afterCameraRender",{set:function(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"unTranslatedPointer",{get:function(){return new e.Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"defaultMaterial",{get:function(){return this._defaultMaterial||(this._defaultMaterial=new e.StandardMaterial("default material",this)),this._defaultMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new e.DebugLayer(this)),this._debugLayer},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"workerCollisions",{get:function(){return this._workerCollisions},set:function(t){t=t&&!!Worker,this._workerCollisions=t,this.collisionCoordinator&&this.collisionCoordinator.destroy(),this.collisionCoordinator=t?new e.CollisionCoordinatorWorker:new e.CollisionCoordinatorLegacy,this.collisionCoordinator.init(this)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"SelectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"meshUnderPointer",{get:function(){return this._pointerOverMesh},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pointerX",{get:function(){return this._pointerX},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pointerY",{get:function(){return this._pointerY},enumerable:!0,configurable:!0}),i.prototype.getCachedMaterial=function(){return this._cachedMaterial},i.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer},i.prototype.getOutlineRenderer=function(){return this._outlineRenderer},i.prototype.getEngine=function(){return this._engine},i.prototype.getTotalVertices=function(){return this._totalVertices.current},Object.defineProperty(i.prototype,"totalVerticesPerfCounter",{get:function(){return this._totalVertices},enumerable:!0,configurable:!0}),i.prototype.getActiveIndices=function(){return this._activeIndices.current},Object.defineProperty(i.prototype,"totalActiveIndicesPerfCounter",{get:function(){return this._activeIndices},enumerable:!0,configurable:!0}),i.prototype.getActiveParticles=function(){return this._activeParticles.current},Object.defineProperty(i.prototype,"activeParticlesPerfCounter",{get:function(){return this._activeParticles},enumerable:!0,configurable:!0}),i.prototype.getActiveBones=function(){return this._activeBones.current},Object.defineProperty(i.prototype,"activeBonesPerfCounter",{get:function(){return this._activeBones},enumerable:!0,configurable:!0}),i.prototype.getLastFrameDuration=function(){return this._lastFrameDuration.current},Object.defineProperty(i.prototype,"lastFramePerfCounter",{get:function(){return this._lastFrameDuration},enumerable:!0,configurable:!0}),i.prototype.getEvaluateActiveMeshesDuration=function(){return this._evaluateActiveMeshesDuration.current},Object.defineProperty(i.prototype,"evaluateActiveMeshesDurationPerfCounter",{get:function(){return this._evaluateActiveMeshesDuration},enumerable:!0,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.getRenderTargetsDuration=function(){return this._renderTargetsDuration.current},i.prototype.getRenderDuration=function(){return this._renderDuration.current},Object.defineProperty(i.prototype,"renderDurationPerfCounter",{get:function(){return this._renderDuration},enumerable:!0,configurable:!0}),i.prototype.getParticlesDuration=function(){return this._particlesDuration.current},Object.defineProperty(i.prototype,"particlesDurationPerfCounter",{get:function(){return this._particlesDuration},enumerable:!0,configurable:!0}),i.prototype.getSpritesDuration=function(){return this._spritesDuration.current},Object.defineProperty(i.prototype,"spriteDuractionPerfCounter",{get:function(){return this._spritesDuration},enumerable:!0,configurable:!0}),i.prototype.getAnimationRatio=function(){return this._animationRatio},i.prototype.getRenderId=function(){return this._renderId},i.prototype.incrementRenderId=function(){this._renderId++},i.prototype._updatePointerPosition=function(e){var t=this._engine.getRenderingCanvasClientRect();this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY,this.cameraToUseForPointers&&(this._pointerX=this._pointerX-this.cameraToUseForPointers.viewport.x*this._engine.getRenderWidth(),this._pointerY=this._pointerY-this.cameraToUseForPointers.viewport.y*this._engine.getRenderHeight())},i.prototype.attachControl=function(i,o,s){var a=this;void 0===i&&(i=!0),void 0===o&&(o=!0),void 0===s&&(s=!0);var h=function(e){return e.isPickable&&e.actionManager&&e.actionManager.hasPointerTriggers};this._onPointerMove=function(e){if(a._updatePointerPosition(e),a.onPrePointerObservable.hasObservers()){var i="mousewheel"===e.type||"DOMMouseScroll"===e.type?t.POINTERWHEEL:t.POINTERMOVE,o=new r(i,e,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(o,i),o.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){var s=a._engine.getRenderingCanvas();a.pointerMovePredicate||(a.pointerMovePredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&(a.constantlyUpdateMeshUnderPointer||null!==e.actionManager&&void 0!==e.actionManager)});var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerMovePredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh?(a.setPointerOverSprite(null),a.setPointerOverMesh(c.pickedMesh),a._pointerOverMesh.actionManager&&a._pointerOverMesh.actionManager.hasPointerTriggers?a._pointerOverMesh.actionManager.hoverCursor?s.style.cursor=a._pointerOverMesh.actionManager.hoverCursor:s.style.cursor=a.hoverCursor:s.style.cursor=""):(a.setPointerOverMesh(null),c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite?(a.setPointerOverSprite(c.pickedSprite),a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor):(a.setPointerOverSprite(null),s.style.cursor="")),a.onPointerMove&&a.onPointerMove(e,c),a.onPointerObservable.hasObservers()){var i="mousewheel"===e.type||"DOMMouseScroll"===e.type?t.POINTERWHEEL:t.POINTERMOVE,o=new n(i,e,c);a.onPointerObservable.notifyObservers(o,i)}}},this._onPointerDown=function(i){if(a._updatePointerPosition(i),a.onPrePointerObservable.hasObservers()){var o=t.POINTERDOWN,s=new r(o,i,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(s,o),s.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){a._startingPointerPosition.x=a._pointerX,a._startingPointerPosition.y=a._pointerY,a._startingPointerTime=(new Date).getTime(),a.pointerDownPredicate||(a.pointerDownPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()}),a._pickedDownMesh=null;var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerDownPredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh&&c.pickedMesh.actionManager){if(a._pickedDownMesh=c.pickedMesh,c.pickedMesh.actionManager.hasPickTriggers){switch(i.button){case 0:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i));break;case 1:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i));break;case 2:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i))}c.pickedMesh.actionManager&&c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i))}if(c.pickedMesh.actionManager&&c.pickedMesh.actionManager.hasSpecificTrigger(e.ActionManager.OnLongPressTrigger)){var l=a;window.setTimeout((function(){var t=l.pick(l._unTranslatedPointerX,l._unTranslatedPointerY,(function(t){return t.isPickable&&t.isVisible&&t.isReady()&&t.actionManager&&t.actionManager.hasSpecificTrigger(e.ActionManager.OnLongPressTrigger)}),!1,l.cameraToUseForPointers);t.hit&&t.pickedMesh&&t.pickedMesh.actionManager&&0!==l._startingPointerTime&&(new Date).getTime()-l._startingPointerTime>e.ActionManager.LongPressDelay&&Math.abs(l._startingPointerPosition.x-l._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(l._startingPointerPosition.y-l._pointerY)<e.ActionManager.DragMovementThreshold&&(l._startingPointerTime=0,t.pickedMesh.actionManager.processTrigger(e.ActionManager.OnLongPressTrigger,e.ActionEvent.CreateNew(t.pickedMesh,i)))}),e.ActionManager.LongPressDelay)}}if(a.onPointerDown&&a.onPointerDown(i,c),a.onPointerObservable.hasObservers()){var o=t.POINTERDOWN,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}if(a._pickedDownSprite=null,a.spriteManagers.length>0&&(c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite&&c.pickedSprite.actionManager)){switch(a._pickedDownSprite=c.pickedSprite,i.button){case 0:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i));break;case 1:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i));break;case 2:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))}c.pickedSprite.actionManager&&c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))}}},this._onPointerUp=function(i){if(a._updatePointerPosition(i),a.onPrePointerObservable.hasObservers()){var o=t.POINTERUP,s=new r(o,i,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(s,o),s.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){a.pointerUpPredicate||(a.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()});var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerUpPredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh){if(null!=a._pickedDownMesh&&c.pickedMesh==a._pickedDownMesh&&(a.onPointerPick&&a.onPointerPick(i,c),a.onPointerObservable.hasObservers())){var o=t.POINTERPICK,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}c.pickedMesh.actionManager&&(c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i)),c.pickedMesh.actionManager&&Math.abs(a._startingPointerPosition.x-a._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(a._startingPointerPosition.y-a._pointerY)<e.ActionManager.DragMovementThreshold&&c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i)))}if(a._pickedDownMesh&&a._pickedDownMesh.actionManager&&a._pickedDownMesh!==c.pickedMesh&&a._pickedDownMesh.actionManager.processTrigger(e.ActionManager.OnPickOutTrigger,e.ActionEvent.CreateNew(a._pickedDownMesh,i)),a.onPointerUp&&a.onPointerUp(i,c),a.onPointerObservable.hasObservers()){var o=t.POINTERUP,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}a._startingPointerTime=0,a.spriteManagers.length>0&&(c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite&&c.pickedSprite.actionManager&&(c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i)),c.pickedSprite.actionManager&&Math.abs(a._startingPointerPosition.x-a._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(a._startingPointerPosition.y-a._pointerY)<e.ActionManager.DragMovementThreshold&&c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==c.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(e.ActionManager.OnPickOutTrigger,e.ActionEvent.CreateNewFromSprite(a._pickedDownSprite,a,i)))}},this._onKeyDown=function(t){a.actionManager&&a.actionManager.processTrigger(e.ActionManager.OnKeyDownTrigger,e.ActionEvent.CreateNewFromScene(a,t))},this._onKeyUp=function(t){a.actionManager&&a.actionManager.processTrigger(e.ActionManager.OnKeyUpTrigger,e.ActionEvent.CreateNewFromScene(a,t))};var c=e.Tools.GetPointerPrefix(),l=this._engine.getRenderingCanvas();s&&(l.addEventListener(c+"move",this._onPointerMove,!1),l.addEventListener("mousewheel",this._onPointerMove,!1),l.addEventListener("DOMMouseScroll",this._onPointerMove,!1)),o&&l.addEventListener(c+"down",this._onPointerDown,!1),i&&l.addEventListener(c+"up",this._onPointerUp,!1),l.tabIndex=1,l.addEventListener("keydown",this._onKeyDown,!1),l.addEventListener("keyup",this._onKeyUp,!1)},i.prototype.detachControl=function(){var t=e.Tools.GetPointerPrefix(),i=this._engine.getRenderingCanvas();i.removeEventListener(t+"move",this._onPointerMove),i.removeEventListener(t+"down",this._onPointerDown),i.removeEventListener(t+"up",this._onPointerUp),i.removeEventListener("mousewheel",this._onPointerMove),i.removeEventListener("DOMMouseScroll",this._onPointerMove),i.removeEventListener("keydown",this._onKeyDown),i.removeEventListener("keyup",this._onKeyUp)},i.prototype.isReady=function(){if(this._pendingData.length>0)return!1;var t;for(t=0;t<this._geometries.length;t++){var i=this._geometries[t];if(i.delayLoadState===e.Engine.DELAYLOADSTATE_LOADING)return!1}for(t=0;t<this.meshes.length;t++){var r=this.meshes[t];if(!r.isReady())return!1;var n=r.material;if(n&&!n.isReady(r))return!1}return!0},i.prototype.resetCachedMaterial=function(){this._cachedMaterial=null},i.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},i.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},i.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},i.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},i.prototype._addPendingData=function(e){this._pendingData.push(e)},i.prototype._removePendingData=function(e){var t=this._pendingData.indexOf(e);t!==-1&&this._pendingData.splice(t,1)},i.prototype.getWaitingItemsCount=function(){return this._pendingData.length},i.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),this._executeWhenReadyTimeoutId===-1&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},i.prototype._checkIsReady=function(){var e=this;return this.isReady()?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):void(this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150))},i.prototype.beginAnimation=function(t,i,r,n,o,s,a){if(void 0===o&&(o=1),this.stopAnimation(t),a||(a=new e.Animatable(this,t,i,r,n,o,s)),t.animations&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var h=t.getAnimatables(),c=0;c<h.length;c++)this.beginAnimation(h[c],i,r,n,o,s,a);return a.reset(),a},i.prototype.beginDirectAnimation=function(t,i,r,n,o,s,a){void 0===s&&(s=1);var h=new e.Animatable(this,t,r,n,o,s,a,i);return h},i.prototype.getAnimatableByTarget=function(e){for(var t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},Object.defineProperty(i.prototype,"Animatables",{get:function(){return this._activeAnimatables},enumerable:!0,configurable:!0}),i.prototype.stopAnimation=function(e,t){var i=this.getAnimatableByTarget(e);i&&i.stop(t)},i.prototype._animate=function(){if(this.animationsEnabled&&0!==this._activeAnimatables.length){if(!this._animationStartDate){if(this._pendingData.length>0)return;this._animationStartDate=e.Tools.Now}for(var t=e.Tools.Now,i=t-this._animationStartDate,r=0;r<this._activeAnimatables.length;r++)this._activeAnimatables[r]._animate(i)}},i.prototype.getViewMatrix=function(){return this._viewMatrix},i.prototype.getProjectionMatrix=function(){return this._projectionMatrix},i.prototype.getTransformMatrix=function(){return this._transformMatrix},i.prototype.setTransformMatrix=function(t,i){this._viewMatrix=t,this._projectionMatrix=i,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix)},i.prototype.addMesh=function(e){e.uniqueId=this._uniqueIdCounter++;this.meshes.push(e);this.collisionCoordinator.onMeshAdded(e),this.onNewMeshAddedObservable.notifyObservers(e)},i.prototype.removeMesh=function(e){var t=this.meshes.indexOf(e);return t!==-1&&this.meshes.splice(t,1),this.collisionCoordinator.onMeshRemoved(e),this.onMeshRemovedObservable.notifyObservers(e),t},i.prototype.removeSkeleton=function(e){var t=this.skeletons.indexOf(e);return t!==-1&&this.skeletons.splice(t,1),t},i.prototype.removeLight=function(e){var t=this.lights.indexOf(e);return t!==-1&&this.lights.splice(t,1),this.onLightRemovedObservable.notifyObservers(e),t},i.prototype.removeCamera=function(e){var t=this.cameras.indexOf(e);t!==-1&&this.cameras.splice(t,1);var i=this.activeCameras.indexOf(e);return i!==-1&&this.activeCameras.splice(i,1),this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},i.prototype.addLight=function(e){e.uniqueId=this._uniqueIdCounter++;this.lights.push(e);this.onNewLightAddedObservable.notifyObservers(e)},i.prototype.addCamera=function(e){e.uniqueId=this._uniqueIdCounter++;this.cameras.push(e);this.onNewCameraAddedObservable.notifyObservers(e)},i.prototype.switchActiveCamera=function(e,t){void 0===t&&(t=!0);var i=this._engine.getRenderingCanvas();this.activeCamera.detachControl(i),this.activeCamera=e,t&&e.attachControl(i)},i.prototype.setActiveCameraByID=function(e){var t=this.getCameraByID(e);return t?(this.activeCamera=t,t):null},i.prototype.setActiveCameraByName=function(e){var t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null},i.prototype.getMaterialByID=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].id===e)return this.materials[t];return null},i.prototype.getMaterialByName=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].name===e)return this.materials[t];return null},i.prototype.getLensFlareSystemByName=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},i.prototype.getLensFlareSystemByID=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},i.prototype.getCameraByID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null},i.prototype.getCameraByUniqueID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null},i.prototype.getCameraByName=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null},i.prototype.getBoneByID=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].id===e)return i.bones[r];return null},i.prototype.getBoneByName=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].name===e)return i.bones[r];return null},i.prototype.getLightByName=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null},i.prototype.getLightByID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null},i.prototype.getLightByUniqueID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];
return null},i.prototype.getParticleSystemByID=function(e){for(var t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null},i.prototype.getGeometryByID=function(e){for(var t=0;t<this._geometries.length;t++)if(this._geometries[t].id===e)return this._geometries[t];return null},i.prototype.pushGeometry=function(e,t){return!(!t&&this.getGeometryByID(e.id))&&(this._geometries.push(e),this.collisionCoordinator.onGeometryAdded(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)},i.prototype.removeGeometry=function(e){var t=this._geometries.indexOf(e);return t>-1&&(this._geometries.splice(t,1),this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},i.prototype.getGeometries=function(){return this._geometries},i.prototype.getMeshByID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null},i.prototype.getMeshesByID=function(e){return this.meshes.filter((function(t){return t.id===e}))},i.prototype.getMeshByUniqueID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null},i.prototype.getLastMeshByID=function(e){for(var t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},i.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},i.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);if(r)return r;var n=this.getBoneByID(e);return n},i.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);if(r)return r;var n=this.getBoneByName(e);return n},i.prototype.getMeshByName=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null},i.prototype.getSoundByName=function(t){var i;if(e.AudioEngine){for(i=0;i<this.mainSoundTrack.soundCollection.length;i++)if(this.mainSoundTrack.soundCollection[i].name===t)return this.mainSoundTrack.soundCollection[i];for(var r=0;r<this.soundTracks.length;r++)for(i=0;i<this.soundTracks[r].soundCollection.length;i++)if(this.soundTracks[r].soundCollection[i].name===t)return this.soundTracks[r].soundCollection[i]}return null},i.prototype.getLastSkeletonByID=function(e){for(var t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},i.prototype.getSkeletonById=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null},i.prototype.getSkeletonByName=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},Object.defineProperty(i.prototype,"uid",{get:function(){return this._uid||(this._uid=e.Tools.RandomId()),this._uid},enumerable:!0,configurable:!0}),i.prototype.addExternalData=function(e,t){return this._externalData.add(e,t)},i.prototype.getExternalData=function(e){return this._externalData.get(e)},i.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData.getOrAddWithFactory(e,t)},i.prototype.removeExternalData=function(e){return this._externalData.remove(e)},i.prototype._evaluateSubMesh=function(e,t){if(t.alwaysSelectAsActiveMesh||1===t.subMeshes.length||e.isInFrustum(this._frustumPlanes)){var i=e.getMaterial();t.showSubMeshesBoundingBox&&this._boundingBoxRenderer.renderList.push(e.getBoundingInfo().boundingBox),i&&(i.getRenderTargetTextures&&this._processedMaterials.indexOf(i)===-1&&(this._processedMaterials.push(i),this._renderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._activeIndices.addCount(e.indexCount,!1),this._renderingManager.dispatch(e))}},i.prototype._isInIntermediateRendering=function(){return this._intermediateRendering},i.prototype._evaluateActiveMeshes=function(){this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._boundingBoxRenderer.reset(),this._edgesRenderers.reset();var t,i;if(this._selectionOctree){var r=this._selectionOctree.select(this._frustumPlanes);t=r.data,i=r.length}else i=this.meshes.length,t=this.meshes;for(var n=0;n<i;n++){var o=t[n];if(!o.isBlocked&&(this._totalVertices.addCount(o.getTotalVertices(),!1),o.isReady()&&o.isEnabled())){o.computeWorldMatrix(),o.actionManager&&o.actionManager.hasSpecificTriggers([e.ActionManager.OnIntersectionEnterTrigger,e.ActionManager.OnIntersectionExitTrigger])&&this._meshesForIntersections.pushNoDuplicate(o);var s=o.getLOD(this.activeCamera);s&&(o._preActivate(),(o.alwaysSelectAsActiveMesh||o.isVisible&&o.visibility>0&&0!==(o.layerMask&this.activeCamera.layerMask)&&o.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(o),this.activeCamera._activeMeshes.push(o),o._activate(this._renderId),this._activeMesh(o,s)))}}this._particlesDuration.beginMonitoring();e.Tools.Now;if(this.particlesEnabled){e.Tools.StartPerformanceCounter("Particles",this.particleSystems.length>0);for(var a=0;a<this.particleSystems.length;a++){var h=this.particleSystems[a];h.isStarted()&&(!h.emitter.position||h.emitter&&h.emitter.isEnabled())&&(this._activeParticleSystems.push(h),h.animate())}e.Tools.EndPerformanceCounter("Particles",this.particleSystems.length>0)}this._particlesDuration.endMonitoring(!1)},i.prototype._activeMesh=function(e,t){if(t.skeleton&&this.skeletonsEnabled&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&t.skeleton.prepare(),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t)),(e.showBoundingBox||this.forceShowBoundingBoxes)&&this._boundingBoxRenderer.renderList.push(e.getBoundingInfo().boundingBox),e._edgesRenderer&&this._edgesRenderers.push(e._edgesRenderer),t&&t.subMeshes){var i,r;if(t._submeshesOctree&&t.useOctreeForRenderingSelection){var n=t._submeshesOctree.select(this._frustumPlanes);i=n.length,r=n.data}else r=t.subMeshes,i=r.length;for(var o=0;o<i;o++){var s=r[o];this._evaluateSubMesh(s,t)}}},i.prototype.updateTransformMatrix=function(e){this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))},i.prototype._renderForCamera=function(t){var i=this._engine;e.Tools.Now;if(this.activeCamera=t,!this.activeCamera)throw new Error("Active camera not set");e.Tools.StartPerformanceCounter("Rendering camera "+this.activeCamera.name),i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshesDuration.beginMonitoring(),e.Tools.StartPerformanceCounter("Active meshes evaluation"),this._evaluateActiveMeshes(),this._evaluateActiveMeshesDuration.endMonitoring(!1),e.Tools.EndPerformanceCounter("Active meshes evaluation");for(var r=0;r<this._softwareSkinnedMeshes.length;r++){var n=this._softwareSkinnedMeshes.data[r];n.applySkeleton(n.skeleton)}this._renderTargetsDuration.beginMonitoring();var o=!1;e.Tools.Now;if(this.renderTargetsEnabled&&this._renderTargets.length>0){this._intermediateRendering=!0,e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s<this._renderTargets.length;s++){var a=this._renderTargets.data[s];if(a._shouldRender()){this._renderId++;var h=a.activeCamera&&a.activeCamera!==this.activeCamera;a.render(h,this.dumpNextRenderTargets)}}e.Tools.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._intermediateRendering=!1,this._renderId++,o=!0}var c=this._engine.getStencilBuffer(),l=!1;if(this.renderTargetsEnabled&&this.highlightLayers&&this.highlightLayers.length>0){this._intermediateRendering=!0;for(var u=0;u<this.highlightLayers.length;u++){var f=this.highlightLayers[u];if(f.shouldRender()&&(!f.camera||f.camera.cameraRigMode===e.Camera.RIG_MODE_NONE&&t===f.camera||f.camera.cameraRigMode!==e.Camera.RIG_MODE_NONE&&f.camera._rigCameras.indexOf(t)>-1)){l=!0;var a=f._mainTexture;a._shouldRender()&&(this._renderId++,a.render(!1,!1),o=!0)}}this._intermediateRendering=!1,this._renderId++}o&&i.restoreDefaultFramebuffer(),this._renderTargetsDuration.endMonitoring(!1),this.postProcessManager._prepareFrame(),this._renderDuration.beginMonitoring();var d,p;if(this.layers.length){for(i.setDepthBuffer(!1),d=0;d<this.layers.length;d++)p=this.layers[d],p.isBackground&&p.render();i.setDepthBuffer(!0)}e.Tools.StartPerformanceCounter("Main render"),l&&this._engine.setStencilBuffer(!0),this._renderingManager.render(null,null,!0,!0),l&&this._engine.setStencilBuffer(c),e.Tools.EndPerformanceCounter("Main render"),this._boundingBoxRenderer.render();for(var m=0;m<this._edgesRenderers.length;m++)this._edgesRenderers.data[m].render();if(this.lensFlaresEnabled){e.Tools.StartPerformanceCounter("Lens flares",this.lensFlareSystems.length>0);for(var g=0;g<this.lensFlareSystems.length;g++){var _=this.lensFlareSystems[g];0!==(t.layerMask&_.layerMask)&&_.render()}e.Tools.EndPerformanceCounter("Lens flares",this.lensFlareSystems.length>0)}if(this.layers.length){for(i.setDepthBuffer(!1),d=0;d<this.layers.length;d++)p=this.layers[d],p.isBackground||p.render();i.setDepthBuffer(!0)}if(l){i.setDepthBuffer(!1);for(var u=0;u<this.highlightLayers.length;u++)this.highlightLayers[u].shouldRender()&&this.highlightLayers[u].render();i.setDepthBuffer(!0)}this._renderDuration.endMonitoring(!1),this.postProcessManager._finalizeFrame(t.isIntermediate),this.activeCamera._updateFromScene(),this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera),e.Tools.EndPerformanceCounter("Rendering camera "+this.activeCamera.name)},i.prototype._processSubCameras=function(t){if(t.cameraRigMode===e.Camera.RIG_MODE_NONE)return void this._renderForCamera(t);for(var i=0;i<t._rigCameras.length;i++)this._renderForCamera(t._rigCameras[i]);this.activeCamera=t,this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix()),this.activeCamera._updateFromScene()},i.prototype._checkIntersections=function(){for(var t=0;t<this._meshesForIntersections.length;t++)for(var i=this._meshesForIntersections.data[t],r=0;r<i.actionManager.actions.length;r++){var n=i.actionManager.actions[r];if(n.trigger===e.ActionManager.OnIntersectionEnterTrigger||n.trigger===e.ActionManager.OnIntersectionExitTrigger){var o=n.getTriggerParameter(),s=o instanceof e.AbstractMesh?o:o.mesh,a=s.intersectsMesh(i,o.usePreciseIntersection),h=i._intersectionsInProgress.indexOf(s);a&&h===-1?n.trigger===e.ActionManager.OnIntersectionEnterTrigger?(n._executeCurrent(e.ActionEvent.CreateNew(i,null,s)),i._intersectionsInProgress.push(s)):n.trigger===e.ActionManager.OnIntersectionExitTrigger&&i._intersectionsInProgress.push(s):!a&&h>-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,null,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger)&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(h,1))}}},i.prototype.render=function(){this._lastFrameDuration.beginMonitoring(),this._particlesDuration.fetchNewFrame(),this._spritesDuration.fetchNewFrame(),this._activeParticles.fetchNewFrame(),this._renderDuration.fetchNewFrame(),this._renderTargetsDuration.fetchNewFrame(),this._evaluateActiveMeshesDuration.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this.getEngine().drawCallsPerfCounter.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),e.Tools.StartPerformanceCounter("Scene rendering"),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger,null),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext();var t=Math.max(i.MinDeltaTime,Math.min(this._engine.getDeltaTime(),i.MaxDeltaTime));this._animationRatio=.06*t,this._animate(),this._physicsEngine&&(e.Tools.StartPerformanceCounter("Physics"),this._physicsEngine._step(t/1e3),e.Tools.EndPerformanceCounter("Physics")),this.onBeforeRenderObservable.notifyObservers(this),this._renderTargetsDuration.beginMonitoring();var r=(e.Tools.Now,this.getEngine()),n=this.activeCamera;if(this.renderTargetsEnabled){e.Tools.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0);for(var o=0;o<this.customRenderTargets.length;o++){var s=this.customRenderTargets[o];if(s._shouldRender()){if(this._renderId++,this.activeCamera=s.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");r.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),s.render(n!==this.activeCamera,this.dumpNextRenderTargets)}}e.Tools.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._renderId++}if(this.customRenderTargets.length>0&&r.restoreDefaultFramebuffer(),this._renderTargetsDuration.endMonitoring(),this.activeCamera=n,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this._proceduralTextures.length>0);for(var a=0;a<this._proceduralTextures.length;a++){var h=this._proceduralTextures[a];h._shouldRender()&&h.render()}e.Tools.EndPerformanceCounter("Procedural textures",this._proceduralTextures.length>0)}if(this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,!0,!0),this.shadowsEnabled)for(var c=0;c<this.lights.length;c++){var l=this.lights[c],u=l.getShadowGenerator();l.isEnabled()&&u&&u.getShadowMap().getScene().textures.indexOf(u.getShadowMap())!==-1&&this._renderTargets.push(u.getShadowMap())}if(this._depthRenderer&&this._renderTargets.push(this._depthRenderer.getDepthMap()),this.postProcessRenderPipelineManager.update(),this.activeCameras.length>0)for(var f=0;f<this.activeCameras.length;f++)f>0&&this._engine.clear(0,!1,!0,!0),this._processSubCameras(this.activeCameras[f]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var d=0;d<this._toBeDisposed.length;d++)this._toBeDisposed.data[d].dispose(),this._toBeDisposed[d]=null;this._toBeDisposed.reset(),this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),e.Tools.EndPerformanceCounter("Scene rendering"),this._lastFrameDuration.endMonitoring(),this._totalMeshesCounter.addCount(this.meshes.length,!0),this._totalLightsCounter.addCount(this.lights.length,!0),this._totalMaterialsCounter.addCount(this.materials.length,!0),this._totalTexturesCounter.addCount(this.textures.length,!0),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0)},i.prototype._updateAudioParameters=function(){if(this.audioEnabled&&(0!==this.mainSoundTrack.soundCollection.length||1!==this.soundTracks.length)){var t,i=e.Engine.audioEngine;if(t=this.activeCameras.length>0?this.activeCameras[0]:this.activeCamera,t&&i.canUseWebAudio){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,(-1)),r);n.normalize(),i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o<this.mainSoundTrack.soundCollection.length;o++){var s=this.mainSoundTrack.soundCollection[o];s.useCustomAttenuation&&s.updateDistanceFromListener()}for(o=0;o<this.soundTracks.length;o++)for(var a=0;a<this.soundTracks[o].soundCollection.length;a++)s=this.soundTracks[o].soundCollection[a],s.useCustomAttenuation&&s.updateDistanceFromListener()}}},Object.defineProperty(i.prototype,"audioEnabled",{get:function(){return this._audioEnabled},set:function(t){this._audioEnabled=t,e.AudioEngine&&(this._audioEnabled?this._enableAudio():this._disableAudio())},enumerable:!0,configurable:!0}),i.prototype._disableAudio=function(){var e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)this.mainSoundTrack.soundCollection[e].pause();for(e=0;e<this.soundTracks.length;e++)for(var t=0;t<this.soundTracks[e].soundCollection.length;t++)this.soundTracks[e].soundCollection[t].pause()},i.prototype._enableAudio=function(){var e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)this.mainSoundTrack.soundCollection[e].isPaused&&this.mainSoundTrack.soundCollection[e].play();for(e=0;e<this.soundTracks.length;e++)for(var t=0;t<this.soundTracks[e].soundCollection.length;t++)this.soundTracks[e].soundCollection[t].isPaused&&this.soundTracks[e].soundCollection[t].play()},Object.defineProperty(i.prototype,"headphone",{get:function(){return this._headphone},set:function(t){this._headphone=t,e.AudioEngine&&(this._headphone?this._switchAudioModeForHeadphones():this._switchAudioModeForNormalSpeakers())},enumerable:!0,configurable:!0}),i.prototype._switchAudioModeForHeadphones=function(){this.mainSoundTrack.switchPanningModelToHRTF();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].switchPanningModelToHRTF()},i.prototype._switchAudioModeForNormalSpeakers=function(){this.mainSoundTrack.switchPanningModelToEqualPower();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].switchPanningModelToEqualPower()},i.prototype.enableDepthRenderer=function(){return this._depthRenderer?this._depthRenderer:(this._depthRenderer=new e.DepthRenderer(this),this._depthRenderer)},i.prototype.disableDepthRenderer=function(){this._depthRenderer&&(this._depthRenderer.dispose(),this._depthRenderer=null)},i.prototype.freezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].freeze()},i.prototype.unfreezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].unfreeze()},i.prototype.dispose=function(){this.beforeRender=null,this.afterRender=null,this.skeletons=[],this._boundingBoxRenderer.dispose(),this._depthRenderer&&this._depthRenderer.dispose(),this._debugLayer&&this._debugLayer.hide(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.detachControl(),e.AudioEngine&&this.disposeSounds();var t,i=this._engine.getRenderingCanvas();for(t=0;t<this.cameras.length;t++)this.cameras[t].detachControl(i);for(;this.lights.length;)this.lights[0].dispose();for(;this.meshes.length;)this.meshes[0].dispose(!0);for(;this.cameras.length;)this.cameras[0].dispose();for(;this.materials.length;)this.materials[0].dispose();for(;this.particleSystems.length;)this.particleSystems[0].dispose();for(;this.spriteManagers.length;)this.spriteManagers[0].dispose();for(;this.layers.length;)this.layers[0].dispose();for(;this.highlightLayers.length;)this.highlightLayers[0].dispose();for(;this.textures.length;)this.textures[0].dispose();this.postProcessManager.dispose(),this._physicsEngine&&this.disablePhysicsEngine(),t=this._engine.scenes.indexOf(this),t>-1&&this._engine.scenes.splice(t,1),this._engine.wipeCaches()},i.prototype.disposeSounds=function(){this.mainSoundTrack.dispose();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].dispose()},i.prototype.getWorldExtends=function(){for(var t=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE)),r=0;r<this.meshes.length;r++){var n=this.meshes[r];n.computeWorldMatrix(!0);var o=n.getBoundingInfo().boundingBox.minimumWorld,s=n.getBoundingInfo().boundingBox.maximumWorld;e.Tools.CheckExtends(o,t,i),e.Tools.CheckExtends(s,t,i)}return{min:t,max:i}},i.prototype.createOrUpdateSelectionOctree=function(t,i){void 0===t&&(t=64),void 0===i&&(i=2),this._selectionOctree||(this._selectionOctree=new e.Octree(e.Octree.CreationFuncForMeshes,t,i));var r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},i.prototype.createPickingRay=function(t,i,r,n,o){void 0===o&&(o=!1);var s=this._engine;if(!n){if(!this.activeCamera)throw new Error("Active camera not set");n=this.activeCamera}var a=n.viewport,h=a.toGlobal(s.getRenderWidth(),s.getRenderHeight());return t=t/this._engine.getHardwareScalingLevel()-h.x,i=i/this._engine.getHardwareScalingLevel()-(this._engine.getRenderHeight()-h.y-h.height),e.Ray.CreateNew(t,i,h.width,h.height,r?r:e.Matrix.Identity(),o?e.Matrix.Identity():n.getViewMatrix(),n.getProjectionMatrix())},i.prototype.createPickingRayInCameraSpace=function(t,i,r){var n=this._engine;if(!r){if(!this.activeCamera)throw new Error("Active camera not set");r=this.activeCamera}var o=r.viewport,s=o.toGlobal(n.getRenderWidth(),n.getRenderHeight()),a=e.Matrix.Identity();return t=t/this._engine.getHardwareScalingLevel()-s.x,i=i/this._engine.getHardwareScalingLevel()-(this._engine.getRenderHeight()-s.y-s.height),e.Ray.CreateNew(t,i,s.width,s.height,a,a,r.getProjectionMatrix())},i.prototype._internalPick=function(t,i,r){for(var n=null,o=0;o<this.meshes.length;o++){var s=this.meshes[o];if(i){if(!i(s))continue}else if(!s.isEnabled()||!s.isVisible||!s.isPickable)continue;var a=s.getWorldMatrix(),h=t(a),c=s.intersects(h,r);if(c&&c.hit&&(r||null==n||!(c.distance>=n.distance))&&(n=c,r))break}return n||new e.PickingInfo},i.prototype._internalMultiPick=function(e,t){for(var i=new Array,r=0;r<this.meshes.length;r++){var n=this.meshes[r];if(t){if(!t(n))continue}else if(!n.isEnabled()||!n.isVisible||!n.isPickable)continue;var o=n.getWorldMatrix(),s=e(o),a=n.intersects(s,!1);a&&a.hit&&i.push(a)}return i},i.prototype._internalPickSprites=function(t,i,r,n){var o=null;if(n=n||this.activeCamera,this.spriteManagers.length>0)for(var s=0;s<this.spriteManagers.length;s++){var a=this.spriteManagers[s];if(a.isPickable){var h=a.intersects(t,n,i,r);if(h&&h.hit&&(r||null==o||!(h.distance>=o.distance))&&(o=h,r))break}}return o||new e.PickingInfo},i.prototype.pick=function(e,t,i,r,n){var o=this;return this._internalPick((function(i){return o.createPickingRay(e,t,i,n)}),i,r)},i.prototype.pickSprite=function(e,t,i,r,n){return this._internalPickSprites(this.createPickingRayInCameraSpace(e,t,n),i,r,n)},i.prototype.pickWithRay=function(t,i,r){var n=this;return this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),e.Ray.Transform(t,n._pickWithRayInverseMatrix)}),i,r)},i.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r)}),i)},i.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),e.Ray.Transform(t,r._pickWithRayInverseMatrix)}),i)},i.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},i.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},i.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},i.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},i.prototype.getPhysicsEngine=function(){return this._physicsEngine},i.prototype.enablePhysics=function(t,i){if(this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(r){return e.Tools.Error(r.message),!1}},i.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=void 0)},i.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},i.prototype.setGravity=function(t){e.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'"),this._physicsEngine&&this._physicsEngine.setGravity(t)},i.prototype.createCompoundImpostor=function(t,i){e.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child"),t.parts&&(i=t,t=t.parts);var r=t[0].mesh;r.physicsImpostor=new e.PhysicsImpostor(r,t[0].impostor,i,this);for(var n=1;n<t.length;n++){var o=t[n].mesh;o.parent!==r&&(o.position=o.position.subtract(r.position),o.parent=r),o.physicsImpostor=new e.PhysicsImpostor(o,t[n].impostor,i,this)}r.physicsImpostor.forceUpdate()},i.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor.dispose(),t.physicsImpostor=null},i.prototype.createDefaultCameraOrLight=function(){if(0===this.lights.length&&new e.HemisphericLight("default light",e.Vector3.Up(),this),!this.activeCamera){var t=new e.FreeCamera("default camera",e.Vector3.Zero(),this),i=this.getWorldExtends(),r=i.min.add(i.max.subtract(i.min).scale(.5));t.position=new e.Vector3(r.x,r.y,i.min.z-(i.max.z-i.min.z)),t.setTarget(r),this.activeCamera=t}},i.prototype._getByTags=function(t,i,r){if(void 0===i)return t;var n=[];r=r||function(e){};for(var o in t){var s=t[o];e.Tags.MatchesQuery(s,i)&&(n.push(s),r(s))}return n},i.prototype.getMeshesByTags=function(e,t){return this._getByTags(this.meshes,e,t)},i.prototype.getCamerasByTags=function(e,t){return this._getByTags(this.cameras,e,t)},i.prototype.getLightsByTags=function(e,t){return this._getByTags(this.lights,e,t)},i.prototype.getMaterialByTags=function(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t)},i._FOGMODE_NONE=0,i._FOGMODE_EXP=1,i._FOGMODE_EXP2=2,i._FOGMODE_LINEAR=3,i.MinDeltaTime=1,i.MaxDeltaTime=1e3,i})();e.Scene=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s){t instanceof e.Mesh?this._engine=t.getScene().getEngine():this._engine=t,this._updatable=r,this._data=i,this._strideSize=n,o||this.create(),this._instanced=s}return t.prototype.createVertexBuffer=function(t,i,r,n){return new e.VertexBuffer(this._engine,this,t,this._updatable,(!0),n?n:this._strideSize,this._instanced,i,r)},t.prototype.isUpdatable=function(){return this._updatable},t.prototype.getData=function(){return this._data},t.prototype.getBuffer=function(){return this._buffer},t.prototype.getStrideSize=function(){return this._strideSize},t.prototype.getIsInstanced=function(){return this._instanced},t.prototype.create=function(e){!e&&this._buffer||(e=e||this._data,this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))},t.prototype.update=function(e){this.create(e)},t.prototype.updateDirectly=function(e,t,i){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,t,i?i*this.getStrideSize():void 0),this._data=null)},t.prototype.dispose=function(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)},t})();e.Buffer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(i,r,n,o,s,a,h,c,l){if(!a)switch(n){case t.PositionKind:a=3;break;case t.NormalKind:a=3;break;case t.UVKind:case t.UV2Kind:case t.UV3Kind:case t.UV4Kind:case t.UV5Kind:case t.UV6Kind:a=2;break;case t.ColorKind:a=4;break;case t.MatricesIndicesKind:case t.MatricesIndicesExtraKind:a=4;break;case t.MatricesWeightsKind:case t.MatricesWeightsExtraKind:a=4}r instanceof e.Buffer?(a||(a=r.getStrideSize()),this._buffer=r,this._ownsBuffer=!1):(this._buffer=new e.Buffer(i,r,o,a,s,h),this._ownsBuffer=!0),this._stride=a,this._offset=c?c:0,this._size=l?l:a,this._kind=n}return t.prototype.getKind=function(){return this._kind},t.prototype.isUpdatable=function(){return this._buffer.isUpdatable()},t.prototype.getData=function(){return this._buffer.getData()},t.prototype.getBuffer=function(){return this._buffer.getBuffer()},t.prototype.getStrideSize=function(){return this._stride},t.prototype.getOffset=function(){return this._offset},t.prototype.getSize=function(){return this._size},t.prototype.getIsInstanced=function(){return this._buffer.getIsInstanced()},t.prototype.create=function(e){return this._buffer.create(e)},t.prototype.update=function(e){return this._buffer.update(e)},t.prototype.updateDirectly=function(e,t){return this._buffer.updateDirectly(e,t)},t.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose()},Object.defineProperty(t,"PositionKind",{get:function(){return t._PositionKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"NormalKind",{get:function(){return t._NormalKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UVKind",{get:function(){return t._UVKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV2Kind",{get:function(){return t._UV2Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV3Kind",{get:function(){return t._UV3Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV4Kind",{get:function(){return t._UV4Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV5Kind",{get:function(){return t._UV5Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV6Kind",{get:function(){return t._UV6Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ColorKind",{get:function(){return t._ColorKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesIndicesKind",{get:function(){return t._MatricesIndicesKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesWeightsKind",{get:function(){return t._MatricesWeightsKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesIndicesExtraKind",{get:function(){return t._MatricesIndicesExtraKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesWeightsExtraKind",{get:function(){return t._MatricesWeightsExtraKind},enumerable:!0,configurable:!0}),t._PositionKind="position",t._NormalKind="normal",t._UVKind="uv",t._UV2Kind="uv2",t._UV3Kind="uv3",t._UV4Kind="uv4",t._UV5Kind="uv5",t._UV6Kind="uv6",t._ColorKind="color",t._MatricesIndicesKind="matricesIndices",t._MatricesWeightsKind="matricesWeights",t._MatricesIndicesExtraKind="matricesIndicesExtra",t._MatricesWeightsExtraKind="matricesWeightsExtra",t})();e.VertexBuffer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i){t.call(this,e,i.getScene()),i.instances.push(this),this._sourceMesh=i,this.position.copyFrom(i.position),this.rotation.copyFrom(i.rotation),this.scaling.copyFrom(i.scaling),i.rotationQuaternion&&(this.rotationQuaternion=i.rotationQuaternion.clone()),this.infiniteDistance=i.infiniteDistance,this.setPivotMatrix(i.getPivotMatrix()),
this.refreshBoundingInfo(),this._syncSubMeshes()}return __extends(i,t),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._sourceMesh.receiveShadows},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._sourceMesh.material},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._sourceMesh.visibility},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._sourceMesh.skeleton},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"renderingGroupId",{get:function(){return this._sourceMesh.renderingGroupId},enumerable:!0,configurable:!0}),i.prototype.getTotalVertices=function(){return this._sourceMesh.getTotalVertices()},Object.defineProperty(i.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!0,configurable:!0}),i.prototype.getVerticesData=function(e,t){return this._sourceMesh.getVerticesData(e,t)},i.prototype.isVerticesDataPresent=function(e){return this._sourceMesh.isVerticesDataPresent(e)},i.prototype.getIndices=function(){return this._sourceMesh.getIndices()},Object.defineProperty(i.prototype,"_positions",{get:function(){return this._sourceMesh._positions},enumerable:!0,configurable:!0}),i.prototype.refreshBoundingInfo=function(){var t=this._sourceMesh.getBoundingInfo();this._boundingInfo=new e.BoundingInfo(t.minimum.clone(),t.maximum.clone()),this._updateBoundingInfo()},i.prototype._preActivate=function(){this._currentLOD&&this._currentLOD._preActivate()},i.prototype._activate=function(e){this._currentLOD&&this._currentLOD._registerInstanceForRenderId(this,e)},i.prototype.getLOD=function(e){return this._currentLOD=this.sourceMesh.getLOD(this.getScene().activeCamera,this.getBoundingInfo().boundingSphere),this._currentLOD===this.sourceMesh?this:this._currentLOD},i.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh)},i.prototype._generatePointsArray=function(){return this._sourceMesh._generatePointsArray()},i.prototype.clone=function(t,i,r){var n=this._sourceMesh.createInstance(t);if(e.Tools.DeepCopy(this,n,["name","subMeshes"],[]),this.refreshBoundingInfo(),i&&(n.parent=i),!r)for(var o=0;o<this.getScene().meshes.length;o++){var s=this.getScene().meshes[o];s.parent===this&&s.clone(s.name,n)}return n.computeWorldMatrix(!0),n},i.prototype.dispose=function(e){var i=this._sourceMesh.instances.indexOf(this);this._sourceMesh.instances.splice(i,1),t.prototype.dispose.call(this,e)},i})(e.AbstractMesh);e.InstancedMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array}return e})();e._InstancesBatch=t;var i=(function(i){function r(n,o,s,a,h,c){if(void 0===s&&(s=null),void 0===c&&(c=!0),i.call(this,n,o),this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onBeforeDrawObservable=new e.Observable,this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this.instances=new Array,this._LODLevels=new Array,this._visibleInstances={},this._renderIdForInstances=new Array,this._batchCache=new t,this._instancesBufferSize=2048,this._sideOrientation=r._DEFAULTSIDE,this._areNormalsFrozen=!1,a){a._geometry&&a._geometry.applyToMesh(this),e.Tools.DeepCopy(a,this,["name","material","skeleton","instances","parent"],["_poseMatrix"]),this.parent=a.parent,this.setPivotMatrix(a.getPivotMatrix()),this.id=n+"."+a.id,this.material=a.material;var l;if(!h)for(l=0;l<o.meshes.length;l++){var u=o.meshes[l];if(u.parent===a){u.clone(n+"."+u.name,this,h)}}var f=this.getScene().getPhysicsEngine();if(c&&f){var d=f.getImpostorForPhysicsObject(a);d&&(this.physicsImpostor=d.clone(this))}for(l=0;l<o.particleSystems.length;l++){var p=o.particleSystems[l];p.emitter===a&&p.clone(p.name,this)}this.computeWorldMatrix(!0)}null!==s&&(this.parent=s)}return __extends(r,i),Object.defineProperty(r,"FRONTSIDE",{get:function(){return r._FRONTSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BACKSIDE",{get:function(){return r._BACKSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"DOUBLESIDE",{get:function(){return r._DOUBLESIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"DEFAULTSIDE",{get:function(){return r._DEFAULTSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"NO_CAP",{get:function(){return r._NO_CAP},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_START",{get:function(){return r._CAP_START},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_END",{get:function(){return r._CAP_END},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_ALL",{get:function(){return r._CAP_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"onBeforeDraw",{set:function(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)},enumerable:!0,configurable:!0}),r.prototype.toString=function(t){var r=i.prototype.toString.call(this,t);if(r+=", n vertices: "+this.getTotalVertices(),r+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(var n=0;n<this.animations.length;n++)r+=", animation[0]: "+this.animations[n].toString(t);return t&&(r+=", flat shading: "+(this._geometry?this.getVerticesData(e.VertexBuffer.PositionKind).length/3===this.getIndices().length?"YES":"NO":"UNKNOWN")),r},Object.defineProperty(r.prototype,"hasLODLevels",{get:function(){return this._LODLevels.length>0},enumerable:!0,configurable:!0}),r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distance<t.distance?1:e.distance>t.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.Internals.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;t<this._LODLevels.length;t++){var i=this._LODLevels[t];if(i.distance===e)return i.mesh}return null},r.prototype.removeLODLevel=function(e){for(var t=0;t<this._LODLevels.length;t++)this._LODLevels[t].mesh===e&&(this._LODLevels.splice(t,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this},r.prototype.getLOD=function(e,t){if(!this._LODLevels||0===this._LODLevels.length)return this;var i=(t?t:this.getBoundingInfo().boundingSphere).centerWorld.subtract(e.globalPosition).length();if(this._LODLevels[this._LODLevels.length-1].distance>i)return this.onLODLevelSelection&&this.onLODLevelSelection(i,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var r=0;r<this._LODLevels.length;r++){var n=this._LODLevels[r];if(n.distance<i)return n.mesh&&(n.mesh._preActivate(),n.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)),this.onLODLevelSelection&&this.onLODLevelSelection(i,this,n.mesh),n.mesh}return this.onLODLevelSelection&&this.onLODLevelSelection(i,this,this),this},Object.defineProperty(r.prototype,"geometry",{get:function(){return this._geometry},enumerable:!0,configurable:!0}),r.prototype.getTotalVertices=function(){return this._geometry?this._geometry.getTotalVertices():0},r.prototype.getVerticesData=function(e,t){return this._geometry?this._geometry.getVerticesData(e,t):null},r.prototype.getVertexBuffer=function(e){if(this._geometry)return this._geometry.getVertexBuffer(e)},r.prototype.isVerticesDataPresent=function(e){return this._geometry?this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&this._delayInfo.indexOf(e)!==-1},r.prototype.getVerticesDataKinds=function(){if(!this._geometry){var e=[];return this._delayInfo&&this._delayInfo.forEach((function(t,i,r){e.push(t)})),e}return this._geometry.getVerticesDataKinds()},r.prototype.getTotalIndices=function(){return this._geometry?this._geometry.getTotalIndices():0},r.prototype.getIndices=function(e){return this._geometry?this._geometry.getIndices(e):[]},Object.defineProperty(r.prototype,"isBlocked",{get:function(){return null!==this._masterMesh&&void 0!==this._masterMesh},enumerable:!0,configurable:!0}),r.prototype.isReady=function(){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&i.prototype.isReady.call(this)},r.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(r.prototype,"sideOrientation",{get:function(){return this._sideOrientation},set:function(e){this._sideOrientation=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"areNormalsFrozen",{get:function(){return this._areNormalsFrozen},enumerable:!0,configurable:!0}),r.prototype.freezeNormals=function(){this._areNormalsFrozen=!0},r.prototype.unfreezeNormals=function(){this._areNormalsFrozen=!1},Object.defineProperty(r.prototype,"overridenInstanceCount",{set:function(e){this._overridenInstanceCount=e},enumerable:!0,configurable:!0}),r.prototype._preActivate=function(){var e=this.getScene().getRenderId();this._preActivateId!==e&&(this._preActivateId=e,this._visibleInstances=null)},r.prototype._preActivateForIntermediateRendering=function(e){this._visibleInstances&&(this._visibleInstances.intermediateDefaultRenderId=e)},r.prototype._registerInstanceForRenderId=function(e,t){this._visibleInstances||(this._visibleInstances={},this._visibleInstances.defaultRenderId=t,this._visibleInstances.selfDefaultRenderId=this._renderId),this._visibleInstances[t]||(this._visibleInstances[t]=new Array),this._visibleInstances[t].push(e)},r.prototype.refreshBoundingInfo=function(){if(!this._boundingInfo.isLocked){var t=this.getVerticesData(e.VertexBuffer.PositionKind);if(t){var i=e.Tools.ExtractMinAndMax(t,0,this.getTotalVertices());this._boundingInfo=new e.BoundingInfo(i.minimum,i.maximum)}if(this.subMeshes)for(var r=0;r<this.subMeshes.length;r++)this.subMeshes[r].refreshBoundingInfo();this._updateBoundingInfo()}},r.prototype._createGlobalSubMesh=function(){var t=this.getTotalVertices();return t&&this.getIndices()?(this.releaseSubMeshes(),new e.SubMesh(0,0,t,0,this.getTotalIndices(),this)):null},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!==0;)r++;this.releaseSubMeshes();for(var o=0;o<t&&!(n>=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}},r.prototype.setVerticesBuffer=function(t){if(!this._geometry){var i=this.getScene();new e.Geometry(e.Geometry.RandomId(),i).applyToMesh(this)}this._geometry.setVerticesBuffer(t)},r.prototype.updateVerticesData=function(e,t,i,r){this._geometry&&(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i))},r.prototype.updateVerticesDataDirectly=function(t,i,r,n){e.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3."),this._geometry&&(n?(this.makeGeometryUnique(),this.updateVerticesDataDirectly(t,i,r,!1)):this._geometry.updateVerticesDataDirectly(t,i,r))},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}},r.prototype.makeGeometryUnique=function(){if(this._geometry){var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());t.releaseForMesh(this,!0),i.applyToMesh(this)}},r.prototype.setIndices=function(t,i){if(this._geometry)this._geometry.setIndices(t,i);else{var r=new e.VertexData;r.indices=t;var n=this.getScene();new e.Geometry(e.Geometry.RandomId(),n,r,(!1),this)}},r.prototype.toLeftHanded=function(){this._geometry&&this._geometry.toLeftHanded()},r.prototype._bind=function(t,i,r){var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}o.bindBuffers(this._geometry.getVertexBuffers(),n,i)},r.prototype._draw=function(t,i,r){if(this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){this.onBeforeDrawObservable.notifyObservers(this);var n=this.getScene().getEngine();switch(i){case e.Material.PointFillMode:n.drawPointClouds(t.verticesStart,t.verticesCount,r);break;case e.Material.WireFrameFillMode:this._unIndexed?n.drawUnIndexed(!1,t.verticesStart,t.verticesCount,r):n.draw(!1,0,r>0?t.linesIndexCount/2:t.linesIndexCount,r);break;default:this._unIndexed?n.drawUnIndexed(!0,t.verticesStart,t.verticesCount,r):n.draw(!0,t.indexStart,t.indexCount,r)}}},r.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},r.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},r.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},r.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;if(!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i)),this._batchCache.visibleInstances[e]&&this._batchCache.visibleInstances[e].length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){for(var s=r.visibleInstances[t._id],a=s.length+1,h=16*a*4,c=this._instancesBufferSize,l=this._instancesBuffer;this._instancesBufferSize<h;)this._instancesBufferSize*=2;this._instancesData&&c==this._instancesBufferSize||(this._instancesData=new Float32Array(this._instancesBufferSize/4));var u=0,f=0,d=this.getWorldMatrix();if(r.renderSelf[t._id]&&(d.copyToArray(this._instancesData,u),u+=16,f++),s)for(var p=0;p<s.length;p++){var m=s[p];m.getWorldMatrix().copyToArray(this._instancesData,u),u+=16,f++}l&&c==this._instancesBufferSize?l.updateDirectly(this._instancesData,0,f):(l&&l.dispose(),l=new e.Buffer(o,this._instancesData,(!0),16,(!1),(!0)),this._instancesBuffer=l,this.setVerticesBuffer(l.createVertexBuffer("world0",0,4)),this.setVerticesBuffer(l.createVertexBuffer("world1",4,4)),this.setVerticesBuffer(l.createVertexBuffer("world2",8,4)),this.setVerticesBuffer(l.createVertexBuffer("world3",12,4))),o.bindBuffers(this.geometry.getVertexBuffers(),this.geometry.getIndexBuffer(),n),this._draw(t,i,f),o.unbindInstanceAttributes()},r.prototype._processRendering=function(e,t,i,r,n,o,s){var a=this.getScene(),h=a.getEngine();if(n)this._renderWithInstances(e,i,r,t,h);else if(r.renderSelf[e._id]&&(o&&o(!1,this.getWorldMatrix(),s),this._draw(e,i,this._overridenInstanceCount)),r.visibleInstances[e._id])for(var c=0;c<r.visibleInstances[e._id].length;c++){var l=r.visibleInstances[e._id][c],u=l.getWorldMatrix();o&&o(!0,u,s),this._draw(e,i)}},r.prototype.render=function(t,i){var r=this.getScene(),n=this._getInstancesRenderList(t._id);if(!n.mustReturn&&this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){this.onBeforeRenderObservable.notifyObservers(this);var o=r.getEngine(),s=null!==o.getCaps().instancedArrays&&null!==n.visibleInstances[t._id]&&void 0!==n.visibleInstances[t._id],a=t.getMaterial();if(a&&a.isReady(this,s)){var h=o.getDepthWrite();this.renderOutline&&(o.setDepthWrite(!1),r.getOutlineRenderer().render(t,n),o.setDepthWrite(h)),a._preBind();var c=a.getEffect(),l=r.forcePointsCloud?e.Material.PointFillMode:r.forceWireframe?e.Material.WireFrameFillMode:a.fillMode;this._bind(t,c,l);var u=this.getWorldMatrix();if(a.bind(u,this),i&&o.setAlphaMode(a.alphaMode),this._processRendering(t,c,l,n,s,this._onBeforeDraw,a),a.unbind(),this.renderOutline&&h&&(o.setDepthWrite(!0),o.setColorWrite(!1),r.getOutlineRenderer().render(t,n),o.setColorWrite(!0)),this.renderOverlay){var f=o.getAlphaMode();o.setAlphaMode(e.Engine.ALPHA_COMBINE),r.getOutlineRenderer().render(t,n,!0),o.setAlphaMode(f)}this.onAfterRenderObservable.notifyObservers(this)}}},r.prototype._onBeforeDraw=function(e,t,i){e&&i.bindOnlyWorldMatrix(t)},r.prototype.getEmittedParticleSystems=function(){for(var e=new Array,t=0;t<this.getScene().particleSystems.length;t++){var i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},r.prototype.getHierarchyEmittedParticleSystems=function(){var e=new Array,t=this.getDescendants();t.push(this);for(var i=0;i<this.getScene().particleSystems.length;i++){var r=this.getScene().particleSystems[i];t.indexOf(r.emitter)!==-1&&e.push(r)}return e},r.prototype._checkDelayState=function(){var t=this.getScene();this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(this,t))},r.prototype._queueLoad=function(t,i){var r=this;i._addPendingData(t);var n=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;e.Tools.LoadFile(this.delayLoadingFile,(function(t){t instanceof ArrayBuffer?r._delayLoadingFunction(t,r):r._delayLoadingFunction(JSON.parse(t),r),r.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,i._removePendingData(r)}),(function(){}),i.database,n)},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=0;t<i.length;t++)if(i[t].id===e)return void(this.material=i[t]);var r=this.getScene().multiMaterials;for(t=0;t<r.length;t++)if(r[t].id===e)return void(this.material=r[t])},r.prototype.getAnimatables=function(){var e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(this.isVerticesDataPresent(e.VertexBuffer.PositionKind)){var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=[];for(r=0;r<n.length;r+=3)e.Vector3.TransformCoordinates(e.Vector3.FromArray(n,r),t).toArray(o,r);if(this.setVerticesData(e.VertexBuffer.PositionKind,o,this.getVertexBuffer(e.VertexBuffer.PositionKind).isUpdatable()),this.isVerticesDataPresent(e.VertexBuffer.NormalKind)){for(n=this.getVerticesData(e.VertexBuffer.NormalKind),o=[],r=0;r<n.length;r+=3)e.Vector3.TransformNormal(e.Vector3.FromArray(n,r),t).normalize().toArray(o,r);this.setVerticesData(e.VertexBuffer.NormalKind,o,this.getVertexBuffer(e.VertexBuffer.NormalKind).isUpdatable()),t.m[0]*t.m[5]*t.m[10]<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=i}}},r.prototype.bakeCurrentTransformIntoVertices=function(){this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=e.Quaternion.Identity()),this._worldMatrix=e.Matrix.Identity()},r.prototype._resetPointsArrayCache=function(){this._positions=null},r.prototype._generatePointsArray=function(){if(this._positions)return!0;this._positions=[];var t=this.getVerticesData(e.VertexBuffer.PositionKind);if(!t)return!1;for(var i=0;i<t.length;i+=3)this._positions.push(e.Vector3.FromArray(t,i));return!0},r.prototype.clone=function(e,t,i,n){return void 0===n&&(n=!0),new r(e,this.getScene(),t,this,i,n)},r.prototype.dispose=function(e){for(this._geometry&&this._geometry.releaseForMesh(this,!0),this._instancesBuffer&&(this._instancesBuffer.dispose(),this._instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(var t=this.getScene().highlightLayers,r=0;r<t.length;r++){var n=t[r];n&&(n.removeMesh(this),n.removeExcludedMesh(this))}i.prototype.dispose.call(this,e)},r.prototype.applyDisplacementMap=function(t,i,r,n){var o=this,s=this.getScene(),a=function(e){var t=document.createElement("canvas"),s=t.getContext("2d"),a=e.width,h=e.height;t.width=a,t.height=h,s.drawImage(e,0,0);var c=s.getImageData(0,0,a,h).data;o.applyDisplacementMapFromBuffer(c,a,h,i,r),n&&n(o)};e.Tools.LoadImage(t,a,(function(){}),s.database)},r.prototype.applyDisplacementMapFromBuffer=function(t,i,r,n,o){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind)||!this.isVerticesDataPresent(e.VertexBuffer.NormalKind)||!this.isVerticesDataPresent(e.VertexBuffer.UVKind))return void e.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");for(var s=this.getVerticesData(e.VertexBuffer.PositionKind),a=this.getVerticesData(e.VertexBuffer.NormalKind),h=this.getVerticesData(e.VertexBuffer.UVKind),c=e.Vector3.Zero(),l=e.Vector3.Zero(),u=e.Vector2.Zero(),f=0;f<s.length;f+=3){e.Vector3.FromArrayToRef(s,f,c),e.Vector3.FromArrayToRef(a,f,l),e.Vector2.FromArrayToRef(h,f/3*2,u);var d=Math.abs(u.x)*i%i|0,p=Math.abs(u.y)*r%r|0,m=4*(d+p*i),g=t[m]/255,_=t[m+1]/255,v=t[m+2]/255,y=.3*g+.59*_+.11*v;l.normalize(),l.scaleInPlace(n+(o-n)*y),c=c.add(l),c.toArray(s,f)}e.VertexData.ComputeNormals(s,this.getIndices(),a),this.updateVerticesData(e.VertexBuffer.PositionKind,s),this.updateVerticesData(e.VertexBuffer.NormalKind,a)},r.prototype.convertToFlatShadedMesh=function(){var t,i,r=this.getVerticesDataKinds(),n=[],o=[],s=[],a=!1;for(t=0;t<r.length;t++){i=r[t];var h=this.getVertexBuffer(i);i!==e.VertexBuffer.NormalKind?(n[i]=h,o[i]=n[i].getData(),s[i]=[]):(a=h.isUpdatable(),r.splice(t,1),t--)}var c,l=this.subMeshes.slice(0),u=this.getIndices(),f=this.getTotalIndices();for(c=0;c<f;c++){var d=u[c];for(t=0;t<r.length;t++){i=r[t];for(var p=n[i].getStrideSize(),m=0;m<p;m++)s[i].push(o[i][d*p+m])}}var g=[],_=s[e.VertexBuffer.PositionKind];for(c=0;c<f;c+=3){u[c]=c,u[c+1]=c+1,u[c+2]=c+2;for(var v=e.Vector3.FromArray(_,3*c),y=e.Vector3.FromArray(_,3*(c+1)),x=e.Vector3.FromArray(_,3*(c+2)),b=v.subtract(y),A=x.subtract(y),T=e.Vector3.Normalize(e.Vector3.Cross(b,A)),E=0;E<3;E++)g.push(T.x),g.push(T.y),g.push(T.z)}for(this.setIndices(u),this.setVerticesData(e.VertexBuffer.NormalKind,g,a),t=0;t<r.length;t++)i=r[t],this.setVerticesData(i,s[i],n[i].isUpdatable());this.releaseSubMeshes();for(var M=0;M<l.length;M++){var P=l[M];new e.SubMesh(P.materialIndex,P.indexStart,P.indexCount,P.indexStart,P.indexCount,this)}this.synchronizeInstances()},r.prototype.convertToUnIndexedMesh=function(){var t,i,r=this.getVerticesDataKinds(),n=[],o=[],s=[];for(t=0;t<r.length;t++){i=r[t];var a=this.getVertexBuffer(i);n[i]=a,o[i]=n[i].getData(),s[i]=[]}var h,c=this.subMeshes.slice(0),l=this.getIndices(),u=this.getTotalIndices();for(h=0;h<u;h++){var f=l[h];for(t=0;t<r.length;t++){i=r[t];for(var d=n[i].getStrideSize(),p=0;p<d;p++)s[i].push(o[i][f*d+p])}}for(h=0;h<u;h+=3)l[h]=h,l[h+1]=h+1,l[h+2]=h+2;for(this.setIndices(l),t=0;t<r.length;t++)i=r[t],this.setVerticesData(i,s[i],n[i].isUpdatable());this.releaseSubMeshes();for(var m=0;m<c.length;m++){var g=c[m];new e.SubMesh(g.materialIndex,g.indexStart,g.indexCount,g.indexStart,g.indexCount,this)}this._unIndexed=!0,this.synchronizeInstances()},r.prototype.flipFaces=function(t){void 0===t&&(t=!1);var i,r=e.VertexData.ExtractFromMesh(this);if(t&&this.isVerticesDataPresent(e.VertexBuffer.NormalKind))for(i=0;i<r.normals.length;i++)r.normals[i]*=-1;var n;for(i=0;i<r.indices.length;i+=3)n=r.indices[i+1],r.indices[i+1]=r.indices[i+2],r.indices[i+2]=n;r.applyToMesh(this)},r.prototype.createInstance=function(t){return new e.InstancedMesh(t,this)},r.prototype.synchronizeInstances=function(){for(var e=0;e<this.instances.length;e++){var t=this.instances[e];t._syncSubMeshes()}},r.prototype.simplify=function(t,i,r,n){void 0===i&&(i=!0),void 0===r&&(r=e.SimplificationType.QUADRATIC),this.getScene().simplificationQueue.addTask({settings:t,parallelProcessing:i,mesh:this,simplificationType:r,successCallback:n})},r.prototype.optimizeIndices=function(t){for(var i=this,r=this.getIndices(),n=this.getVerticesData(e.VertexBuffer.PositionKind),o=[],s=0;s<n.length;s+=3)o.push(e.Vector3.FromArray(n,s));var a=[];e.AsyncLoop.SyncAsyncForLoop(o.length,40,(function(e){for(var t=o.length-1-e,i=o[t],r=0;r<t;++r){var n=o[r];if(i.equals(n)){a[t]=r;break}}}),(function(){for(var e=0;e<r.length;++e)r[e]=a[r[e]]||r[e];var n=i.subMeshes.slice(0);i.setIndices(r),i.subMeshes=n,t&&t(i)}))},r.Parse=function(t,i,n){var o=new r(t.name,i);if(o.id=t.id,e.Tags.AddTagsTo(o,t.tags),o.position=e.Vector3.FromArray(t.position),void 0!==t.metadata&&(o.metadata=t.metadata),t.rotationQuaternion?o.rotationQuaternion=e.Quaternion.FromArray(t.rotationQuaternion):t.rotation&&(o.rotation=e.Vector3.FromArray(t.rotation)),o.scaling=e.Vector3.FromArray(t.scaling),t.localMatrix?o.setPivotMatrix(e.Matrix.FromArray(t.localMatrix)):t.pivotMatrix&&o.setPivotMatrix(e.Matrix.FromArray(t.pivotMatrix)),o.setEnabled(t.isEnabled),o.isVisible=t.isVisible,o.infiniteDistance=t.infiniteDistance,o.showBoundingBox=t.showBoundingBox,o.showSubMeshesBoundingBox=t.showSubMeshesBoundingBox,void 0!==t.applyFog&&(o.applyFog=t.applyFog),void 0!==t.pickable&&(o.isPickable=t.pickable),void 0!==t.alphaIndex&&(o.alphaIndex=t.alphaIndex),o.receiveShadows=t.receiveShadows,o.billboardMode=t.billboardMode,void 0!==t.visibility&&(o.visibility=t.visibility),o.checkCollisions=t.checkCollisions,void 0!==t.isBlocker&&(o.isBlocker=t.isBlocker),o._shouldGenerateFlatShading=t.useFlatShading,t.freezeWorldMatrix&&(o._waitingFreezeWorldMatrix=t.freezeWorldMatrix),t.parentId&&(o._waitingParentId=t.parentId),void 0!==t.actions&&(o._waitingActions=t.actions),void 0!==t.overlayAlpha&&(o.overlayAlpha=t.overlayAlpha),void 0!==t.overlayColor&&(o.overlayColor=e.Color3.FromArray(t.overlayColor)),void 0!==t.renderOverlay&&(o.renderOverlay=t.renderOverlay),o.hasVertexAlpha=t.hasVertexAlpha,t.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+t.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(t.boundingBoxMinimum),e.Vector3.FromArray(t.boundingBoxMaximum)),t._binaryInfo&&(o._binaryInfo=t._binaryInfo),o._delayInfo=[],t.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),t.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),t.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),t.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),t.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),t.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),t.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),t.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),t.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.Geometry.ImportGeometry,e.SceneLoader.ForceFullSceneLoadingForIncremental&&o._checkDelayState()):e.Geometry.ImportGeometry(t,o),t.materialId?o.setMaterialByID(t.materialId):o.material=null,t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s<t.animations.length;s++){var a=t.animations[s];o.animations.push(e.Animation.Parse(a))}e.Node.ParseAnimationRanges(o,t,i)}if(t.autoAnimate&&i.beginAnimation(o,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),t.layerMask&&!isNaN(t.layerMask)?o.layerMask=Math.abs(parseInt(t.layerMask)):o.layerMask=268435455,t.physicsImpostor&&(o.physicsImpostor=new e.PhysicsImpostor(o,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},i)),t.instances)for(var h=0;h<t.instances.length;h++){var c=t.instances[h],l=o.createInstance(c.name);if(e.Tags.AddTagsTo(l,c.tags),l.position=e.Vector3.FromArray(c.position),c.parentId&&(l._waitingParentId=c.parentId),c.rotationQuaternion?l.rotationQuaternion=e.Quaternion.FromArray(c.rotationQuaternion):c.rotation&&(l.rotation=e.Vector3.FromArray(c.rotation)),l.scaling=e.Vector3.FromArray(c.scaling),l.checkCollisions=o.checkCollisions,t.animations){for(s=0;s<t.animations.length;s++)a=t.animations[s],l.animations.push(e.Animation.Parse(a));e.Node.ParseAnimationRanges(l,t,i)}}return o},r.CreateRibbon=function(t,i,r,n,o,s,a,h,c){return e.MeshBuilder.CreateRibbon(t,{pathArray:i,closeArray:r,closePath:n,offset:o,updatable:a,sideOrientation:h,instance:c},s)},r.CreateDisc=function(t,i,r,n,o,s){var a={radius:i,tessellation:r,sideOrientation:s,updatable:o};return e.MeshBuilder.CreateDisc(t,a,n)},r.CreateBox=function(t,i,r,n,o){var s={size:i,sideOrientation:o,updatable:n};return e.MeshBuilder.CreateBox(t,s,r)},r.CreateSphere=function(t,i,r,n,o,s){var a={segments:i,diameterX:r,diameterY:r,diameterZ:r,sideOrientation:s,updatable:o};return e.MeshBuilder.CreateSphere(t,a,n)},r.CreateCylinder=function(t,i,n,o,s,a,h,c,l){void 0!==h&&h instanceof e.Scene||(void 0!==h&&(l=c||r.DEFAULTSIDE,c=h),h=a,a=1);var u={height:i,diameterTop:n,diameterBottom:o,tessellation:s,subdivisions:a,sideOrientation:l,updatable:c};return e.MeshBuilder.CreateCylinder(t,u,h)},r.CreateTorus=function(t,i,r,n,o,s,a){var h={diameter:i,thickness:r,tessellation:n,sideOrientation:a,updatable:s};return e.MeshBuilder.CreateTorus(t,h,o)},r.CreateTorusKnot=function(t,i,r,n,o,s,a,h,c,l){var u={radius:i,tube:r,radialSegments:n,tubularSegments:o,p:s,q:a,sideOrientation:l,updatable:c};return e.MeshBuilder.CreateTorusKnot(t,u,h)},r.CreateLines=function(t,i,r,n,o){var s={points:i,updatable:n,instance:o};return e.MeshBuilder.CreateLines(t,s,r)},r.CreateDashedLines=function(t,i,r,n,o,s,a,h){var c={points:i,dashSize:r,gapSize:n,dashNb:o,updatable:a,instance:h};return e.MeshBuilder.CreateDashedLines(t,c,s)},r.ExtrudeShape=function(t,i,n,o,s,a,h,c,l,u){var f={shape:i,path:n,scale:o,rotation:s,cap:0===a?0:a||r.NO_CAP,sideOrientation:l,instance:u,updatable:c};return e.MeshBuilder.ExtrudeShape(t,f,h)},r.ExtrudeShapeCustom=function(t,i,n,o,s,a,h,c,l,u,f,d){var p={shape:i,path:n,scaleFunction:o,rotationFunction:s,ribbonCloseArray:a,ribbonClosePath:h,cap:0===c?0:c||r.NO_CAP,sideOrientation:f,instance:d,updatable:u};return e.MeshBuilder.ExtrudeShapeCustom(t,p,l)},r.CreateLathe=function(t,i,r,n,o,s,a){var h={shape:i,radius:r,tessellation:n,sideOrientation:a,updatable:s};return e.MeshBuilder.CreateLathe(t,h,o)},r.CreatePlane=function(t,i,r,n,o){var s={size:i,width:i,height:i,sideOrientation:o,updatable:n};return e.MeshBuilder.CreatePlane(t,s,r)},r.CreateGround=function(t,i,r,n,o,s){var a={width:i,height:r,subdivisions:n,updatable:s};return e.MeshBuilder.CreateGround(t,a,o)},r.CreateTiledGround=function(t,i,r,n,o,s,a,h,c){var l={xmin:i,zmin:r,xmax:n,zmax:o,subdivisions:s,precision:a,updatable:c};return e.MeshBuilder.CreateTiledGround(t,l,h)},r.CreateGroundFromHeightMap=function(t,i,r,n,o,s,a,h,c,l){var u={width:r,height:n,subdivisions:o,minHeight:s,maxHeight:a,updatable:c,onReady:l};return e.MeshBuilder.CreateGroundFromHeightMap(t,i,u,h)},r.CreateTube=function(t,i,r,n,o,s,a,h,c,l){var u={path:i,radius:r,tessellation:n,radiusFunction:o,arc:1,cap:s,updatable:h,sideOrientation:c,instance:l};return e.MeshBuilder.CreateTube(t,u,a)},r.CreatePolyhedron=function(t,i,r){return e.MeshBuilder.CreatePolyhedron(t,i,r)},r.CreateIcoSphere=function(t,i,r){
return e.MeshBuilder.CreateIcoSphere(t,i,r)},r.CreateDecal=function(t,i,r,n,o,s){var a={position:r,normal:n,size:o,angle:s};return e.MeshBuilder.CreateDecal(t,i,a)},r.prototype.setPositionsForCPUSkinning=function(){var t;return this._sourcePositions||(t=this.getVerticesData(e.VertexBuffer.PositionKind),this._sourcePositions=new Float32Array(t),this.getVertexBuffer(e.VertexBuffer.PositionKind).isUpdatable()||this.setVerticesData(e.VertexBuffer.PositionKind,t,!0)),this._sourcePositions},r.prototype.setNormalsForCPUSkinning=function(){var t;return this._sourceNormals||(t=this.getVerticesData(e.VertexBuffer.NormalKind),this._sourceNormals=new Float32Array(t),this.getVertexBuffer(e.VertexBuffer.NormalKind).isUpdatable()||this.setVerticesData(e.VertexBuffer.NormalKind,t,!0)),this._sourceNormals},r.prototype.applySkeleton=function(t){if(this.geometry&&this.geometry._softwareSkinningRenderId!=this.getScene().getRenderId()){if(this.geometry._softwareSkinningRenderId=this.getScene().getRenderId(),!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.NormalKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind))return this;if(!this._sourcePositions){var i=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=i}this._sourceNormals||this.setNormalsForCPUSkinning();var r=this.getVerticesData(e.VertexBuffer.PositionKind);r instanceof Float32Array||(r=new Float32Array(r));var n=this.getVerticesData(e.VertexBuffer.NormalKind);n instanceof Float32Array||(n=new Float32Array(n));for(var o,s=this.getVerticesData(e.VertexBuffer.MatricesIndicesKind),a=this.getVerticesData(e.VertexBuffer.MatricesWeightsKind),h=this.numBoneInfluencers>4,c=h?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,l=h?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),f=e.Vector3.Zero(),d=new e.Matrix,p=new e.Matrix,m=0,g=0;g<r.length;g+=3,m+=4){var _;for(o=0;o<4&&(_=a[m+o],_>0);o++)e.Matrix.FromFloat32ArrayToRefScaled(u,16*s[m+o],_,p),d.addToSelf(p);if(h)for(o=0;o<4&&(_=l[m+o],_>0);o++)e.Matrix.FromFloat32ArrayToRefScaled(u,16*c[m+o],_,p),d.addToSelf(p);e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[g],this._sourcePositions[g+1],this._sourcePositions[g+2],d,f),f.toArray(r,g),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[g],this._sourceNormals[g+1],this._sourceNormals[g+2],d,f),f.toArray(n,g),d.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this}},r.MinMax=function(e){var t=null,i=null;return e.forEach((function(e,r,n){var o=e.getBoundingInfo().boundingBox;t?(t.MinimizeInPlace(o.minimumWorld),i.MaximizeInPlace(o.maximumWorld)):(t=o.minimumWorld,i=o.maximumWorld)})),{min:t,max:i}},r.Center=function(t){var i=t instanceof Array?e.Mesh.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o){void 0===i&&(i=!0);var s;if(!n){var a=0;for(s=0;s<t.length;s++)if(t[s]&&(a+=t[s].getTotalVertices(),a>65536))return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var h,c,l;for(s=0;s<t.length;s++)t[s]&&(t[s].computeWorldMatrix(!0),c=e.VertexData.ExtractFromMesh(t[s],!0),c.transform(t[s].getWorldMatrix()),h?h.merge(c):(h=c,l=t[s]));if(o||(o=new r(l.name+"_merged",l.getScene())),h.applyToMesh(o),o.material=l.material,o.checkCollisions=l.checkCollisions,i)for(s=0;s<t.length;s++)t[s]&&t[s].dispose();return o},r._FRONTSIDE=0,r._BACKSIDE=1,r._DOUBLESIDE=2,r._DEFAULTSIDE=0,r._NO_CAP=0,r._CAP_START=1,r._CAP_END=2,r._CAP_ALL=3,r})(e.AbstractMesh);e.Mesh=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o,s,a){void 0===a&&(a=!0),this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=n,this._renderId=0,this._mesh=o,this._renderingMesh=s||o,o.subMeshes.push(this),this._trianglePlanes=[],this._id=o.subMeshes.length-1,a&&(this.refreshBoundingInfo(),o.computeWorldMatrix(!0))}return Object.defineProperty(t.prototype,"IsGlobal",{get:function(){return 0===this.verticesStart&&this.verticesCount==this._mesh.getTotalVertices()},enumerable:!0,configurable:!0}),t.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},t.prototype.getMesh=function(){return this._mesh},t.prototype.getRenderingMesh=function(){return this._renderingMesh},t.prototype.getMaterial=function(){var t=this._renderingMesh.material;if(t&&t instanceof e.MultiMaterial){var i=t;return i.getSubMaterial(this.materialIndex)}return t?t:this._mesh.getScene().defaultMaterial},t.prototype.refreshBoundingInfo=function(){if(this._lastColliderWorldVertices=null,!this.IsGlobal){var t=this._renderingMesh.getVerticesData(e.VertexBuffer.PositionKind);if(!t)return void(this._boundingInfo=this._mesh._boundingInfo);var i,r=this._renderingMesh.getIndices();i=0===this.indexStart&&this.indexCount===r.length?{minimum:this._renderingMesh.getBoundingInfo().minimum.clone(),maximum:this._renderingMesh.getBoundingInfo().maximum.clone()}:e.Tools.ExtractMinAndMaxIndexed(t,r,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias),this._boundingInfo=new e.BoundingInfo(i.minimum,i.maximum)}},t.prototype._checkCollision=function(e){return this.getBoundingInfo()._checkCollision(e)},t.prototype.updateBoundingInfo=function(e){this.getBoundingInfo()||this.refreshBoundingInfo(),this.getBoundingInfo().update(e)},t.prototype.isInFrustum=function(e){return this.getBoundingInfo().isInFrustum(e)},t.prototype.isCompletelyInFrustum=function(e){return this.getBoundingInfo().isCompletelyInFrustum(e)},t.prototype.render=function(e){this._renderingMesh.render(this,e)},t.prototype.getLinesIndexBuffer=function(e,t){if(!this._linesIndexBuffer){for(var i=[],r=this.indexStart;r<this.indexStart+this.indexCount;r+=3)i.push(e[r],e[r+1],e[r+1],e[r+2],e[r+2],e[r]);this._linesIndexBuffer=t.createIndexBuffer(i),this.linesIndexCount=i.length}return this._linesIndexBuffer},t.prototype.canIntersects=function(e){return e.intersectsBox(this.getBoundingInfo().boundingBox)},t.prototype.intersects=function(t,i,r,n){var o=null;if(this._mesh instanceof e.LinesMesh)for(var s=this._mesh,a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){var h=i[r[a]],c=i[r[a+1]],l=t.intersectionSegment(h,c,s.intersectionThreshold);if(!(l<0)&&(n||!o||l<o.distance)&&(o=new e.IntersectionInfo(null,null,l),n))break}else for(var a=this.indexStart;a<this.indexStart+this.indexCount;a+=3){var h=i[r[a]],c=i[r[a+1]],u=i[r[a+2]],f=t.intersectsTriangle(h,c,u);if(f){if(f.distance<0)continue;if((n||!o||f.distance<o.distance)&&(o=f,o.faceId=a/3,n))break}}return o},t.prototype.clone=function(i,r){var n=new t(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,i,r,(!1));return this.IsGlobal||(n._boundingInfo=new e.BoundingInfo(this.getBoundingInfo().minimum,this.getBoundingInfo().maximum)),n},t.prototype.dispose=function(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);var e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1)},t.CreateFromIndices=function(e,i,r,n,o){var s=Number.MAX_VALUE,a=-Number.MAX_VALUE;o=o||n;for(var h=o.getIndices(),c=i;c<i+r;c++){var l=h[c];l<s&&(s=l),l>a&&(a=l)}return new t(e,s,a-s+1,i,r,n,o)},t})();e.SubMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.updateSideOrientation=function(t,i){return t==e.Mesh.DOUBLESIDE?e.Mesh.DOUBLESIDE:void 0===t||null===t?e.Mesh.FRONTSIDE:t},t.CreateBox=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateBox(i);return o.applyToMesh(n,i.updatable),n},t.CreateSphere=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateSphere(i);return o.applyToMesh(n,i.updatable),n},t.CreateDisc=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateDisc(i);return o.applyToMesh(n,i.updatable),n},t.CreateIcoSphere=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateIcoSphere(i);return o.applyToMesh(n,i.updatable),n},t.CreateRibbon=function(t,i,r){var n=i.pathArray,o=i.closeArray,s=i.closePath,a=(i.offset,this.updateSideOrientation(i.sideOrientation,r)),h=i.instance,c=i.updatable;if(h){e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,e.Tmp.Vector3[0]),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,e.Tmp.Vector3[1]);var l=function(t){for(var i=n[0].length,r=0,o=h.sideOrientation===e.Mesh.DOUBLESIDE?2:1,s=1;s<=o;s++)for(var a=0;a<n.length;a++){var c=n[a],l=c.length;i=i<l?i:l;for(var u=0;u<i;)t[r]=c[u].x,t[r+1]=c[u].y,t[r+2]=c[u].z,c[u].x<e.Tmp.Vector3[0].x&&(e.Tmp.Vector3[0].x=c[u].x),c[u].x>e.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=c[u].x),c[u].y<e.Tmp.Vector3[0].y&&(e.Tmp.Vector3[0].y=c[u].y),c[u].y>e.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=c[u].y),c[u].z<e.Tmp.Vector3[0].z&&(e.Tmp.Vector3[0].z=c[u].z),c[u].z>e.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=c[u].z),u++,r+=3;h._closePath&&(t[r]=c[0].x,t[r+1]=c[0].y,t[r+2]=c[0].z,r+=3)}},u=h.getVerticesData(e.VertexBuffer.PositionKind);if(l(u),h._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),h._boundingInfo.update(h._worldMatrix),h.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),!h.areNormalsFrozen){var f=h.getIndices(),d=h.getVerticesData(e.VertexBuffer.NormalKind);if(e.VertexData.ComputeNormals(u,f,d),h._closePath)for(var p=0,m=0,g=0;g<n.length;g++)p=3*h._idx[g],m=g+1<n.length?3*(h._idx[g+1]-1):d.length-3,d[p]=.5*(d[p]+d[m]),d[p+1]=.5*(d[p+1]+d[m+1]),d[p+2]=.5*(d[p+2]+d[m+2]),d[m]=d[p],d[m+1]=d[p+1],d[m+2]=d[p+2];h.updateVerticesData(e.VertexBuffer.NormalKind,d,!1,!1)}return h}var _=new e.Mesh(t,r);_.sideOrientation=a;var v=e.VertexData.CreateRibbon(i);return s&&(_._idx=v._idx),_._closePath=s,_._closeArray=o,v.applyToMesh(_,c),_},t.CreateCylinder=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateCylinder(i);return o.applyToMesh(n,i.updatable),n},t.CreateTorus=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateTorus(i);return o.applyToMesh(n,i.updatable),n},t.CreateTorusKnot=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateTorusKnot(i);return o.applyToMesh(n,i.updatable),n},t.CreateLineSystem=function(t,i,r){var n=i.instance,o=i.lines;if(n){var s=function(e){for(var t=0,i=0;i<o.length;i++)for(var r=o[i],n=0;n<r.length;n++)e[t]=r[n].x,e[t+1]=r[n].y,e[t+2]=r[n].z,t+=3};return n.updateMeshPositions(s,!1),n}var a=new e.LinesMesh(t,r),h=e.VertexData.CreateLineSystem(i);return h.applyToMesh(a,i.updatable),a},t.CreateLines=function(e,i,r){var n=t.CreateLineSystem(e,{lines:[i.points],updatable:i.updatable,instance:i.instance},r);return n},t.CreateDashedLines=function(t,i,r){var n=i.points,o=i.instance,s=i.gapSize,a=(i.dashNb,i.dashSize);if(o){var h=function(t){var i=e.Vector3.Zero(),r=t.length/6,s=0,a=0,h=0,c=0,l=0,u=0,f=0,d=0;for(f=0;f<n.length-1;f++)n[f+1].subtractToRef(n[f],i),s+=i.length();for(h=s/r,c=o.dashSize*h/(o.dashSize+o.gapSize),f=0;f<n.length-1;f++)for(n[f+1].subtractToRef(n[f],i),a=Math.floor(i.length()/h),i.normalize(),d=0;d<a&&u<t.length;)l=h*d,t[u]=n[f].x+l*i.x,t[u+1]=n[f].y+l*i.y,t[u+2]=n[f].z+l*i.z,t[u+3]=n[f].x+(l+c)*i.x,t[u+4]=n[f].y+(l+c)*i.y,t[u+5]=n[f].z+(l+c)*i.z,u+=6,d++;for(;u<t.length;)t[u]=n[f].x,t[u+1]=n[f].y,t[u+2]=n[f].z,u+=3};return o.updateMeshPositions(h,!1),o}var c=new e.LinesMesh(t,r),l=e.VertexData.CreateDashedLines(i);return l.applyToMesh(c,i.updatable),c.dashSize=a,c.gapSize=s,c},t.ExtrudeShape=function(i,r,n){var o=r.path,s=r.shape,a=r.scale||1,h=r.rotation||0,c=0===r.cap?0:r.cap||e.Mesh.NO_CAP,l=r.updatable,u=this.updateSideOrientation(r.sideOrientation,n),f=r.instance,d=r.invertUV||!1;return t._ExtrudeShapeGeneric(i,s,o,a,h,null,null,!1,!1,c,!1,n,l,u,f,d)},t.ExtrudeShapeCustom=function(i,r,n){var o=r.path,s=r.shape,a=r.scaleFunction||function(){return 1},h=r.rotationFunction||function(){return 0},c=r.ribbonCloseArray||!1,l=r.ribbonClosePath||!1,u=0===r.cap?0:r.cap||e.Mesh.NO_CAP,f=r.updatable,d=this.updateSideOrientation(r.sideOrientation,n),p=r.instance,m=r.invertUV||!1;return t._ExtrudeShapeGeneric(i,s,o,null,null,a,h,c,l,u,!0,n,f,d,p,m)},t.CreateLathe=function(i,r,n){var o,s=r.arc<=0||r.arc>1?1:r.arc||1,a=void 0===r.closed||r.closed,h=r.shape,c=r.radius||1,l=r.tessellation||64,u=r.updatable,f=this.updateSideOrientation(r.sideOrientation,n),d=r.cap||e.Mesh.NO_CAP,p=2*Math.PI,m=new Array,g=r.invertUV||!1,_=0,v=0,y=p/l*s,x=new Array;for(_=0;_<=l;_++){var x=[];for(d!=e.Mesh.CAP_START&&d!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,h[0].y,0)),x.push(new e.Vector3(Math.cos(_*y)*h[0].x*c,h[0].y,Math.sin(_*y)*h[0].x*c))),v=0;v<h.length;v++)o=new e.Vector3(Math.cos(_*y)*h[v].x*c,h[v].y,Math.sin(_*y)*h[v].x*c),x.push(o);d!=e.Mesh.CAP_END&&d!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(Math.cos(_*y)*h[h.length-1].x*c,h[h.length-1].y,Math.sin(_*y)*h[h.length-1].x*c)),x.push(new e.Vector3(0,h[h.length-1].y,0))),m.push(x)}var b=t.CreateRibbon(i,{pathArray:m,closeArray:a,sideOrientation:f,updatable:u,invertUV:g},n);return b},t.CreatePlane=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreatePlane(i);if(o.applyToMesh(n,i.updatable),i.sourcePlane){n.translate(i.sourcePlane.normal,i.sourcePlane.d);var s=Math.acos(e.Vector3.Dot(i.sourcePlane.normal,e.Axis.Z)),a=e.Vector3.Cross(e.Axis.Z,i.sourcePlane.normal);n.rotate(a,s)}return n},t.CreateGround=function(t,i,r){var n=new e.GroundMesh(t,r);n._setReady(!1),n._subdivisionsX=i.subdivisionsX||i.subdivisions||1,n._subdivisionsY=i.subdivisionsY||i.subdivisions||1,n._width=i.width||1,n._height=i.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ;var o=e.VertexData.CreateGround(i);return o.applyToMesh(n,i.updatable),n._setReady(!0),n},t.CreateTiledGround=function(t,i,r){var n=new e.Mesh(t,r),o=e.VertexData.CreateTiledGround(i);return o.applyToMesh(n,i.updatable),n},t.CreateGroundFromHeightMap=function(t,i,r,n){var o=r.width||10,s=r.height||10,a=r.subdivisions||1,h=r.minHeight||0,c=r.maxHeight||10,l=r.updatable,u=r.onReady,f=new e.GroundMesh(t,n);f._subdivisionsX=a,f._subdivisionsY=a,f._width=o,f._height=s,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);var d=function(t){var i=document.createElement("canvas"),r=i.getContext("2d"),n=t.width,d=t.height;i.width=n,i.height=d,r.drawImage(t,0,0);var p=r.getImageData(0,0,n,d).data,m=e.VertexData.CreateGroundFromHeightMap({width:o,height:s,subdivisions:a,minHeight:h,maxHeight:c,buffer:p,bufferWidth:n,bufferHeight:d});m.applyToMesh(f,l),f._setReady(!0),u&&u(f)};return e.Tools.LoadImage(i,d,(function(){}),n.database),f},t.CreateTube=function(i,r,n){var o=r.path,s=r.radius||1,a=r.tessellation||64,h=r.radiusFunction,c=r.cap||e.Mesh.NO_CAP,l=r.invertUV||!1,u=r.updatable,f=this.updateSideOrientation(r.sideOrientation,n),d=r.instance;r.arc=r.arc<=0||r.arc>1?1:r.arc||1;var p,m,g=function(t,i,r,n,o,s,a,h){for(var c,l,u,f,d=i.getTangents(),p=i.getNormals(),m=i.getDistances(),g=2*Math.PI,_=g/o*h,v=function(){return n},y=s||v,x=e.Tmp.Matrix[0],b=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,A=0;A<t.length;A++){l=y(A,m[A]),c=Array(),u=p[A];for(var T=0;T<o;T++)e.Matrix.RotationAxisToRef(d[A],_*T,x),f=c[T]?c[T]:e.Vector3.Zero(),e.Vector3.TransformCoordinatesToRef(u,x,f),f.scaleInPlace(l).addInPlace(t[A]),c[T]=f;r[b]=c,b++}var E=function(e,i){for(var r=Array(),n=0;n<e;n++)r.push(t[i]);return r};switch(a){case e.Mesh.NO_CAP:break;case e.Mesh.CAP_START:r[0]=E(o,0),r[1]=r[2].slice(0);break;case e.Mesh.CAP_END:r[b]=r[b-1].slice(0),r[b+1]=E(o,t.length-1);break;case e.Mesh.CAP_ALL:r[0]=E(o,0),r[1]=r[2].slice(0),r[b]=r[b-1].slice(0),r[b+1]=E(o,t.length-1)}return r};if(d){var _=r.arc||d.arc;return p=d.path3D.update(o),m=g(o,p,d.pathArray,s,d.tessellation,h,d.cap,_),d=t.CreateRibbon(null,{pathArray:m,instance:d}),d.path3D=p,d.pathArray=m,d.arc=_,d}p=new e.Path3D(o);var v=new Array;c=c<0||c>3?0:c,m=g(o,p,v,s,a,h,c,r.arc);var y=t.CreateRibbon(i,{pathArray:m,closePath:!0,closeArray:!1,updatable:u,sideOrientation:f,invertUV:l},n);return y.pathArray=m,y.path3D=p,y.tessellation=a,y.cap=c,y.arc=r.arc,y},t.CreatePolyhedron=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreatePolyhedron(i);return o.applyToMesh(n,i.updatable),n},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),h=r.normal||e.Vector3.Up(),c=r.size||new e.Vector3(1,1,1),l=r.angle||0;if(!h){var u=new e.Vector3(0,0,1),f=i.getScene().activeCamera,d=e.Vector3.TransformCoordinates(u,f.getWorldMatrix());h=f.globalPosition.subtract(d)}var p=-Math.atan2(h.z,h.x)-Math.PI/2,m=Math.sqrt(h.x*h.x+h.z*h.z),g=Math.atan2(h.y,m),_=e.Matrix.RotationYawPitchRoll(p,g,l).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(_),y=i.getWorldMatrix(),x=y.multiply(v),b=new e.VertexData;b.indices=[],b.positions=[],b.normals=[],b.uvs=[];for(var A=0,T=function(t){var i=n[t],r=new e.PositionNormalVertex;return r.position=new e.Vector3(o[3*i],o[3*i+1],o[3*i+2]),r.position=e.Vector3.TransformCoordinates(r.position,x),r.normal=new e.Vector3(s[3*i],s[3*i+1],s[3*i+2]),r},E=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(c,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s<t.length;s+=3){var a,h,l,u,f,d,p,m=0,g=e.Vector3.Dot(t[s].position,i)-r,_=e.Vector3.Dot(t[s+1].position,i)-r,v=e.Vector3.Dot(t[s+2].position,i)-r;switch(a=g>0,h=_>0,l=v>0,m=(a?1:0)+(h?1:0)+(l?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],f=t[s+2],d=n(t[s],u),p=n(t[s],f)),h){u=t[s],f=t[s+2],d=n(t[s+1],u),p=n(t[s+1],f),o.push(d),o.push(f.clone()),o.push(u.clone()),o.push(f.clone()),o.push(d.clone()),o.push(p);break}l&&(u=t[s],f=t[s+1],d=n(t[s+2],u),p=n(t[s+2],f)),o.push(u.clone()),o.push(f.clone()),o.push(d),o.push(p),o.push(d.clone()),o.push(f.clone());break;case 2:a||(u=t[s].clone(),f=n(u,t[s+1]),d=n(u,t[s+2]),o.push(u),o.push(f),o.push(d)),h||(u=t[s+1].clone(),f=n(u,t[s+2]),d=n(u,t[s]),o.push(u),o.push(f),o.push(d)),l||(u=t[s+2].clone(),f=n(u,t[s]),d=n(u,t[s+1]),o.push(u),o.push(f),o.push(d));break;case 3:}}return o},M=0;M<n.length;M+=3){var P=new Array;if(P.push(T(M)),P.push(T(M+1)),P.push(T(M+2)),P=E(P,new e.Vector3(1,0,0)),P=E(P,new e.Vector3((-1),0,0)),P=E(P,new e.Vector3(0,1,0)),P=E(P,new e.Vector3(0,(-1),0)),P=E(P,new e.Vector3(0,0,1)),P=E(P,new e.Vector3(0,0,(-1))),0!==P.length)for(var S=0;S<P.length;S++){var C=P[S];b.indices.push(A),C.position.toArray(b.positions,3*A),C.normal.toArray(b.normals,3*A),b.uvs.push(.5+C.position.x/c.x),b.uvs.push(.5+C.position.y/c.y),A++}}var R=new e.Mesh(t,i.getScene());return b.applyToMesh(R),R.position=a.clone(),R.rotation=new e.Vector3(g,p,l),R},t._ExtrudeShapeGeneric=function(i,r,n,o,s,a,h,c,l,u,f,d,p,m,g,_){var v,y,x=function(t,i,r,n,o,s,a,h,c,l){for(var u=r.getTangents(),f=r.getNormals(),d=r.getBinormals(),p=r.getDistances(),m=0,g=function(){return o},_=function(){return s},v=l?h:_,y=l?a:g,x=c===e.Mesh.NO_CAP||c===e.Mesh.CAP_END?0:2,b=e.Tmp.Matrix[0],A=0;A<i.length;A++){for(var T=new Array,E=v(A,p[A]),M=y(A,p[A]),P=0;P<t.length;P++){e.Matrix.RotationAxisToRef(u[A],m,b);var S=u[A].scale(t[P].z).add(f[A].scale(t[P].x)).add(d[A].scale(t[P].y)),C=T[P]?T[P]:e.Vector3.Zero();e.Vector3.TransformCoordinatesToRef(S,b,C),C.scaleInPlace(M).addInPlace(i[A]),T[P]=C}n[x]=T,m+=E,x++}var R=function(t){var i,r=Array(),n=e.Vector3.Zero();for(i=0;i<t.length;i++)n.addInPlace(t[i]);for(n.scaleInPlace(1/t.length),i=0;i<t.length;i++)r.push(n);return r};switch(c){case e.Mesh.NO_CAP:break;case e.Mesh.CAP_START:n[0]=R(n[2]),n[1]=n[2].slice(0);break;case e.Mesh.CAP_END:n[x]=n[x-1],n[x+1]=R(n[x-1]);break;case e.Mesh.CAP_ALL:n[0]=R(n[2]),n[1]=n[2].slice(0),n[x]=n[x-1],n[x+1]=R(n[x-1])}return n};if(g)return v=g.path3D.update(n),y=x(r,n,g.path3D,g.pathArray,o,s,a,h,g.cap,f),g=e.Mesh.CreateRibbon(null,y,null,null,null,d,null,null,g);v=new e.Path3D(n);var b=new Array;u=u<0||u>3?0:u,y=x(r,n,v,b,o,s,a,h,u,f);var A=t.CreateRibbon(i,{pathArray:y,closeArray:c,closePath:l,updatable:p,sideOrientation:m,invertUV:_},d);return A.pathArray=y,A.path3D=v,A.cap=u,A},t})();e.MeshBuilder=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.hasAlpha=!1,this.getAlphaFromRGB=!1,this.level=1,this.coordinatesIndex=0,this.coordinatesMode=e.Texture.EXPLICIT_MODE,this.wrapU=e.Texture.WRAP_ADDRESSMODE,this.wrapV=e.Texture.WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.isCube=!1,this.isRenderTarget=!1,this.animations=new Array,this.onDisposeObservable=new e.Observable,this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this._scene=t,this._scene.textures.push(this),this._uid=null}return Object.defineProperty(t.prototype,"uid",{get:function(){return this._uid||(this._uid=e.Tools.RandomId()),this._uid},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return this.name},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getTextureMatrix=function(){return null},t.prototype.getReflectionTextureMatrix=function(){return null},t.prototype.getInternalTexture=function(){return this._texture},t.prototype.isReady=function(){return this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED||!!this._texture&&this._texture.isReady},t.prototype.getSize=function(){return this._texture._width?new e.Size(this._texture._width,this._texture._height):this._texture._size?new e.Size(this._texture._size,this._texture._size):e.Size.Zero()},t.prototype.getBaseSize=function(){return this.isReady()&&this._texture?this._texture._size?new e.Size(this._texture._size,this._texture._size):new e.Size(this._texture._baseWidth,this._texture._baseHeight):e.Size.Zero()},t.prototype.scale=function(e){},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),t.prototype._removeFromCache=function(e,t){for(var i=this._scene.getEngine().getLoadedTexturesCache(),r=0;r<i.length;r++){var n=i[r];if(n.url===e&&n.noMipmap===t)return void i.splice(r,1)}},t.prototype._getFromCache=function(e,t,i){for(var r=this._scene.getEngine().getLoadedTexturesCache(),n=0;n<r.length;n++){var o=r[n];if(o.url===e&&o.noMipmap===t&&(!i||i===o.samplingMode))return o.references++,o}return null},t.prototype.delayLoad=function(){},t.prototype.clone=function(){return null},t.prototype.releaseInternalTexture=function(){this._texture&&(this._scene.getEngine().releaseInternalTexture(this._texture),delete this._texture)},t.prototype.dispose=function(){this.getScene().stopAnimation(this);var e=this._scene.textures.indexOf(this);e>=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"hasAlpha",void 0),__decorate([e.serialize()],t.prototype,"getAlphaFromRGB",void 0),__decorate([e.serialize()],t.prototype,"level",void 0),__decorate([e.serialize()],t.prototype,"coordinatesIndex",void 0),__decorate([e.serialize()],t.prototype,"coordinatesMode",void 0),__decorate([e.serialize()],t.prototype,"wrapU",void 0),__decorate([e.serialize()],t.prototype,"wrapV",void 0),__decorate([e.serialize()],t.prototype,"anisotropicFilteringLevel",void 0),__decorate([e.serialize()],t.prototype,"isCube",void 0),__decorate([e.serialize()],t.prototype,"isRenderTarget",void 0),t})();e.BaseTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a,h,c,l,u){var f=this;if(void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=i.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=null),void 0===c&&(c=null),void 0===l&&(l=null),void 0===u&&(u=!1),t.call(this,n),this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.name=r,this.url=r,this._noMipmap=o,this._invertY=s,this._samplingMode=a,this._buffer=l,this._deleteBuffer=u,r){this._texture=this._getFromCache(r,o,a);var d=function(){f._onLoadObservarble&&f._onLoadObservarble.hasObservers()&&f.onLoadObservable.notifyObservers(!0),h&&h()};this._texture?this._texture.isReady?e.Tools.SetImmediate((function(){return d()})):this._texture.onLoadedCallbacks.push(d):n.useDelayedTextureLoading?(this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=d,this._delayedOnError=c):(this._texture=n.getEngine().createTexture(r,o,s,n,this._samplingMode,d,c,this._buffer),u&&delete this._buffer)}}return __extends(i,t),Object.defineProperty(i.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!0,configurable:!0}),i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this._samplingMode),this._texture||(this._texture=this.getScene().getEngine().createTexture(this.url,this._noMipmap,this._invertY,this.getScene(),this._samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer),this._deleteBuffer&&delete this._buffer))},i.prototype.updateSamplingMode=function(e){this._texture&&(this._samplingMode=e,this.getScene().getEngine().updateTextureSamplingMode(e,this._texture))},i.prototype._prepareRowForTextureGeneration=function(t,i,r,n){t*=this.uScale,i*=this.vScale,t-=.5*this.uScale,i-=.5*this.vScale,r-=.5,e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,this._rowGenerationMatrix,n),n.x+=.5*this.uScale+this.uOffset,n.y+=.5*this.vScale+this.vOffset,n.z+=.5},i.prototype.getTextureMatrix=function(){return this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng?this._cachedTextureMatrix:(this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedTextureMatrix||(this._cachedTextureMatrix=e.Matrix.Zero(),this._rowGenerationMatrix=new e.Matrix,this._t0=e.Vector3.Zero(),this._t1=e.Vector3.Zero(),this._t2=e.Vector3.Zero()),e.Matrix.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),e.Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix.m[0]=this._t1.x,this._cachedTextureMatrix.m[1]=this._t1.y,this._cachedTextureMatrix.m[2]=this._t1.z,this._cachedTextureMatrix.m[4]=this._t2.x,this._cachedTextureMatrix.m[5]=this._t2.y,this._cachedTextureMatrix.m[6]=this._t2.z,this._cachedTextureMatrix.m[8]=this._t0.x,this._cachedTextureMatrix.m[9]=this._t0.y,this._cachedTextureMatrix.m[10]=this._t0.z,this._cachedTextureMatrix)},i.prototype.getReflectionTextureMatrix=function(){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.coordinatesMode===this._cachedCoordinatesMode)return this._cachedTextureMatrix;switch(this._cachedTextureMatrix||(this._cachedTextureMatrix=e.Matrix.Zero(),this._projectionModeMatrix=e.Matrix.Zero()),this._cachedCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case i.PLANAR_MODE:e.Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix[0]=this.uScale,this._cachedTextureMatrix[5]=this.vScale,this._cachedTextureMatrix[12]=this.uOffset,this._cachedTextureMatrix[13]=this.vOffset;break;case i.PROJECTION_MODE:e.Matrix.IdentityToRef(this._projectionModeMatrix),this._projectionModeMatrix.m[0]=.5,this._projectionModeMatrix.m[5]=-.5,this._projectionModeMatrix.m[10]=0,this._projectionModeMatrix.m[12]=.5,this._projectionModeMatrix.m[13]=.5,this._projectionModeMatrix.m[14]=1,this._projectionModeMatrix.m[15]=1,this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix,this._cachedTextureMatrix);break;default:e.Matrix.IdentityToRef(this._cachedTextureMatrix)}return this._cachedTextureMatrix},i.prototype.clone=function(){var t=this;return e.SerializationHelper.Clone((function(){return new i(t._texture.url,t.getScene(),t._noMipmap,t._invertY,t._samplingMode)}),this)},Object.defineProperty(i.prototype,"onLoadObservable",{get:function(){return this._onLoadObservarble||(this._onLoadObservarble=new e.Observable),this._onLoadObservarble},enumerable:!0,configurable:!0}),i.CreateFromBase64String=function(e,t,r,n,o,s,a,h){return void 0===s&&(s=i.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===h&&(h=null),new i("data:"+t,r,n,o,s,a,h,e)},i.Parse=function(t,r,n){if(t.customType){var o=e.Tools.Instantiate(t.customType);return o.Parse(t,r,n)}if(t.isCube)return e.CubeTexture.Parse(t,r,n);if(!t.name&&!t.isRenderTarget)return null;var s=e.SerializationHelper.Parse((function(){if(t.mirrorPlane){var o=new e.MirrorTexture(t.name,t.renderTargetSize,r);return o._waitingRenderList=t.renderList,o.mirrorPlane=e.Plane.FromArray(t.mirrorPlane),o}if(t.isRenderTarget){var s=new e.RenderTargetTexture(t.name,t.renderTargetSize,r);return s._waitingRenderList=t.renderList,s}var a;return a=t.base64String?i.CreateFromBase64String(t.base64String,t.name,r):new i(n+t.name,r)}),t,r);if(t.animations)for(var a=0;a<t.animations.length;a++){var h=t.animations[a];s.animations.push(e.Animation.Parse(h))}return s},i.LoadFromDataString=function(e,t,r,n,o,s,a,h,c){return void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=i.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=null),void 0===c&&(c=null),"data:"!==e.substr(0,5)&&(e="data:"+e),new i(e,r,o,s,a,h,c,t,n)},i.NEAREST_SAMPLINGMODE=1,i.BILINEAR_SAMPLINGMODE=2,i.TRILINEAR_SAMPLINGMODE=3,i.EXPLICIT_MODE=0,i.SPHERICAL_MODE=1,i.PLANAR_MODE=2,i.CUBIC_MODE=3,i.PROJECTION_MODE=4,i.SKYBOX_MODE=5,i.INVCUBIC_MODE=6,i.EQUIRECTANGULAR_MODE=7,i.FIXED_EQUIRECTANGULAR_MODE=8,i.CLAMP_ADDRESSMODE=0,i.WRAP_ADDRESSMODE=1,i.MIRROR_ADDRESSMODE=2,__decorate([e.serialize()],i.prototype,"url",void 0),__decorate([e.serialize()],i.prototype,"uOffset",void 0),__decorate([e.serialize()],i.prototype,"vOffset",void 0),__decorate([e.serialize()],i.prototype,"uScale",void 0),__decorate([e.serialize()],i.prototype,"vScale",void 0),__decorate([e.serialize()],i.prototype,"uAng",void 0),__decorate([e.serialize()],i.prototype,"vAng",void 0),__decorate([e.serialize()],i.prototype,"wAng",void 0),i})(e.BaseTexture);e.Texture=t;
})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){if(void 0===a&&(a=null),void 0===h&&(h=null),t.call(this,r),this.coordinatesMode=e.Texture.CUBIC_MODE,this.name=i,this.url=i,this._noMipmap=o,this.hasAlpha=!1,i||s){if(this._texture=this._getFromCache(i,o),!s){n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[];for(var c=0;c<n.length;c++)s.push(i+n[c]);this._extensions=n}this._files=s,this._texture?a&&(this._texture.isReady?e.Tools.SetImmediate((function(){return a()})):this._texture.onLoadedCallbacks.push(a)):r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this._texture=r.getEngine().createCubeTexture(i,r,s,o,a,h),this.isCube=!0,this._textureMatrix=e.Matrix.Identity()}}return __extends(i,t),i.CreateFromImages=function(e,t,r){return new i("",t,null,r,e)},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||(this._texture=this.getScene().getEngine().createCubeTexture(this.url,this.getScene(),this._files,this._noMipmap)))},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.Parse=function(t,i,r){var n=e.SerializationHelper.Parse((function(){return new e.CubeTexture(r+t.name,i,t.extensions)}),t,i);if(t.animations)for(var o=0;o<t.animations.length;o++){var s=t.animations[o];n.animations.push(e.Animation.Parse(s))}return n},i.prototype.clone=function(){var t=this;return e.SerializationHelper.Clone((function(){return new i(t.url,t.getScene(),t._extensions,t._noMipmap,t._files)}),this)},i})(e.BaseTexture);e.CubeTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c,l,u){void 0===s&&(s=!0),void 0===a&&(a=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=!0),void 0===u&&(u=!1),t.call(this,null,n,!o),this.isCube=h,this.renderList=new Array,this.renderParticles=!0,this.renderSprites=!1,this.coordinatesMode=e.Texture.PROJECTION_MODE,this.onAfterUnbindObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onClearObservable=new e.Observable,this._currentRefreshId=-1,this._refreshRate=1,this.name=i,this.isRenderTarget=!0,this._size=r,this._generateMipMaps=o,this._doNotChangeAspectRatio=s,c===e.Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE),h?(this._texture=n.getEngine().createRenderTargetCubeTexture(r,{generateMipMaps:o,samplingMode:c,generateDepthBuffer:l,generateStencilBuffer:u}),this.coordinatesMode=e.Texture.INVCUBIC_MODE,this._textureMatrix=e.Matrix.Identity()):this._texture=n.getEngine().createRenderTargetTexture(r,{generateMipMaps:o,type:a,samplingMode:c,generateDepthBuffer:l,generateStencilBuffer:u}),this._renderingManager=new e.RenderingManager(n)}return __extends(i,t),Object.defineProperty(i,"REFRESHRATE_RENDER_ONCE",{get:function(){return i._REFRESHRATE_RENDER_ONCE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"REFRESHRATE_RENDER_ONEVERYFRAME",{get:function(){return i._REFRESHRATE_RENDER_ONEVERYFRAME},enumerable:!0,configurable:!0}),Object.defineProperty(i,"REFRESHRATE_RENDER_ONEVERYTWOFRAMES",{get:function(){return i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onAfterUnbind",{set:function(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onClear",{set:function(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)},enumerable:!0,configurable:!0}),i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.isReady=function(){return!!this.getScene().renderTargetsEnabled&&t.prototype.isReady.call(this)},i.prototype.getRenderSize=function(){return this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this._size*e;this.resize(t,this._generateMipMaps)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e,t){this.releaseInternalTexture(),this.isCube?this._texture=this.getScene().getEngine().createRenderTargetCubeTexture(e):this._texture=this.getScene().getEngine().createRenderTargetTexture(e,t)},i.prototype.render=function(e,t){var i=this.getScene();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(!0)),this._waitingRenderList){this.renderList=[];for(var r=0;r<this._waitingRenderList.length;r++){var n=this._waitingRenderList[r];this.renderList.push(i.getMeshByID(n))}delete this._waitingRenderList}if(this.renderListPredicate){this.renderList.splice(0);for(var o=this.getScene().meshes,r=0;r<o.length;r++){var s=o[r];this.renderListPredicate(s)&&this.renderList.push(s)}}if(!this.renderList||0!==this.renderList.length){this._renderingManager.reset();for(var a=this.renderList?this.renderList:i.getActiveMeshes().data,h=this.renderList?this.renderList.length:i.getActiveMeshes().length,c=i.getRenderId(),l=0;l<h;l++){var s=a[l];if(s){if(!s.isReady()){this.resetRefreshCounter();continue}if(s._preActivateForIntermediateRendering(c),s.isEnabled()&&s.isVisible&&s.subMeshes&&0!==(s.layerMask&i.activeCamera.layerMask)){s._activate(c);for(var u=0;u<s.subMeshes.length;u++){var f=s.subMeshes[u];i._activeIndices.addCount(f.indexCount,!1),this._renderingManager.dispatch(f)}}}}if(this.isCube)for(var d=0;d<6;d++)this.renderToTarget(d,a,h,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,a,h,e,t);this.onAfterUnbindObservable.notifyObservers(this),this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),i.resetCachedMaterial()}},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene(),a=s.getEngine();n&&s.postProcessManager._prepareFrame(this._texture)||(this.isCube?a.bindFramebuffer(this._texture,t):a.bindFramebuffer(this._texture)),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this.onAfterRenderObservable.notifyObservers(t),o&&e.Tools.DumpFramebuffer(this._size,this._size,a),this.isCube&&5!==t||(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),a.unBindFramebuffer(this._texture,this.isCube))},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t)},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.renderList=this.renderList.slice(0),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);e.renderTargetSize=this.getRenderSize(),e.renderList=[];for(var i=0;i<this.renderList.length;i++)e.renderList.push(this.renderList[i].id);return e},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){void 0===a&&(a=!0),void 0===h&&(h=!1),t.call(this,null,o,!a),this.isCube=h,this.isEnabled=!0,this._currentRefreshId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._textures=new Array,this._floats=new Array,this._floatsArrays={},this._colors3=new Array,this._colors4=new Array,this._vectors2=new Array,this._vectors3=new Array,this._matrices=new Array,this._fallbackTextureUsed=!1,o._proceduralTextures.push(this),this.name=i,this.isRenderTarget=!0,this._size=r,this._generateMipMaps=a,this.setFragment(n),this._fallbackTexture=s;var c=o.getEngine();h?(this._texture=c.createRenderTargetCubeTexture(r,{generateMipMaps:a}),this.setFloat("face",0)):this._texture=c.createRenderTargetTexture(r,a);var l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(c,l,e.VertexBuffer.PositionKind,(!1),(!1),2);var u=[];u.push(0),u.push(1),u.push(2),u.push(0),u.push(2),u.push(3),this._indexBuffer=c.createIndexBuffer(u)}return __extends(i,t),i.prototype.reset=function(){if(void 0!==this._effect){var e=this.getScene().getEngine();e._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this.getScene().getEngine();return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",null,null,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture.references++),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this.getScene().getEngine().createRenderTargetTexture(e,t))},i.prototype._checkUniform=function(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(e){var t=this.getScene(),i=t.getEngine();i.enableEffect(this._effect),i.setState(!1);for(var r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);if(i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this.isCube)for(var o=0;o<6;o++)i.bindFramebuffer(this._texture,o),this._effect.setFloat("face",o),i.clear(t.clearColor,!0,!0,!0),i.draw(!0,0,6),5===o&&i.generateMipMapsForCubemap(this._texture);else i.bindFramebuffer(this._texture),i.clear(t.clearColor,!0,!0,!0),i.draw(!0,0,6);i.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene()._proceduralTextures.indexOf(this);i>=0&&this.getScene()._proceduralTextures.splice(i,1);var r=this._vertexBuffers[e.VertexBuffer.PositionKind];r&&(r.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this.getScene().getEngine()._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)},i})(e.Texture);e.ProceduralTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,r,n,o,!0),this.mirrorPlane=new e.Plane(0,1,0,1),this._transformMatrix=e.Matrix.Zero(),this._mirrorMatrix=e.Matrix.Zero(),this.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(s.mirrorPlane,s._mirrorMatrix),s._savedViewMatrix=n.getViewMatrix(),s._mirrorMatrix.multiplyToRef(s._savedViewMatrix,s._transformMatrix),n.setTransformMatrix(s._transformMatrix,n.getProjectionMatrix()),n.clipPlane=s.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.position,s._mirrorMatrix)})),this.onAfterRenderObservable.add((function(){n.setTransformMatrix(s._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane}))}return __extends(i,t),i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.mirrorPlane=this.mirrorPlane.clone(),t.renderList=this.renderList.slice(0),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i})(e.RenderTargetTexture);e.MirrorTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,r,n,o,!0),this.refractionPlane=new e.Plane(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),this.onAfterRenderObservable.add((function(){delete n.clipPlane}))}return __extends(i,t),i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.refractionPlane=this.refractionPlane.clone(),t.renderList=this.renderList.slice(0),t.depth=this.depth,t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,n,!o),this.name=i,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=o,r.getContext?(this._canvas=r,this._texture=n.getEngine().createDynamicTexture(r.width,r.height,o,s)):(this._canvas=document.createElement("canvas"),r.width?this._texture=n.getEngine().createDynamicTexture(r.width,r.height,o,s):this._texture=n.getEngine().createDynamicTexture(r,r,o,s));var a=this.getSize();this._canvas.width=a.width,this._canvas.height=a.height,this._context=this._canvas.getContext("2d")}return __extends(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._canvas.width=t.width,this._canvas.height=t.height,this.releaseInternalTexture(),this._texture=this.getScene().getEngine().createDynamicTexture(t.width,t.height,this._generateMipMaps,this._samplingMode)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e){this.getScene().getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var h=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,h.width,h.height)),this._context.font=r,null===t){var c=this._context.measureText(e);t=(h.width-c.width)/2}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t},i})(e.Texture);e.DynamicTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,n,!o,s),this._autoLaunch=!0;var c;this.name=i,r instanceof HTMLVideoElement?this.video=r:(c=r,this.video=document.createElement("video"),this.video.autoplay=!1,this.video.loop=!0),this._generateMipMaps=o,this._samplingMode=a,e.Tools.IsExponentOfTwo(this.video.videoWidth)&&e.Tools.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=e.Texture.WRAP_ADDRESSMODE,this.wrapV=e.Texture.WRAP_ADDRESSMODE):(this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),c?(this.video.addEventListener("canplaythrough",(function(){h._createTexture()})),c.forEach((function(e){var t=document.createElement("source");t.src=e,h.video.appendChild(t)}))):this._createTexture(),this._lastUpdate=e.Tools.Now}return __extends(i,t),i.prototype._createTexture=function(){this._texture=this.getScene().getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this._samplingMode),this._texture.isReady=!0},i.prototype.update=function(){this._autoLaunch&&(this._autoLaunch=!1,this.video.play());var t=e.Tools.Now;return!(t-this._lastUpdate<15||this.video.readyState!==this.video.HAVE_ENOUGH_DATA)&&(this._lastUpdate=t,this.getScene().getEngine().updateVideoTexture(this._texture,this.video,this._invertY),!0)},i})(e.Texture);e.VideoTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){t.call(this,e,r,null,n,o,s),this._animate=!0,this._time=0,this._texturePath=i,this.loadJson(i),this.refreshRate=1}return __extends(i,t),i.prototype.loadJson=function(t){function i(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{n.setFragment(n._texturePath)}catch(i){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}}var r=this,n=this,o=t+"/config.json",s=new XMLHttpRequest;s.open("GET",o,!0),s.addEventListener("load",(function(){if(200===s.status||e.Tools.ValidateXHRData(s,1))try{r._config=JSON.parse(s.response),r.updateShaderUniforms(),r.updateTextures(),r.setFragment(r._texturePath+"/custom"),r._animate=r._config.animate,r.refreshRate=r._config.refreshrate}catch(t){i()}else i()}),!1),s.addEventListener("error",(function(){i()}),!1);try{s.send()}catch(a){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){var i=this._textures[e];if(!i.isReady())return!1}return!0},i.prototype.render=function(e){this._animate&&(this._time+=.03*this.getScene().getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t<this._config.sampler2Ds.length;t++)this.setTexture(this._config.sampler2Ds[t].sample2Dname,new e.Texture(this._texturePath+"/"+this._config.sampler2Ds[t].textureRelativeUrl,this.getScene()))},i.prototype.updateShaderUniforms=function(){if(this._config)for(var t=0;t<this._config.uniforms.length;t++){var i=this._config.uniforms[t];switch(i.type){case"float":this.setFloat(i.name,i.value);break;case"color3":this.setColor3(i.name,new e.Color3(i.r,i.g,i.b));break;case"color4":this.setColor4(i.name,new e.Color4(i.r,i.g,i.b,i.a));break;case"vector2":this.setVector2(i.name,new e.Vector2(i.x,i.y));break;case"vector3":this.setVector3(i.name,new e.Vector3(i.x,i.y,i.z))}}this.setFloat("time",this._time)},Object.defineProperty(i.prototype,"animate",{get:function(){return this._animate},set:function(e){this._animate=e},enumerable:!0,configurable:!0}),i})(e.ProceduralTexture);e.CustomProceduralTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._defines={},this._currentRank=32,this._maxRank=-1}return t.prototype.addFallback=function(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},t.prototype.addCPUSkinningFallback=function(e,t){this._meshRank=e,this._mesh=t,e>this._maxRank&&(this._maxRank=e)},Object.defineProperty(t.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),t.prototype.reduce=function(t){for(var i=this._defines[this._currentRank],r=0;r<i.length;r++)t=t.replace("#define "+i[r],"");return this._mesh&&this._currentRank===this._meshRank&&(this._mesh.computeBonesUsingShaders=!1,t=t.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),e.Tools.Log("Falling back to CPU skinning for "+this._mesh.name)),this._currentRank++,t},t})();e.EffectFallbacks=t;var i=(function(){function t(e,t,i,r,n,o,s,a,h,c){var l=this;this._isReady=!1,this._compilationError="",this._valueCache={},this._engine=n,this.name=e,this.defines=o,this._uniformsNames=i.concat(r),this._samplers=r,this._attributesNames=t,this.onError=h,this.onCompiled=a,this._indexParameters=c;var u,f;e.vertexElement?(u=document.getElementById(e.vertexElement),u||(u=e.vertexElement)):u=e.vertex||e,e.fragmentElement?(f=document.getElementById(e.fragmentElement),f||(f=e.fragmentElement)):f=e.fragment||e,this._loadVertexShader(u,(function(e){l._processIncludes(e,(function(e){l._loadFragmentShader(f,(function(i){l._processIncludes(i,(function(i){l._prepareEffect(e,i,t,o,s)}))}))}))}))}return t.prototype.isReady=function(){return this._isReady},t.prototype.getProgram=function(){return this._program},t.prototype.getAttributesNames=function(){return this._attributesNames},t.prototype.getAttributeLocation=function(e){return this._attributes[e]},t.prototype.getAttributeLocationByName=function(e){var t=this._attributesNames.indexOf(e);return this._attributes[t]},t.prototype.getAttributesCount=function(){return this._attributes.length},t.prototype.getUniformIndex=function(e){return this._uniformsNames.indexOf(e)},t.prototype.getUniform=function(e){return this._uniforms[this._uniformsNames.indexOf(e)]},t.prototype.getSamplers=function(){return this._samplers},t.prototype.getCompilationError=function(){return this._compilationError},t.prototype.getVertexShaderSource=function(){return this._engine.getVertexShaderSource(this._program)},t.prototype.getFragmentShaderSource=function(){return this._engine.getFragmentShaderSource(this._program)},t.prototype._loadVertexShader=function(i,r){if(i instanceof HTMLElement){var n=e.Tools.GetDOMTextContent(i);return void r(n)}if("base64:"===i.substr(0,7)){var o=window.atob(i.substr(7));return void r(o)}if(t.ShadersStore[i+"VertexShader"])return void r(t.ShadersStore[i+"VertexShader"]);var s;s="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,e.Tools.LoadFile(s+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(i instanceof HTMLElement){var n=e.Tools.GetDOMTextContent(i);return void r(n)}if("base64:"===i.substr(0,7)){var o=window.atob(i.substr(7));return void r(o)}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var s;s="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,e.Tools.LoadFile(s+".fragment.fx",r)},t.prototype._dumpShadersName=function(){this.name.vertexElement?(e.Tools.Error("Vertex shader:"+this.name.vertexElement),e.Tools.Error("Fragment shader:"+this.name.fragmentElement)):this.name.vertex?(e.Tools.Error("Vertex shader:"+this.name.vertex),e.Tools.Error("Fragment shader:"+this.name.fragment)):(e.Tools.Error("Vertex shader:"+this.name),e.Tools.Error("Fragment shader:"+this.name))},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var h=s[1];if(!t.IncludesShadersStore[h]){var c=e.Engine.ShadersRepository+"ShadersInclude/"+h+".fx";return void e.Tools.LoadFile(c,(function(e){t.IncludesShadersStore[h]=e,n._processIncludes(a,r)}))}var l=t.IncludesShadersStore[h];if(s[2])for(var u=s[3].split(","),f=0;f<u.length;f+=2){var d=new RegExp(u[f],"g"),p=u[f+1];l=l.replace(d,p)}if(s[4]){var m=s[5];if(m.indexOf("..")!==-1){var g=m.split(".."),_=parseInt(g[0]),v=parseInt(g[1]),y=l.slice(0);l="",isNaN(v)&&(v=this._indexParameters[g[1]]);for(var x=_;x<=v;x++)l+=y.replace(/\{X\}/g,x)+"\n"}else l=l.replace(/\{X\}/g,m)}a=a.replace(s[0],l),s=o.exec(i)}r(a)},t.prototype._processPrecision=function(e){return e.indexOf("precision highp float")===-1?e=this._engine.getCaps().highPrecisionShaderSupported?"precision highp float;\n"+e:"precision mediump float;\n"+e:this._engine.getCaps().highPrecisionShaderSupported||(e=e.replace("precision highp float","precision mediump float")),e},t.prototype._prepareEffect=function(t,i,r,n,o){try{var s=this._engine;t=this._processPrecision(t),i=this._processPrecision(i),this._program=s.createShaderProgram(t,i,n),this._uniforms=s.getUniforms(this._program,this._uniformsNames),this._attributes=s.getAttributes(this._program,r);var a;for(a=0;a<this._samplers.length;a++){var h=this.getUniform(this._samplers[a]);null==h&&(this._samplers.splice(a,1),a--)}s.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this)}catch(c){this._compilationError=c.message,e.Tools.Error("Unable to compile effect: "),e.Tools.Error("Defines: "+n),e.Tools.Error("Error: "+this._compilationError),this._dumpShadersName(),o&&o.isMoreFallbacks?(e.Tools.Error("Trying next fallback."),n=o.reduce(n),this._prepareEffect(t,i,r,n,o)):this.onError&&this.onError(this,this._compilationError)}},Object.defineProperty(t.prototype,"isSupported",{get:function(){return""===this._compilationError},enumerable:!0,configurable:!0}),t.prototype._bindTexture=function(e,t){this._engine._bindTexture(this._samplers.indexOf(e),t)},t.prototype.setTexture=function(e,t){this._engine.setTexture(this._samplers.indexOf(e),this.getUniform(e),t)},t.prototype.setTextureArray=function(e,t){if(this._samplers.indexOf(e+"Ex")===-1)for(var i=this._samplers.indexOf(e),r=1;r<t.length;r++)this._samplers.splice(i+r,0,e+"Ex");this._engine.setTextureArray(this._samplers.indexOf(e),this.getUniform(e),t)},t.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers.indexOf(e),t)},t.prototype._cacheMatrix=function(t,i){var r=!1,n=this._valueCache[t];n&&n instanceof e.Matrix||(r=!0,n=new e.Matrix);for(var o=n.m,s=i.m,a=0;a<16;a++)o[a]!==s[a]&&(o[a]=s[a],r=!0);return this._valueCache[t]=n,r},t.prototype._cacheFloat2=function(e,t,i){var r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;var n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n},t.prototype._cacheFloat3=function(e,t,i,r){var n=this._valueCache[e];if(!n)return n=[t,i,r],this._valueCache[e]=n,!0;var o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==r&&(n[2]=r,o=!0),o},t.prototype._cacheFloat4=function(e,t,i,r,n){var o=this._valueCache[e];if(!o)return o=[t,i,r,n],this._valueCache[e]=o,!0;var s=!1;return o[0]!==t&&(o[0]=t,s=!0),o[1]!==i&&(o[1]=i,s=!0),o[2]!==r&&(o[2]=r,s=!0),o[3]!==n&&(o[3]=n,s=!0),s},t.prototype.setIntArray=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray(this.getUniform(e),t),this},t.prototype.setIntArray2=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray2(this.getUniform(e),t),this},t.prototype.setIntArray3=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray3(this.getUniform(e),t),this},t.prototype.setIntArray4=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray4(this.getUniform(e),t),this},t.prototype.setFloatArray=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray(this.getUniform(e),t),this},t.prototype.setFloatArray2=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray2(this.getUniform(e),t),this},t.prototype.setFloatArray3=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray3(this.getUniform(e),t),this},t.prototype.setFloatArray4=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray4(this.getUniform(e),t),this},t.prototype.setArray=function(e,t){return this._valueCache[e]=null,this._engine.setArray(this.getUniform(e),t),this},t.prototype.setArray2=function(e,t){return this._valueCache[e]=null,this._engine.setArray2(this.getUniform(e),t),this},t.prototype.setArray3=function(e,t){return this._valueCache[e]=null,this._engine.setArray3(this.getUniform(e),t),this},t.prototype.setArray4=function(e,t){return this._valueCache[e]=null,this._engine.setArray4(this.getUniform(e),t),this},t.prototype.setMatrices=function(e,t){return this._valueCache[e]=null,this._engine.setMatrices(this.getUniform(e),t),this},t.prototype.setMatrix=function(e,t){return this._cacheMatrix(e,t)&&this._engine.setMatrix(this.getUniform(e),t),this},t.prototype.setMatrix3x3=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix3x3(this.getUniform(e),t),this},t.prototype.setMatrix2x2=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix2x2(this.getUniform(e),t),this},t.prototype.setFloat=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setFloat(this.getUniform(e),t),this)},t.prototype.setBool=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setBool(this.getUniform(e),t?1:0),
this)},t.prototype.setVector2=function(e,t){return this._cacheFloat2(e,t.x,t.y)&&this._engine.setFloat2(this.getUniform(e),t.x,t.y),this},t.prototype.setFloat2=function(e,t,i){return this._cacheFloat2(e,t,i)&&this._engine.setFloat2(this.getUniform(e),t,i),this},t.prototype.setVector3=function(e,t){return this._cacheFloat3(e,t.x,t.y,t.z)&&this._engine.setFloat3(this.getUniform(e),t.x,t.y,t.z),this},t.prototype.setFloat3=function(e,t,i,r){return this._cacheFloat3(e,t,i,r)&&this._engine.setFloat3(this.getUniform(e),t,i,r),this},t.prototype.setVector4=function(e,t){return this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&this._engine.setFloat4(this.getUniform(e),t.x,t.y,t.z,t.w),this},t.prototype.setFloat4=function(e,t,i,r,n){return this._cacheFloat4(e,t,i,r,n)&&this._engine.setFloat4(this.getUniform(e),t,i,r,n),this},t.prototype.setColor3=function(e,t){return this._cacheFloat3(e,t.r,t.g,t.b)&&this._engine.setColor3(this.getUniform(e),t),this},t.prototype.setColor4=function(e,t,i){return this._cacheFloat4(e,t.r,t.g,t.b,i)&&this._engine.setColor4(this.getUniform(e),t,i),this},t.ShadersStore={},t.IncludesShadersStore={},t})();e.Effect=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.PrepareDefinesForLights=function(t,i,r,n){void 0===n&&(n=4);for(var o=0,s=!1,a=!1,h=!1,c=!1,l=0;l<t.lights.length;l++){var u=t.lights[l];if(u.isEnabled()){if(u._excludedMeshesIds.length>0){for(var f=0;f<u._excludedMeshesIds.length;f++){var d=t.getMeshByID(u._excludedMeshesIds[f]);d&&u.excludedMeshes.push(d)}u._excludedMeshesIds=[]}if(u._includedOnlyMeshesIds.length>0){for(var p=0;p<u._includedOnlyMeshesIds.length;p++){var m=t.getMeshByID(u._includedOnlyMeshesIds[p]);m&&u.includedOnlyMeshes.push(m)}u._includedOnlyMeshesIds=[]}if(u.canAffectMesh(i)){s=!0,void 0===r["LIGHT"+o]&&(a=!0),r["LIGHT"+o]=!0;var g;if(g=u instanceof e.SpotLight?"SPOTLIGHT"+o:u instanceof e.HemisphericLight?"HEMILIGHT"+o:u instanceof e.PointLight?"POINTLIGHT"+o:"DIRLIGHT"+o,void 0===r[g]&&(a=!0),r[g]=!0,u.specular.equalsFloats(0,0,0)||void 0===r.SPECULARTERM||(r.SPECULARTERM=!0),t.shadowsEnabled){var _=u.getShadowGenerator();i&&i.receiveShadows&&_&&(void 0===r["SHADOW"+o]&&(a=!0),r["SHADOW"+o]=!0,r.SHADOWS=!0,(_.useVarianceShadowMap||_.useBlurVarianceShadowMap)&&(void 0===r["SHADOWVSM"+o]&&(a=!0),r["SHADOWVSM"+o]=!0),_.usePoissonSampling&&(void 0===r["SHADOWPCF"+o]&&(a=!0),r["SHADOWPCF"+o]=!0),h=!0)}if(u.lightmapMode!=e.Light.LIGHTMAP_DEFAULT&&(c=!0,void 0===r["LIGHTMAPEXCLUDED"+o]&&(a=!0),void 0===r["LIGHTMAPNOSPECULAR"+o]&&(a=!0),r["LIGHTMAPEXCLUDED"+o]=!0,u.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY&&(r["LIGHTMAPNOSPECULAR"+o]=!0)),o++,o===n)break}}}var v=t.getEngine().getCaps();return h&&v.textureFloat&&v.textureFloatLinearFiltering&&v.textureFloatRender&&(void 0===r.SHADOWFULLFLOAT&&(a=!0),r.SHADOWFULLFLOAT=!0),void 0===r.LIGHTMAPEXCLUDED&&(a=!0),c&&(r.LIGHTMAPEXCLUDED=!0),a&&r.rebuild(),s},t.PrepareUniformsAndSamplersList=function(e,t,i,r){void 0===r&&(r=4);for(var n=0;n<r&&i["LIGHT"+n];n++)e.push("vLightData"+n,"vLightDiffuse"+n,"vLightSpecular"+n,"vLightDirection"+n,"vLightGround"+n,"lightMatrix"+n,"shadowsInfo"+n),t.push("shadowSampler"+n)},t.HandleFallbacksForShadows=function(e,t,i){void 0===i&&(i=4);for(var r=0;r<i&&e["LIGHT"+r];r++)r>0&&t.addFallback(r,"LIGHT"+r),e["SHADOW"+r]&&t.addFallback(0,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(0,"SHADOWPCF"+r),e["SHADOWVSM"+r]&&t.addFallback(0,"SHADOWVSM"+r)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n,o){var s=e.getShadowGenerator();return i.receiveShadows&&s&&(e.needCube()?o||(o=!0,n.setFloat2("depthValues",t.activeCamera.minZ,t.activeCamera.maxZ)):n.setMatrix("lightMatrix"+r,s.getTransformMatrix()),n.setTexture("shadowSampler"+r,s.getShadowMapForRendering()),n.setFloat3("shadowsInfo"+r,s.getDarkness(),s.blurScale/s.getShadowMap().getSize().width,s.bias)),o},t.BindLightProperties=function(t,i,r){t instanceof e.PointLight?t.transferToEffect(i,"vLightData"+r):t instanceof e.DirectionalLight?t.transferToEffect(i,"vLightData"+r):t instanceof e.SpotLight?t.transferToEffect(i,"vLightData"+r,"vLightDirection"+r):t instanceof e.HemisphericLight&&t.transferToEffect(i,"vLightData"+r,"vLightGround"+r)},t.BindLights=function(i,r,n,o,s){void 0===s&&(s=4);for(var a=0,h=!1,c=0;c<i.lights.length;c++){var l=i.lights[c];if(l.isEnabled()&&l.canAffectMesh(r)&&(t.BindLightProperties(l,n,a),l.diffuse.scaleToRef(l.intensity,e.Tmp.Color3[0]),n.setColor4("vLightDiffuse"+a,e.Tmp.Color3[0],l.range),o.SPECULARTERM&&(l.specular.scaleToRef(l.intensity,e.Tmp.Color3[1]),n.setColor3("vLightSpecular"+a,e.Tmp.Color3[1])),i.shadowsEnabled&&(h=this.BindLightShadow(l,i,r,a,n,h)),a++,a===s))break}},t.BindFogParameters=function(t,i,r){t.fogEnabled&&i.applyFog&&t.fogMode!==e.Scene.FOGMODE_NONE&&(r.setFloat4("vFogInfos",t.fogMode,t.fogStart,t.fogEnd,t.fogDensity),r.setColor3("vFogColor",t.fogColor))},t.BindBonesParameters=function(e,t){if(e&&e.useBones&&e.computeBonesUsingShaders){var i=e.skeleton.getTransformMatrices(e);i&&t.setMatrices("mBones",i)}},t.BindLogDepth=function(e,t,i){e.LOGARITHMICDEPTH&&t.setFloat("logarithmicDepthConstant",2/(Math.log(i.activeCamera.maxZ+1)/Math.LN2))},t.BindClipPlane=function(e,t){if(t.clipPlane){var i=t.clipPlane;e.setFloat4("vClipPlane",i.normal.x,i.normal.y,i.normal.z,i.d)}},t})();e.MaterialHelper=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor,e.rightColor=this.rightColor,e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e.prototype.rebuild=function(){this._keys&&delete this._keys,this._keys=Object.keys(this)},e.prototype.isEqual=function(e){if(this._keys.length!==e._keys.length)return!1;for(var t=0;t<this._keys.length;t++){var i=this._keys[t];if(this[i]!==e[i])return!1}return!0},e.prototype.cloneTo=function(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(var t=0;t<this._keys.length;t++){var i=this._keys[t];e[i]=this[i]}},e.prototype.reset=function(){for(var e=0;e<this._keys.length;e++){var t=this._keys[e];"number"==typeof this[t]?this[t]=0:this[t]=!1}},e.prototype.toString=function(){for(var e="",t=0;t<this._keys.length;t++){var i=this._keys[t];"number"==typeof this[i]?e+="#define "+i+" "+this[i]+"\n":this[i]&&(e+="#define "+i+"\n")}return e},e})();e.MaterialDefines=t;var i=(function(){function t(i,r,n){this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this.alpha=1,this.backFaceCulling=!0,this.doNotSerialize=!1,this.onDisposeObservable=new e.Observable,this.onBindObservable=new e.Observable,this.onUnBindObservable=new e.Observable,this.alphaMode=e.Engine.ALPHA_COMBINE,this.disableDepthWrite=!1,this.fogEnabled=!0,this.pointSize=1,this.zOffset=0,this._wasPreviouslyReady=!1,this._fillMode=t.TriangleFillMode,this.name=i,this.id=i,this._scene=r,r.useRightHandedSystem?this.sideOrientation=t.ClockWiseSideOrientation:this.sideOrientation=t.CounterClockWiseSideOrientation,n||r.materials.push(this)}return Object.defineProperty(t,"TriangleFillMode",{get:function(){return t._TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WireFrameFillMode",{get:function(){return t._WireFrameFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PointFillMode",{get:function(){return t._PointFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ClockWiseSideOrientation",{get:function(){return t._ClockWiseSideOrientation},enumerable:!0,configurable:!0}),Object.defineProperty(t,"CounterClockWiseSideOrientation",{get:function(){return t._CounterClockWiseSideOrientation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBind",{set:function(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wireframe",{get:function(){return this._fillMode===t.WireFrameFillMode},set:function(e){this._fillMode=e?t.WireFrameFillMode:t.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pointsCloud",{get:function(){return this._fillMode===t.PointFillMode},set:function(e){this._fillMode=e?t.PointFillMode:t.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fillMode",{get:function(){return this._fillMode},set:function(e){this._fillMode=e},enumerable:!0,configurable:!0}),t.prototype.toString=function(e){var t="Name: "+this.name;return t},Object.defineProperty(t.prototype,"isFrozen",{get:function(){return this.checkReadyOnlyOnce},enumerable:!0,configurable:!0}),t.prototype.freeze=function(){this.checkReadyOnlyOnce=!0},t.prototype.unfreeze=function(){this.checkReadyOnlyOnce=!1},t.prototype.isReady=function(e,t){return!0},t.prototype.getEffect=function(){return this._effect},t.prototype.getScene=function(){return this._scene},t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.markDirty=function(){this._wasPreviouslyReady=!1},t.prototype._preBind=function(){var e=this._scene.getEngine(),i=this.sideOrientation===t.ClockWiseSideOrientation;e.enableEffect(this._effect),e.setState(this.backFaceCulling,this.zOffset,!1,i)},t.prototype.bind=function(e,t){if(this._scene._cachedMaterial=this,this.onBindObservable.notifyObservers(t),this.disableDepthWrite){var i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}},t.prototype.bindOnlyWorldMatrix=function(e){},t.prototype.unbind=function(){if(this.onUnBindObservable.notifyObservers(this),this.disableDepthWrite){var e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}},t.prototype.clone=function(e){return null},t.prototype.getBindedMeshes=function(){for(var e=new Array,t=0;t<this._scene.meshes.length;t++){var i=this._scene.meshes[t];i.material===this&&e.push(i)}return e},t.prototype.dispose=function(e,t){this.getScene().stopAnimation(this);var i=this._scene.materials.indexOf(this);for(i>=0&&this._scene.materials.splice(i,1),e&&this._effect&&(this._scene.getEngine()._releaseEffect(this._effect),this._effect=null),i=0;i<this._scene.meshes.length;i++){var r=this._scene.meshes[i];r.material===this&&(r.material=null)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBindObservable.clear(),this.onUnBindObservable.clear()},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.ParseMultiMaterial=function(t,i){var r=new e.MultiMaterial(t.name,i);r.id=t.id,e.Tags.AddTagsTo(r,t.tags);for(var n=0;n<t.materials.length;n++){var o=t.materials[n];o?r.subMaterials.push(i.getMaterialByID(o)):r.subMaterials.push(null)}return r},t.Parse=function(t,i,r){if(!t.customType)return e.StandardMaterial.Parse(t,i,r);var n=e.Tools.Instantiate(t.customType);return n.Parse(t,i,r)},t._TriangleFillMode=0,t._WireFrameFillMode=1,t._PointFillMode=2,t._ClockWiseSideOrientation=0,t._CounterClockWiseSideOrientation=1,__decorate([e.serialize()],t.prototype,"id",void 0),__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"checkReadyOnEveryCall",void 0),__decorate([e.serialize()],t.prototype,"checkReadyOnlyOnce",void 0),__decorate([e.serialize()],t.prototype,"state",void 0),__decorate([e.serialize()],t.prototype,"alpha",void 0),__decorate([e.serialize()],t.prototype,"backFaceCulling",void 0),__decorate([e.serialize()],t.prototype,"sideOrientation",void 0),__decorate([e.serialize()],t.prototype,"alphaMode",void 0),__decorate([e.serialize()],t.prototype,"disableDepthWrite",void 0),__decorate([e.serialize()],t.prototype,"fogEnabled",void 0),__decorate([e.serialize()],t.prototype,"pointSize",void 0),__decorate([e.serialize()],t.prototype,"zOffset",void 0),__decorate([e.serialize()],t.prototype,"wireframe",null),__decorate([e.serialize()],t.prototype,"pointsCloud",null),__decorate([e.serialize()],t.prototype,"fillMode",null),t})();e.Material=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(){e.call(this),this.DIFFUSE=!1,this.AMBIENT=!1,this.OPACITY=!1,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.SPECULAR=!1,this.BUMP=!1,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.ALPHATEST=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.INVERTNORMALMAPX=!1,this.INVERTNORMALMAPY=!1,this.SHADOWFULLFLOAT=!1,this.CAMERACOLORGRADING=!1,this.CAMERACOLORCURVES=!1,this.rebuild()}return __extends(t,e),t})(e.MaterialDefines),i=(function(i){function r(r,n){var o=this;i.call(this,r,n),this.ambientColor=new e.Color3(0,0,0),this.diffuseColor=new e.Color3(1,1,1),this.specularColor=new e.Color3(1,1,1),this.emissiveColor=new e.Color3(0,0,0),this.specularPower=64,this.useAlphaFromDiffuseTexture=!1,this.useEmissiveAsIllumination=!1,this.linkEmissiveWithDiffuse=!1,this.useReflectionFresnelFromSpecular=!1,this.useSpecularOverAlpha=!1,this.useReflectionOverAlpha=!1,this.disableLighting=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.useLightmapAsShadowmap=!1,this.useGlossinessFromSpecularMapAlpha=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.cameraColorGradingTexture=null,this.cameraColorCurves=null,this._renderTargets=new e.SmartArray(16),this._worldViewProjectionMatrix=e.Matrix.Zero(),this._globalAmbientColor=new e.Color3(0,0,0),this._defines=new t,this._cachedDefines=new t,this._cachedDefines.BonesPerMesh=-1,this.getRenderTargetTextures=function(){return o._renderTargets.reset(),o.reflectionTexture&&o.reflectionTexture.isRenderTarget&&o._renderTargets.push(o.reflectionTexture),o.refractionTexture&&o.refractionTexture.isRenderTarget&&o._renderTargets.push(o.refractionTexture),o._renderTargets}}return __extends(r,i),Object.defineProperty(r.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),r.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this.opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled},r.prototype.needAlphaTesting=function(){return null!=this.diffuseTexture&&this.diffuseTexture.hasAlpha},r.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this.diffuseTexture&&this.diffuseTexture.hasAlpha&&this.useAlphaFromDiffuseTexture},r.prototype.getAlphaTestTexture=function(){return this.diffuseTexture},r.prototype._checkCache=function(e,t,i){return!t||this._defines.INSTANCES===i&&!(!t._materialDefines||!t._materialDefines.isEqual(this._defines))},r.prototype.isReady=function(i,n){if(this.isFrozen&&this._wasPreviouslyReady)return!0;var o=this.getScene(),s=o.getEngine(),a=!1,h=!1;if(this._defines.reset(),o.lightsEnabled&&!this.disableLighting&&(h=e.MaterialHelper.PrepareDefinesForLights(o,i,this._defines,this.maxSimultaneousLights)),!this.checkReadyOnEveryCall&&this._renderId===o.getRenderId()&&this._checkCache(o,i,n))return!0;if(o.texturesEnabled){if(this.diffuseTexture&&r.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;a=!0,this._defines.DIFFUSE=!0}if(this.ambientTexture&&r.AmbientTextureEnabled){if(!this.ambientTexture.isReady())return!1;a=!0,this._defines.AMBIENT=!0}if(this.opacityTexture&&r.OpacityTextureEnabled){if(!this.opacityTexture.isReady())return!1;a=!0,this._defines.OPACITY=!0,this.opacityTexture.getAlphaFromRGB&&(this._defines.OPACITYRGB=!0)}if(this.reflectionTexture&&r.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady())return!1;switch(h=!0,this._defines.REFLECTION=!0,this.roughness>0&&(this._defines.ROUGHNESS=!0),this.useReflectionOverAlpha&&(this._defines.REFLECTIONOVERALPHA=!0),this.reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE&&(this._defines.INVERTCUBICMAP=!0),this._defines.REFLECTIONMAP_3D=this.reflectionTexture.isCube,this.reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:this._defines.REFLECTIONMAP_CUBIC=!0;break;case e.Texture.EXPLICIT_MODE:this._defines.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:this._defines.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:this._defines.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:this._defines.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:this._defines.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0}}if(this.emissiveTexture&&r.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady())return!1;a=!0,this._defines.EMISSIVE=!0}if(this.lightmapTexture&&r.LightmapTextureEnabled){if(!this.lightmapTexture.isReady())return!1;a=!0,this._defines.LIGHTMAP=!0,this._defines.USELIGHTMAPASSHADOWMAP=this.useLightmapAsShadowmap}if(this.specularTexture&&r.SpecularTextureEnabled){if(!this.specularTexture.isReady())return!1;a=!0,this._defines.SPECULAR=!0,this._defines.GLOSSINESS=this.useGlossinessFromSpecularMapAlpha}if(o.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&r.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;a=!0,this._defines.BUMP=!0,this.useParallax&&(this._defines.PARALLAX=!0,this.useParallaxOcclusion&&(this._defines.PARALLAXOCCLUSION=!0)),this.invertNormalMapX&&(this._defines.INVERTNORMALMAPX=!0),this.invertNormalMapY&&(this._defines.INVERTNORMALMAPY=!0)}if(this.refractionTexture&&r.RefractionTextureEnabled){if(!this.refractionTexture.isReady())return!1;a=!0,this._defines.REFRACTION=!0,this._defines.REFRACTIONMAP_3D=this.refractionTexture.isCube}if(this.cameraColorGradingTexture&&r.ColorGradingTextureEnabled){if(!this.cameraColorGradingTexture.isReady())return!1;this._defines.CAMERACOLORGRADING=!0}}if(o.clipPlane&&(this._defines.CLIPPLANE=!0),s.getAlphaTesting()&&(this._defines.ALPHATEST=!0),this._shouldUseAlphaFromDiffuseTexture()&&(this._defines.ALPHAFROMDIFFUSE=!0),this.useEmissiveAsIllumination&&(this._defines.EMISSIVEASILLUMINATION=!0),this.linkEmissiveWithDiffuse&&(this._defines.LINKEMISSIVEWITHDIFFUSE=!0),this.useLogarithmicDepth&&(this._defines.LOGARITHMICDEPTH=!0),this.cameraColorCurves&&(this._defines.CAMERACOLORCURVES=!0),(this.pointsCloud||o.forcePointsCloud)&&(this._defines.POINTSIZE=!0),o.fogEnabled&&i&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(this._defines.FOG=!0),r.FresnelEnabled&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled||this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled||this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled||this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled)&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._defines.DIFFUSEFRESNEL=!0),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&(this._defines.OPACITYFRESNEL=!0),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._defines.REFLECTIONFRESNEL=!0,this.useReflectionFresnelFromSpecular&&(this._defines.REFLECTIONFRESNELFROMSPECULAR=!0)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._defines.REFRACTIONFRESNEL=!0),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._defines.EMISSIVEFRESNEL=!0),h=!0,this._defines.FRESNEL=!0),this._defines.SPECULARTERM&&this.useSpecularOverAlpha&&(this._defines.SPECULAROVERALPHA=!0),i&&(h&&i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(this._defines.NORMAL=!0),a&&(i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(this._defines.UV1=!0),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(this._defines.UV2=!0)),i.useVertexColors&&i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(this._defines.VERTEXCOLOR=!0,i.hasVertexAlpha&&(this._defines.VERTEXALPHA=!0)),i.useBones&&i.computeBonesUsingShaders&&(this._defines.NUM_BONE_INFLUENCERS=i.numBoneInfluencers,this._defines.BonesPerMesh=i.skeleton.bones.length+1),n&&(this._defines.INSTANCES=!0)),!this._defines.isEqual(this._cachedDefines)){this._defines.cloneTo(this._cachedDefines),o.resetCachedMaterial();var c=new e.EffectFallbacks;this._defines.REFLECTION&&c.addFallback(0,"REFLECTION"),this._defines.SPECULAR&&c.addFallback(0,"SPECULAR"),this._defines.BUMP&&c.addFallback(0,"BUMP"),this._defines.PARALLAX&&c.addFallback(1,"PARALLAX"),this._defines.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),this._defines.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),this._defines.FOG&&c.addFallback(1,"FOG"),this._defines.POINTSIZE&&c.addFallback(0,"POINTSIZE"),this._defines.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(this._defines,c,this.maxSimultaneousLights),this._defines.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),this._defines.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),this._defines.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),this._defines.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),this._defines.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),this._defines.FRESNEL&&c.addFallback(4,"FRESNEL");var l=[e.VertexBuffer.PositionKind];this._defines.NORMAL&&l.push(e.VertexBuffer.NormalKind),this._defines.UV1&&l.push(e.VertexBuffer.UVKind),this._defines.UV2&&l.push(e.VertexBuffer.UV2Kind),this._defines.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,i,this._defines,c),e.MaterialHelper.PrepareAttributesForInstances(l,this._defines);var u="default",f=this._defines.toString(),d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","depthValues","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","logarithmicDepthConstant"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"];this._defines.CAMERACOLORCURVES&&e.ColorCurves.PrepareUniforms(d),this._defines.CAMERACOLORGRADING&&e.ColorGradingTexture.PrepareUniformsAndSamplers(d,p),e.MaterialHelper.PrepareUniformsAndSamplersList(d,p,this._defines,this.maxSimultaneousLights),this._effect=o.getEngine().createEffect(u,l,d,p,f,c,this.onCompiled,this.onError,{maxSimultaneousLights:this.maxSimultaneousLights-1})}return!!this._effect.isReady()&&(this._renderId=o.getRenderId(),this._wasPreviouslyReady=!0,i&&(i._materialDefines||(i._materialDefines=new t),this._defines.cloneTo(i._materialDefines)),!0)},r.prototype.unbind=function(){this.reflectionTexture&&this.reflectionTexture.isRenderTarget&&this._effect.setTexture("reflection2DSampler",null),this.refractionTexture&&this.refractionTexture.isRenderTarget&&this._effect.setTexture("refraction2DSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._effect.setMatrix("world",e)},r.prototype.bind=function(t,n){var o=this.getScene();if(this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(n,this._effect),o.getCachedMaterial()!==this){if(this._effect.setMatrix("viewProjection",o.getTransformMatrix()),r.FresnelEnabled&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._effect.setColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._effect.setColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._effect.setColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._effect.setColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._effect.setColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._effect.setColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._effect.setColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._effect.setColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._effect.setColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this.diffuseTexture&&r.DiffuseTextureEnabled&&(this._effect.setTexture("diffuseSampler",this.diffuseTexture),this._effect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._effect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.ambientTexture&&r.AmbientTextureEnabled&&(this._effect.setTexture("ambientSampler",this.ambientTexture),this._effect.setFloat2("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level),this._effect.setMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix())),this.opacityTexture&&r.OpacityTextureEnabled&&(this._effect.setTexture("opacitySampler",this.opacityTexture),this._effect.setFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level),this._effect.setMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix())),this.reflectionTexture&&r.ReflectionTextureEnabled&&(this.reflectionTexture.isCube?this._effect.setTexture("reflectionCubeSampler",this.reflectionTexture):this._effect.setTexture("reflection2DSampler",this.reflectionTexture),this._effect.setMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix()),this._effect.setFloat2("vReflectionInfos",this.reflectionTexture.level,this.roughness)),this.emissiveTexture&&r.EmissiveTextureEnabled&&(this._effect.setTexture("emissiveSampler",this.emissiveTexture),this._effect.setFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level),this._effect.setMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix())),this.lightmapTexture&&r.LightmapTextureEnabled&&(this._effect.setTexture("lightmapSampler",this.lightmapTexture),this._effect.setFloat2("vLightmapInfos",this.lightmapTexture.coordinatesIndex,this.lightmapTexture.level),this._effect.setMatrix("lightmapMatrix",this.lightmapTexture.getTextureMatrix())),this.specularTexture&&r.SpecularTextureEnabled&&(this._effect.setTexture("specularSampler",this.specularTexture),this._effect.setFloat2("vSpecularInfos",this.specularTexture.coordinatesIndex,this.specularTexture.level),this._effect.setMatrix("specularMatrix",this.specularTexture.getTextureMatrix())),this.bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._effect.setTexture("bumpSampler",this.bumpTexture),this._effect.setFloat3("vBumpInfos",this.bumpTexture.coordinatesIndex,1/this.bumpTexture.level,this.parallaxScaleBias),this._effect.setMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix())),this.refractionTexture&&r.RefractionTextureEnabled){var s=1;this.refractionTexture.isCube?this._effect.setTexture("refractionCubeSampler",this.refractionTexture):(this._effect.setTexture("refraction2DSampler",this.refractionTexture),this._effect.setMatrix("refractionMatrix",this.refractionTexture.getReflectionTextureMatrix()),this.refractionTexture.depth&&(s=this.refractionTexture.depth)),this._effect.setFloat4("vRefractionInfos",this.refractionTexture.level,this.indexOfRefraction,s,this.invertRefractionY?-1:1)}this.cameraColorGradingTexture&&r.ColorGradingTextureEnabled&&e.ColorGradingTexture.Bind(this.cameraColorGradingTexture,this._effect)}e.MaterialHelper.BindClipPlane(this._effect,o),this.pointsCloud&&this._effect.setFloat("pointSize",this.pointSize),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),this._effect.setVector3("vEyePosition",o._mirroredCameraPosition?o._mirroredCameraPosition:o.activeCamera.position),this._effect.setColor3("vAmbientColor",this._globalAmbientColor),this._defines.SPECULARTERM&&this._effect.setColor4("vSpecularColor",this.specularColor,this.specularPower),this._effect.setColor3("vEmissiveColor",this.emissiveColor)}o.getCachedMaterial()===this&&this.isFrozen||(this._effect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*n.visibility),o.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(o,n,this._effect,this._defines,this.maxSimultaneousLights),(o.fogEnabled&&n.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this.reflectionTexture||this.refractionTexture)&&this._effect.setMatrix("view",o.getViewMatrix()),e.MaterialHelper.BindFogParameters(o,n,this._effect),e.MaterialHelper.BindLogDepth(this._defines,this._effect,o),
this.cameraColorCurves&&e.ColorCurves.Bind(this.cameraColorCurves,this._effect)),i.prototype.bind.call(this,t,n)},r.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0&&e.push(this.ambientTexture),this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0&&e.push(this.opacityTexture),this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0&&e.push(this.reflectionTexture),this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0&&e.push(this.emissiveTexture),this.specularTexture&&this.specularTexture.animations&&this.specularTexture.animations.length>0&&e.push(this.specularTexture),this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this.lightmapTexture&&this.lightmapTexture.animations&&this.lightmapTexture.animations.length>0&&e.push(this.lightmapTexture),this.refractionTexture&&this.refractionTexture.animations&&this.refractionTexture.animations.length>0&&e.push(this.refractionTexture),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.animations&&this.cameraColorGradingTexture.animations.length>0&&e.push(this.cameraColorGradingTexture),e},r.prototype.dispose=function(e,t){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.ambientTexture&&this.ambientTexture.dispose(),this.opacityTexture&&this.opacityTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose(),this.emissiveTexture&&this.emissiveTexture.dispose(),this.specularTexture&&this.specularTexture.dispose(),this.bumpTexture&&this.bumpTexture.dispose(),this.lightmapTexture&&this.lightmapTexture.dispose(),this.refractionTexture&&this.refractionTexture.dispose(),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.dispose()),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.DiffuseTextureEnabled=!0,r.AmbientTextureEnabled=!0,r.OpacityTextureEnabled=!0,r.ReflectionTextureEnabled=!0,r.EmissiveTextureEnabled=!0,r.SpecularTextureEnabled=!0,r.BumpTextureEnabled=!0,r.FresnelEnabled=!0,r.LightmapTextureEnabled=!0,r.RefractionTextureEnabled=!0,r.ColorGradingTextureEnabled=!0,__decorate([e.serializeAsTexture()],r.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"ambientTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"specularTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),__decorate([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),__decorate([e.serialize()],r.prototype,"specularPower",void 0),__decorate([e.serialize()],r.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([e.serialize()],r.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize()],r.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([e.serialize()],r.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([e.serialize()],r.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useReflectionOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"disableLighting",void 0),__decorate([e.serialize()],r.prototype,"useParallax",void 0),__decorate([e.serialize()],r.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],r.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize()],r.prototype,"roughness",void 0),__decorate([e.serialize()],r.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],r.prototype,"invertRefractionY",void 0),__decorate([e.serialize()],r.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"diffuseFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"reflectionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"refractionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize()],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.serialize()],r.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapX",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapY",void 0),__decorate([e.serializeAsTexture()],r.prototype,"cameraColorGradingTexture",void 0),__decorate([e.serializeAsColorCurves()],r.prototype,"cameraColorCurves",void 0),__decorate([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.Material);e.StandardMaterial=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i){t.call(this,e,i,!0),this.subMaterials=new Array,i.multiMaterials.push(this)}return __extends(i,t),i.prototype.getSubMaterial=function(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.isReady=function(e){for(var t=0;t<this.subMaterials.length;t++){var i=this.subMaterials[t];if(i&&!this.subMaterials[t].isReady(e))return!1}return!0},i.prototype.clone=function(e,t){for(var r=new i(e,this.getScene()),n=0;n<this.subMaterials.length;n++){var o=null;o=t?this.subMaterials[n].clone(e+"-"+this.subMaterials[n].name):this.subMaterials[n],r.subMaterials.push(o)}return r},i.prototype.serialize=function(){var t={};t.name=this.name,t.id=this.id,t.tags=e.Tags.GetTags(this),t.materials=[];for(var i=0;i<this.subMaterials.length;i++){var r=this.subMaterials[i];r?t.materials.push(r.id):t.materials.push(null)}return t},i})(e.Material);e.MultiMaterial=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"NO_LOGGING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MINIMAL_LOGGING",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"SUMMARY_LOGGING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DETAILED_LOGGING",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ForceFullSceneLoadingForIncremental",{get:function(){return t._ForceFullSceneLoadingForIncremental},set:function(e){t._ForceFullSceneLoadingForIncremental=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ShowLoadingScreen",{get:function(){return t._ShowLoadingScreen},set:function(e){t._ShowLoadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"loggingLevel",{get:function(){return t._loggingLevel},set:function(e){t._loggingLevel=e},enumerable:!0,configurable:!0}),t._getDefaultPlugin=function(){return t._registeredPlugins[".babylon"]},t._getPluginForExtension=function(e){var i=t._registeredPlugins[e];return i?i:t._getDefaultPlugin()},t._getPluginForFilename=function(e){e.name&&(e=e.name);var i=e.lastIndexOf("."),r=e.indexOf("?");r===-1&&(r=e.length);var n=e.substring(i,r).toLowerCase();return t._getPluginForExtension(n)},t._getDirectLoad=function(e){return e.substr&&"data:"===e.substr(0,5)?e.substr(5):null},t.GetPluginForExtension=function(e){return t._getPluginForExtension(e).plugin},t.RegisterPlugin=function(e){if("string"==typeof e.extensions){var i=e.extensions;t._registeredPlugins[i.toLowerCase()]={plugin:e,isBinary:!1}}else{var r=e.extensions;Object.keys(r).forEach((function(i){t._registeredPlugins[i.toLowerCase()]={plugin:e,isBinary:r[i].isBinary}}))}},t.ImportMesh=function(i,r,n,o,s,a,h){if(n.substr&&"/"===n.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");if(n.substr&&"/"===n.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");var c=t._getDirectLoad(n),l={};o._addPendingData(l);var u=function(u){o.database=f;var d=c?t._getDefaultPlugin():t._getPluginForFilename(n),p=d.plugin,m=d.isBinary,g=function(e){var t=[],a=[],c=[];try{if(p.importMesh){var u=p;if(!u.importMesh(i,o,e,r,t,a,c))return h&&h(o,"Unable to import meshes from "+r+n),void o._removePendingData(l);s&&(o.importedMeshesFiles.push(r+n),s(t,a,c),o._removePendingData(l))}else{var f=p;f.importMeshAsync(i,o,e,r,(function(e,t,i){s&&(o.importedMeshesFiles.push(r+n),s(e,t,i),o._removePendingData(l))}),(function(){h&&h(o,"Unable to import meshes from "+r+n),o._removePendingData(l)}))}}catch(d){h&&h(o,"Unable to import meshes from "+r+n,d),o._removePendingData(l)}};return c?void g(c):void e.Tools.LoadFile(r+n,(function(e){g(e)}),a,f,m)};if(o.getEngine().enableOfflineSupport&&!c)var f=new e.Database(r+n,u);else u(!0)},t.Load=function(i,r,n,o,s,a){t.Append(i,r,new e.Scene(n),o,s,a)},t.Append=function(i,r,n,o,s,a){if(r.substr&&"/"===r.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");var h,c=t._getDirectLoad(r),l=c?t._getDefaultPlugin():t._getPluginForFilename(r),u=l.plugin,f=l.isBinary,d={};n._addPendingData(d),t.ShowLoadingScreen&&n.getEngine().displayLoadingUI();var p=function(e){if(n.database=h,u.load){var r=u;if(!r.load(n,e,i))return a&&a(n),n._removePendingData(d),void n.getEngine().hideLoadingUI();o&&o(n),n._removePendingData(d)}else{var s=u;s.loadAsync(n,e,i,(function(){o&&o(n),n._removePendingData(d)}),(function(){a&&a(n),n._removePendingData(d),n.getEngine().hideLoadingUI()}))}t.ShowLoadingScreen&&n.executeWhenReady((function(){n.getEngine().hideLoadingUI()}))},m=function(t){e.Tools.LoadFile(i+r,p,s,h,f)};return c?void p(c):void(i.indexOf("file:")===-1?n.getEngine().enableOfflineSupport?h=new e.Database(i+r,m):m(!0):e.Tools.ReadFile(r,p,s,f))},t._ForceFullSceneLoadingForIncremental=!1,t._ShowLoadingScreen=!0,t._loggingLevel=t.NO_LOGGING,t._registeredPlugins={},t})();e.SceneLoader=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=function(t,i,r,n){for(var o=0,s=i.materials.length;o<s;o++){var a=i.materials[o];if(a.id===t)return e.Material.Parse(a,r,n)}return null},r=function(e,t,i){t=t instanceof Array?t:[t];for(var r in t)if(e.name===t[r])return i.push(e.id),!0;return!(!e.parentId||i.indexOf(e.parentId)===-1)&&(i.push(e.id),!0)},n=function(e,t){return e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown")};e.SceneLoader.RegisterPlugin({extensions:".babylon",importMesh:function(t,o,s,a,h,c,l){var u="importMesh has failed JSON parse";try{var f=JSON.parse(s);u="";var d,p,m=e.SceneLoader.loggingLevel===e.SceneLoader.DETAILED_LOGGING,g=[],_=[],v=[];for(d=0,p=f.meshes.length;d<p;d++){var y=f.meshes[d];if(!t||r(y,t,v)){if(t instanceof Array&&delete t[t.indexOf(y.name)],y.geometryId&&f.geometries){var x=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach((function(t){!x&&f.geometries[t]&&f.geometries[t]instanceof Array&&f.geometries[t].forEach((function(i){if(i.id===y.geometryId){switch(t){case"boxes":e.Geometry.Primitives.Box.Parse(i,o);break;case"spheres":e.Geometry.Primitives.Sphere.Parse(i,o);break;case"cylinders":e.Geometry.Primitives.Cylinder.Parse(i,o);break;case"toruses":e.Geometry.Primitives.Torus.Parse(i,o);break;case"grounds":e.Geometry.Primitives.Ground.Parse(i,o);break;case"planes":e.Geometry.Primitives.Plane.Parse(i,o);break;case"torusKnots":e.Geometry.Primitives.TorusKnot.Parse(i,o);break;case"vertexData":e.Geometry.Parse(i,o,a)}x=!0}}))})),x||e.Tools.Warn("Geometry not found for mesh "+y.id)}if(y.materialId){var b=_.indexOf(y.materialId)!==-1;if(!b&&f.multiMaterials)for(var A=0,T=f.multiMaterials.length;A<T;A++){var E=f.multiMaterials[A];if(E.id===y.materialId){for(var M=0,P=E.materials.length;M<P;M++){var S=E.materials[M];_.push(S);var C=i(S,f,o,a);u+="\n\tMaterial "+C.toString(m)}_.push(E.id);var R=e.Material.ParseMultiMaterial(E,o);b=!0,u+="\n\tMulti-Material "+R.toString(m);break}}if(!b){_.push(y.materialId);var C=i(y.materialId,f,o,a);C?u+="\n\tMaterial "+C.toString(m):e.Tools.Warn("Material not found for mesh "+y.id)}}if(y.skeletonId>-1&&o.skeletons){var O=g.indexOf(y.skeletonId)>-1;if(!O)for(var D=0,I=f.skeletons.length;D<I;D++){var L=f.skeletons[D];if(L.id===y.skeletonId){var w=e.Skeleton.Parse(L,o);l.push(w),g.push(L.id),u+="\n\tSkeleton "+w.toString(m)}}}var B=e.Mesh.Parse(y,o,a);h.push(B),u+="\n\tMesh "+B.toString(m)}}var F;for(d=0,p=o.meshes.length;d<p;d++)F=o.meshes[d],F._waitingParentId&&(F.parent=o.getLastEntryByID(F._waitingParentId),F._waitingParentId=void 0);for(d=0,p=o.meshes.length;d<p;d++)F=o.meshes[d],F._waitingFreezeWorldMatrix?(F.freezeWorldMatrix(),F._waitingFreezeWorldMatrix=void 0):F.computeWorldMatrix(!0);if(f.particleSystems)for(d=0,p=f.particleSystems.length;d<p;d++){var V=f.particleSystems[d];v.indexOf(V.emitterId)!==-1&&c.push(e.ParticleSystem.Parse(V,o,a))}return!0}catch(N){throw e.Tools.Log(n("importMesh",f?f.producer:"Unknown")+u),u=null,N}finally{null!==u&&e.SceneLoader.loggingLevel!==e.SceneLoader.NO_LOGGING&&e.Tools.Log(n("importMesh",f?f.producer:"Unknown")+(e.SceneLoader.loggingLevel!==e.SceneLoader.MINIMAL_LOGGING?u:""))}},load:function(t,i,r){var o="importScene has failed JSON parse";try{var s=JSON.parse(i);o="";var a=e.SceneLoader.loggingLevel===e.SceneLoader.DETAILED_LOGGING;if(t.useDelayedTextureLoading=s.useDelayedTextureLoading&&!e.SceneLoader.ForceFullSceneLoadingForIncremental,t.autoClear=s.autoClear,t.clearColor=e.Color4.FromArray(s.clearColor),t.ambientColor=e.Color3.FromArray(s.ambientColor),s.gravity&&(t.gravity=e.Vector3.FromArray(s.gravity)),s.fogMode&&0!==s.fogMode)switch(t.fogMode=s.fogMode,t.fogColor=e.Color3.FromArray(s.fogColor),t.fogStart=s.fogStart,t.fogEnd=s.fogEnd,t.fogDensity=s.fogDensity,o+="\tFog mode for scene:  ",t.fogMode){case 1:o+="exp\n";break;case 2:o+="exp2\n";break;case 3:o+="linear\n"}if(s.physicsEnabled){var h;"cannon"===s.physicsEngine?h=new e.CannonJSPlugin:"oimo"===s.physicsEngine&&(h=new e.OimoJSPlugin),o="\tPhysics engine "+(s.physicsEngine?s.physicsEngine:"oimo")+" enabled\n";var c=s.physicsGravity?e.Vector3.FromArray(s.physicsGravity):null;t.enablePhysics(c,h)}void 0!==s.metadata&&(t.metadata=s.metadata),void 0!=s.collisionsEnabled&&(t.collisionsEnabled=s.collisionsEnabled),t.workerCollisions=!!s.workerCollisions;var l,u;for(l=0,u=s.lights.length;l<u;l++){var f=s.lights[l],d=e.Light.Parse(f,t);o+=0===l?"\n\tLights:":"",o+="\n\t\t"+d.toString(a)}if(s.animations)for(l=0,u=s.animations.length;l<u;l++){var p=s.animations[l],m=e.Animation.Parse(p);t.animations.push(m),o+=0===l?"\n\tAnimations:":"",o+="\n\t\t"+m.toString(a)}if(s.autoAnimate&&t.beginAnimation(t,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1),s.materials)for(l=0,u=s.materials.length;l<u;l++){var g=s.materials[l],_=e.Material.Parse(g,t,r);o+=0===l?"\n\tMaterials:":"",o+="\n\t\t"+_.toString(a)}if(s.multiMaterials)for(l=0,u=s.multiMaterials.length;l<u;l++){var v=s.multiMaterials[l],y=e.Material.ParseMultiMaterial(v,t);o+=0===l?"\n\tMultiMaterials:":"",o+="\n\t\t"+y.toString(a)}if(s.skeletons)for(l=0,u=s.skeletons.length;l<u;l++){var x=s.skeletons[l],b=e.Skeleton.Parse(x,t);o+=0===l?"\n\tSkeletons:":"",o+="\n\t\t"+b.toString(a)}var A=s.geometries;if(A){var T=A.boxes;if(T)for(l=0,u=T.length;l<u;l++){var E=T[l];e.Geometry.Primitives.Box.Parse(E,t)}var M=A.spheres;if(M)for(l=0,u=M.length;l<u;l++){var P=M[l];e.Geometry.Primitives.Sphere.Parse(P,t)}var S=A.cylinders;if(S)for(l=0,u=S.length;l<u;l++){var C=S[l];e.Geometry.Primitives.Cylinder.Parse(C,t)}var R=A.toruses;if(R)for(l=0,u=R.length;l<u;l++){var O=R[l];e.Geometry.Primitives.Torus.Parse(O,t)}var D=A.grounds;if(D)for(l=0,u=D.length;l<u;l++){var I=D[l];e.Geometry.Primitives.Ground.Parse(I,t)}var L=A.planes;if(L)for(l=0,u=L.length;l<u;l++){var w=L[l];e.Geometry.Primitives.Plane.Parse(w,t)}var B=A.torusKnots;if(B)for(l=0,u=B.length;l<u;l++){var F=B[l];e.Geometry.Primitives.TorusKnot.Parse(F,t)}var V=A.vertexData;if(V)for(l=0,u=V.length;l<u;l++){var N=V[l];e.Geometry.Parse(N,t,r)}}for(l=0,u=s.meshes.length;l<u;l++){var U=s.meshes[l],z=e.Mesh.Parse(U,t,r);o+=0===l?"\n\tMeshes:":"",o+="\n\t\t"+z.toString(a)}for(l=0,u=s.cameras.length;l<u;l++){var k=s.cameras[l],W=e.Camera.Parse(k,t);o+=0===l?"\n\tCameras:":"",o+="\n\t\t"+W.toString(a)}for(s.activeCameraID&&t.setActiveCameraByID(s.activeCameraID),l=0,u=t.cameras.length;l<u;l++){var W=t.cameras[l];W._waitingParentId&&(W.parent=t.getLastEntryByID(W._waitingParentId),W._waitingParentId=void 0)}for(l=0,u=t.lights.length;l<u;l++){var d=t.lights[l];d._waitingParentId&&(d.parent=t.getLastEntryByID(d._waitingParentId),d._waitingParentId=void 0)}var G,Y=[];if(e.AudioEngine&&s.sounds)for(l=0,u=s.sounds.length;l<u;l++){var K=s.sounds[l];if(e.Engine.audioEngine.canUseWebAudio)K.url||(K.url=K.name),Y[K.url]?e.Sound.Parse(K,t,r,Y[K.url]):(G=e.Sound.Parse(K,t,r),Y[K.url]=G);else{new e.Sound(K.name,null,t)}}for(Y=[],l=0,u=t.meshes.length;l<u;l++){var z=t.meshes[l];z._waitingParentId&&(z.parent=t.getLastEntryByID(z._waitingParentId),z._waitingParentId=void 0),z._waitingActions&&(e.ActionManager.Parse(z._waitingActions,z,t),z._waitingActions=void 0)}for(l=0,u=t.meshes.length;l<u;l++){var X=t.meshes[l];X._waitingFreezeWorldMatrix?(X.freezeWorldMatrix(),X._waitingFreezeWorldMatrix=void 0):X.computeWorldMatrix(!0)}if(s.particleSystems)for(l=0,u=s.particleSystems.length;l<u;l++){var H=s.particleSystems[l];e.ParticleSystem.Parse(H,t,r)}if(s.lensFlareSystems)for(l=0,u=s.lensFlareSystems.length;l<u;l++){var j=s.lensFlareSystems[l];e.LensFlareSystem.Parse(j,t,r)}if(s.shadowGenerators)for(l=0,u=s.shadowGenerators.length;l<u;l++){var Z=s.shadowGenerators[l];e.ShadowGenerator.Parse(Z,t)}return s.actions&&e.ActionManager.Parse(s.actions,null,t),!0}catch(q){throw e.Tools.Log(n("importScene",s?s.producer:"Unknown")+o),o=null,q}finally{null!==o&&e.SceneLoader.loggingLevel!==e.SceneLoader.NO_LOGGING&&e.Tools.Log(n("importScene",s?s.producer:"Unknown")+(e.SceneLoader.loggingLevel!==e.SceneLoader.MINIMAL_LOGGING?o:""))}}})})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a){if(void 0===s&&(s=.01),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),this.name=t,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.fogEnabled=!0,this.isPickable=!1,this.onDisposeObservable=new e.Observable,this._vertexBuffers={},this._capacity=r,this._spriteTexture=new e.Texture(i,o,(!0),(!1),a),this._spriteTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._spriteTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return;this.cellWidth=n,this.cellHeight=n}this._epsilon=s,this._scene=o,this._scene.spriteManagers.push(this);for(var h=[],c=0,l=0;l<r;l++)h.push(c),h.push(c+1),h.push(c+2),h.push(c),h.push(c+2),h.push(c+3),c+=4;this._indexBuffer=o.getEngine().createIndexBuffer(h),this._vertexData=new Float32Array(16*r*4),this._buffer=new e.Buffer(o.getEngine(),this._vertexData,(!0),16);var u=this._buffer.createVertexBuffer(e.VertexBuffer.PositionKind,0,4),f=this._buffer.createVertexBuffer("options",4,4),d=this._buffer.createVertexBuffer("cellInfo",8,4),p=this._buffer.createVertexBuffer(e.VertexBuffer.ColorKind,12,4);this._vertexBuffers[e.VertexBuffer.PositionKind]=u,this._vertexBuffers.options=f,this._vertexBuffers.cellInfo=d,this._vertexBuffers[e.VertexBuffer.ColorKind]=p,this._effectBase=this._scene.getEngine().createEffect("sprites",[e.VertexBuffer.PositionKind,"options","cellInfo",e.VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],""),this._effectFog=this._scene.getEngine().createEffect("sprites",[e.VertexBuffer.PositionKind,"options","cellInfo",e.VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],"#define FOG")}return Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"texture",{get:function(){return this._spriteTexture},set:function(e){this._spriteTexture=e},enumerable:!0,configurable:!0}),t.prototype._appendSpriteVertex=function(e,t,i,r,n){var o=16*e;0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._vertexData[o+6]=i,this._vertexData[o+7]=r,this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0;var s=t.cellIndex/n>>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o,s=Math.min(this._capacity,this.sprites.length),a=e.Vector3.Zero(),h=e.Vector3.Zero(),c=Number.MAX_VALUE,l=e.Vector3.Zero(),u=i.getViewMatrix(),f=0;f<s;f++){var d=this.sprites[f];if(d){if(r){if(!r(d))continue}else if(!d.isPickable)continue;if(e.Vector3.TransformCoordinatesToRef(d.position,u,l),a.copyFromFloats(l.x-d.width/2,l.y-d.height/2,l.z),h.copyFromFloats(l.x+d.width/2,l.y+d.height/2,l.z),t.intersectsBoxMinMax(a,h)){var p=e.Vector3.Distance(l,t.origin);if(c>p&&(c=p,o=d,n))break}}}if(o){var m=new e.PickingInfo;return m.hit=!0,m.pickedSprite=o,m.distance=c,m}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;a<n;a++){var h=this.sprites[a];h&&(h._animate(r),this._appendSpriteVertex(s++,h,0,0,o),this._appendSpriteVertex(s++,h,1,0,o),this._appendSpriteVertex(s++,h,1,1,o),this._appendSpriteVertex(s++,h,0,1,o))}this._buffer.update(this._vertexData);var c=this._effectBase;this._scene.fogEnabled&&this._scene.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(c=this._effectFog),t.enableEffect(c);var l=this._scene.getViewMatrix();c.setTexture("diffuseSampler",this._spriteTexture),c.setMatrix("view",l),c.setMatrix("projection",this._scene.getProjectionMatrix()),c.setFloat2("textureInfos",this.cellWidth/i.width,this.cellHeight/i.height),this._scene.fogEnabled&&this._scene.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(c.setFloat4("vFogInfos",this._scene.fogMode,this._scene.fogStart,this._scene.fogEnd,this._scene.fogDensity),c.setColor3("vFogColor",this._scene.fogColor)),t.bindBuffers(this._vertexBuffers,this._indexBuffer,c),t.setDepthFunctionToLessOrEqual(),c.setBool("alphaTest",!0),t.setColorWrite(!1),t.draw(!0,0,6*n),t.setColorWrite(!0),c.setBool("alphaTest",!1),t.setAlphaMode(e.Engine.ALPHA_COMBINE),t.draw(!0,0,6*n),t.setAlphaMode(e.Engine.ALPHA_DISABLE)}},t.prototype.dispose=function(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._spriteTexture&&(this._spriteTexture.dispose(),this._spriteTexture=null);var e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t})();e.SpriteManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.name=t,this.color=new e.Color4(1,1,1,1),this.width=1,this.height=1,this.angle=0,this.cellIndex=0,this.invertU=0,this.invertV=0,this.animations=new Array,this.isPickable=!1,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._frameCount=0,this._time=0,this._manager=i,this._manager.sprites.push(this),this.position=e.Vector3.Zero()}return Object.defineProperty(t.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!0,configurable:!0}),t.prototype.playAnimation=function(e,t,i,r,n){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r,this._animationStarted=!0,this._direction=e<t?1:-1,this.cellIndex=e,this._time=0,this._onAnimationEnd=n},t.prototype.stopAnimation=function(){this._animationStarted=!1},t.prototype._animate=function(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex===this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1)},t})();e.Sprite=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.name=t,this.scale=new e.Vector2(1,1),this.offset=new e.Vector2(0,0),this.alphaBlendingMode=e.Engine.ALPHA_COMBINE,this._vertexBuffers={},this.onDisposeObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.texture=i?new e.Texture(i,r,(!0)):null,this.isBackground=void 0===n||n,this.color=void 0===o?new e.Color4(1,1,1,1):o,this._scene=r,this._scene.layers.push(this);var s=r.getEngine(),a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);var h=new e.VertexBuffer(s,a,e.VertexBuffer.PositionKind,(!1),(!1),2);this._vertexBuffers[e.VertexBuffer.PositionKind]=h;var c=[];c.push(0),c.push(1),c.push(2),c.push(0),c.push(2),c.push(3),this._indexBuffer=s.createIndexBuffer(c),this._effect=s.createEffect("layer",[e.VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],""),this._alphaTestEffect=s.createEffect("layer",[e.VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],"#define ALPHATEST")}return Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.render=function(){var t=this.alphaTest?this._alphaTestEffect:this._effect;if(t.isReady()&&this.texture&&this.texture.isReady()){var i=this._scene.getEngine();this.onBeforeRenderObservable.notifyObservers(this),i.enableEffect(t),i.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?i.draw(!0,0,6):(i.setAlphaMode(this.alphaBlendingMode),i.draw(!0,0,6),i.setAlphaMode(e.Engine.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this)}},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null);var i=this._scene.layers.indexOf(this);this._scene.layers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},t})();e.Layer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.position=e.Vector3.Zero(),this.direction=e.Vector3.Zero(),this.color=new e.Color4(0,0,0,0),this.colorStep=new e.Color4(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.angle=0,this.angularSpeed=0}return t.prototype.copyTo=function(e){e.position.copyFrom(this.position),e.direction.copyFrom(this.direction),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e.size=this.size,e.angle=this.angle,e.angularSpeed=this.angularSpeed},t})();e.Particle=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t){if(e===t)return e;var i=Math.random();return i*(t-e)+e},i=(function(){function i(r,n,o,s){var a=this;this.name=r,this.animations=[],this.renderingGroupId=0,this.emitter=null,this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.onDisposeObservable=new e.Observable,this.blendMode=i.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.gravity=e.Vector3.Zero(),this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3((-.5),(-.5),(-.5)),this.maxEmitBox=new e.Vector3(.5,.5,.5),this.color1=new e.Color4(1,1,1,1),this.color2=new e.Color4(1,1,1,1),this.colorDead=new e.Color4(0,0,0,1),this.textureMask=new e.Color4(1,1,1,1),this.particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new e.Color4(0,0,0,0),this._colorDiff=new e.Color4(0,0,0,0),this._scaledDirection=e.Vector3.Zero(),this._scaledGravity=e.Vector3.Zero(),this._currentRenderId=-1,this._started=!1,this._stopped=!1,this._actualFrame=0,this.id=r,this._capacity=n,this._scene=o,this._customEffect=s,o.particleSystems.push(this);for(var h=[],c=0,l=0;l<n;l++)h.push(c),h.push(c+1),h.push(c+2),h.push(c),h.push(c+2),h.push(c+3),c+=4;this._indexBuffer=o.getEngine().createIndexBuffer(h),this._vertexData=new Float32Array(11*n*4),this._vertexBuffer=new e.Buffer(o.getEngine(),this._vertexData,(!0),11);var u=this._vertexBuffer.createVertexBuffer(e.VertexBuffer.PositionKind,0,3),f=this._vertexBuffer.createVertexBuffer(e.VertexBuffer.ColorKind,3,4),d=this._vertexBuffer.createVertexBuffer("options",7,4);this._vertexBuffers[e.VertexBuffer.PositionKind]=u,this._vertexBuffers[e.VertexBuffer.ColorKind]=f,this._vertexBuffers.options=d,this.startDirectionFunction=function(i,r,n,o){var s=t(a.direction1.x,a.direction2.x),h=t(a.direction1.y,a.direction2.y),c=t(a.direction1.z,a.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(s*i,h*i,c*i,r,n)},this.startPositionFunction=function(i,r,n){var o=t(a.minEmitBox.x,a.maxEmitBox.x),s=t(a.minEmitBox.y,a.maxEmitBox.y),h=t(a.minEmitBox.z,a.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(o,s,h,i,r);
},this.updateFunction=function(e){for(var t=0;t<e.length;t++){var i=e[t];i.age+=a._scaledUpdateSpeed,i.age>=i.lifeTime?(a.recycleParticle(i),t--):(i.colorStep.scaleToRef(a._scaledUpdateSpeed,a._scaledColorStep),i.color.addInPlace(a._scaledColorStep),i.color.a<0&&(i.color.a=0),i.angle+=i.angularSpeed*a._scaledUpdateSpeed,i.direction.scaleToRef(a._scaledUpdateSpeed,a._scaledDirection),i.position.addInPlace(a._scaledDirection),a.gravity.scaleToRef(a._scaledUpdateSpeed,a._scaledGravity),i.direction.addInPlace(a._scaledGravity))}}}return Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),i.prototype.recycleParticle=function(e){var t=this.particles.pop();t!==e&&(t.copyTo(e),this._stockParticles.push(t))},i.prototype.getCapacity=function(){return this._capacity},i.prototype.isAlive=function(){return this._alive},i.prototype.isStarted=function(){return this._started},i.prototype.start=function(){this._started=!0,this._stopped=!1,this._actualFrame=0},i.prototype.stop=function(){this._stopped=!0},i.prototype._appendParticleVertex=function(e,t,i,r){var n=11*e;this._vertexData[n]=t.position.x,this._vertexData[n+1]=t.position.y,this._vertexData[n+2]=t.position.z,this._vertexData[n+3]=t.color.r,this._vertexData[n+4]=t.color.g,this._vertexData[n+5]=t.color.b,this._vertexData[n+6]=t.color.a,this._vertexData[n+7]=t.angle,this._vertexData[n+8]=t.size,this._vertexData[n+9]=i,this._vertexData[n+10]=r},i.prototype._update=function(i){this._alive=this.particles.length>0,this.updateFunction(this.particles);var r;r=this.emitter.position?this.emitter.getWorldMatrix():e.Matrix.Translation(this.emitter.x,this.emitter.y,this.emitter.z);for(var n,o=0;o<i&&this.particles.length!==this._capacity;o++){0!==this._stockParticles.length?(n=this._stockParticles.pop(),n.age=0):n=new e.Particle,this.particles.push(n);var s=t(this.minEmitPower,this.maxEmitPower);this.startDirectionFunction(s,r,n.direction,n),n.lifeTime=t(this.minLifeTime,this.maxLifeTime),n.size=t(this.minSize,this.maxSize),n.angularSpeed=t(this.minAngularSpeed,this.maxAngularSpeed),this.startPositionFunction(r,n.position,n);var a=t(0,1);e.Color4.LerpToRef(this.color1,this.color2,a,n.color),this.colorDead.subtractToRef(n.color,this._colorDiff),this._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)}},i.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var t=[];this._scene.clipPlane&&t.push("#define CLIPPLANE");var i=t.join("\n");return this._cachedDefines!==i&&(this._cachedDefines=i,this._effect=this._scene.getEngine().createEffect("particles",[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"options"],["invView","view","projection","vClipPlane","textureMask"],["diffuseSampler"],i)),this._effect},i.prototype.animate=function(){if(this._started){var e=this._getEffect();if(this.emitter&&e.isReady()&&this.particleTexture&&this.particleTexture.isReady()&&this._currentRenderId!==this._scene.getRenderId()){this._currentRenderId=this._scene.getRenderId(),this._scaledUpdateSpeed=this.updateSpeed*this._scene.getAnimationRatio();var t;this.manualEmitCount>-1?(t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(t=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-t),this._newPartsExcess>1&&(t+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.disposeOnStop&&this._scene._toBeDisposed.push(this)));for(var i=0,r=0;r<this.particles.length;r++){var n=this.particles[r];this._appendParticleVertex(i++,n,0,0),this._appendParticleVertex(i++,n,1,0),this._appendParticleVertex(i++,n,1,1),this._appendParticleVertex(i++,n,0,1)}this._vertexBuffer.update(this._vertexData)}}},i.prototype.render=function(){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()&&this.particles.length))return 0;var r=this._scene.getEngine();r.enableEffect(t),r.setState(!1);var n=this._scene.getViewMatrix();if(t.setTexture("diffuseSampler",this.particleTexture),t.setMatrix("view",n),t.setMatrix("projection",this._scene.getProjectionMatrix()),t.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._scene.clipPlane){var o=this._scene.clipPlane,s=n.clone();s.invert(),t.setMatrix("invView",s),t.setFloat4("vClipPlane",o.normal.x,o.normal.y,o.normal.z,o.d)}return r.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.blendMode===i.BLENDMODE_ONEONE?r.setAlphaMode(e.Engine.ALPHA_ONEONE):r.setAlphaMode(e.Engine.ALPHA_COMBINE),this.forceDepthWrite&&r.setDepthWrite(!0),r.draw(!0,0,6*this.particles.length),r.setAlphaMode(e.Engine.ALPHA_DISABLE),this.particles.length},i.prototype.dispose=function(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null);var e=this._scene.particleSystems.indexOf(this);this._scene.particleSystems.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},i.prototype.clone=function(t,r){var n=new i(t,this._capacity,this._scene);return e.Tools.DeepCopy(this,n,["particles"]),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n.start(),n},i.prototype.serialize=function(){var t={};return t.name=this.name,t.id=this.id,this.emitter.position?t.emitterId=this.emitter.id:t.emitter=this.emitter.asArray(),t.capacity=this.getCapacity(),this.particleTexture&&(t.textureName=this.particleTexture.name),e.Animation.AppendSerializedAnimations(this,t),t.minAngularSpeed=this.minAngularSpeed,t.maxAngularSpeed=this.maxAngularSpeed,t.minSize=this.minSize,t.maxSize=this.maxSize,t.minEmitPower=this.minEmitPower,t.maxEmitPower=this.maxEmitPower,t.minLifeTime=this.minLifeTime,t.maxLifeTime=this.maxLifeTime,t.emitRate=this.emitRate,t.minEmitBox=this.minEmitBox.asArray(),t.maxEmitBox=this.maxEmitBox.asArray(),t.gravity=this.gravity.asArray(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.color1=this.color1.asArray(),t.color2=this.color2.asArray(),t.colorDead=this.colorDead.asArray(),t.updateSpeed=this.updateSpeed,t.targetStopDuration=this.targetStopDuration,t.textureMask=this.textureMask.asArray(),t.blendMode=this.blendMode,t},i.Parse=function(t,r,n){var o=t.name,s=new i(o,t.capacity,r);if(t.id&&(s.id=t.id),t.textureName&&(s.particleTexture=new e.Texture(n+t.textureName,r),s.particleTexture.name=t.textureName),t.emitterId?s.emitter=r.getLastMeshByID(t.emitterId):s.emitter=e.Vector3.FromArray(t.emitter),t.animations)for(var a=0;a<t.animations.length;a++){var h=t.animations[a];s.animations.push(e.Animation.Parse(h))}return t.autoAnimate&&r.beginAnimation(s,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),s.minAngularSpeed=t.minAngularSpeed,s.maxAngularSpeed=t.maxAngularSpeed,s.minSize=t.minSize,s.maxSize=t.maxSize,s.minLifeTime=t.minLifeTime,s.maxLifeTime=t.maxLifeTime,s.minEmitPower=t.minEmitPower,s.maxEmitPower=t.maxEmitPower,s.emitRate=t.emitRate,s.minEmitBox=e.Vector3.FromArray(t.minEmitBox),s.maxEmitBox=e.Vector3.FromArray(t.maxEmitBox),s.gravity=e.Vector3.FromArray(t.gravity),s.direction1=e.Vector3.FromArray(t.direction1),s.direction2=e.Vector3.FromArray(t.direction2),s.color1=e.Color4.FromArray(t.color1),s.color2=e.Color4.FromArray(t.color2),s.colorDead=e.Color4.FromArray(t.colorDead),s.updateSpeed=t.updateSpeed,s.targetStopDuration=t.targetStopDuration,s.textureMask=e.Color4.FromArray(t.textureMask),s.blendMode=t.blendMode,t.preventAutoStart||s.start(),s},i.BLENDMODE_ONEONE=0,i.BLENDMODE_STANDARD=1,i})();e.ParticleSystem=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(e){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._events=new Array,this.allowMatricesInterpolation=!1,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,h,c){var l=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?l=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?l=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?l=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?l=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?l=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(l=i.ANIMATIONTYPE_SIZE),void 0==l)return null;var u=new i(t,r,n,l,h),f=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(f),void 0!==c&&u.setEasingFunction(c),u},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,h,c,l){var u=i._PrepareAnimation(e,r,n,o,s,a,h,c);return t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,l)},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,h,c,l){var u=i._PrepareAnimation(e,r,n,o,s,a,h,c);return t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,l)},i.prototype.toString=function(e){var t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},i.prototype.addEvent=function(e){this._events.push(e)},i.prototype.removeEvents=function(e){for(var t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)},i.prototype.createRange=function(e,i,r){this._ranges[e]||(this._ranges[e]=new t(e,i,r))},i.prototype.deleteRange=function(e,t){if(void 0===t&&(t=!0),this._ranges[e]){if(t)for(var i=this._ranges[e].from,r=this._ranges[e].to,n=this._keys.length-1;n>=0;n--)this._keys[n].frame>=i&&this._keys[n].frame<=r&&this._keys.splice(n,1);this._ranges[e]=void 0}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.reset=function(){this._offsetsCache={},this._highLimitsCache={},this.currentFrame=0,this._blendingFactor=0,this._originalBlendValue=null},i.prototype.isStopped=function(){return this._stopped},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e},i.prototype.getEasingFunction=function(){return this._easingFunction},i.prototype.setEasingFunction=function(e){this._easingFunction=e},i.prototype.floatInterpolateFunction=function(e,t,i){return e+(t-e)*i},i.prototype.quaternionInterpolateFunction=function(t,i,r){return e.Quaternion.Slerp(t,i,r)},i.prototype.vector3InterpolateFunction=function(t,i,r){return e.Vector3.Lerp(t,i,r)},i.prototype.vector2InterpolateFunction=function(t,i,r){return e.Vector2.Lerp(t,i,r)},i.prototype.sizeInterpolateFunction=function(t,i,r){return e.Size.Lerp(t,i,r)},i.prototype.color3InterpolateFunction=function(t,i,r){return e.Color3.Lerp(t,i,r)},i.prototype.matrixInterpolateFunction=function(t,i,r){return e.Matrix.Lerp(t,i,r)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges)e._ranges[t]=this._ranges[t].clone()}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0),this._offsetsCache={},this._highLimitsCache={}},i.prototype._getKeyValue=function(e){return"function"==typeof e?e():e},i.prototype._interpolate=function(e,t,r,n,o){if(r===i.ANIMATIONLOOPMODE_CONSTANT&&t>0)return o.clone?o.clone():o;this.currentFrame=e;var s=Math.max(0,Math.min(this._keys.length-1,Math.floor(this._keys.length*(e-this._keys[0].frame)/(this._keys[this._keys.length-1].frame-this._keys[0].frame))-1));if(this._keys[s].frame>=e)for(;s-1>=0&&this._keys[s].frame>=e;)s--;for(var a=s;a<this._keys.length;a++)if(this._keys[a+1].frame>=e){var h=this._getKeyValue(this._keys[a].value),c=this._getKeyValue(this._keys[a+1].value),l=(e-this._keys[a].frame)/(this._keys[a+1].frame-this._keys[a].frame);switch(null!=this._easingFunction&&(l=this._easingFunction.ease(l)),this.dataType){case i.ANIMATIONTYPE_FLOAT:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.floatInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return n*t+this.floatInterpolateFunction(h,c,l)}break;case i.ANIMATIONTYPE_QUATERNION:var u=null;switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:u=this.quaternionInterpolateFunction(h,c,l);break;case i.ANIMATIONLOOPMODE_RELATIVE:u=this.quaternionInterpolateFunction(h,c,l).add(n.scale(t))}return u;case i.ANIMATIONTYPE_VECTOR3:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.vector3InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.vector3InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_VECTOR2:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.vector2InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.vector2InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(this.allowMatricesInterpolation)return this.matrixInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return h}}break}return this._getKeyValue(this._keys[this._keys.length-1].value)},i.prototype.setValue=function(t,i){void 0===i&&(i=!1);var r,n;if(this.targetPropertyPath.length>1){for(var o=this._target[this.targetPropertyPath[0]],s=1;s<this.targetPropertyPath.length-1;s++)o=o[this.targetPropertyPath[s]];r=this.targetPropertyPath[this.targetPropertyPath.length-1],n=o}else r=this.targetPropertyPath[0],n=this._target;this.enableBlending&&this._blendingFactor<=1?(this._originalBlendValue||(n[r].clone?this._originalBlendValue=n[r].clone():this._originalBlendValue=n[r]),this._originalBlendValue.prototype?this._originalBlendValue.prototype.Lerp?n[r]=this._originalBlendValue.construtor.prototype.Lerp(t,this._originalBlendValue,this._blendingFactor):n[r]=t:this._originalBlendValue.m?n[r]=e.Matrix.Lerp(this._originalBlendValue,t,this._blendingFactor):n[r]=this._originalBlendValue*(1-this._blendingFactor)+this._blendingFactor*t,this._blendingFactor+=this.blendingSpeed):n[r]=t,this._target.markAsDirty&&this._target.markAsDirty(this.targetProperty)},i.prototype.goToFrame=function(e){e<this._keys[0].frame?e=this._keys[0].frame:e>this._keys[this._keys.length-1].frame&&(e=this._keys[this._keys.length-1].frame);var t=this._interpolate(e,0,this.loopMode);this.setValue(t)},i.prototype.animate=function(t,r,n,o,s,a){if(void 0===a&&(a=!1),!this.targetPropertyPath||this.targetPropertyPath.length<1)return this._stopped=!0,!1;var h=!0;if(0!==this._keys[0].frame){var c={frame:0,value:this._keys[0].value};this._keys.splice(0,0,c)}(r<this._keys[0].frame||r>this._keys[this._keys.length-1].frame)&&(r=this._keys[0].frame),(n<this._keys[0].frame||n>this._keys[this._keys.length-1].frame)&&(n=this._keys[this._keys.length-1].frame),r===n&&r++;var l,u=n-r,f=t*(this.framePerSecond*s)/1e3,d=0;if(f>u&&!o)h=!1,d=this._getKeyValue(this._keys[this._keys.length-1].value);else if(this.loopMode!==i.ANIMATIONLOOPMODE_CYCLE){var p=n.toString()+r.toString();if(!this._offsetsCache[p]){var m=this._interpolate(r,0,i.ANIMATIONLOOPMODE_CYCLE),g=this._interpolate(n,0,i.ANIMATIONLOOPMODE_CYCLE);switch(this.dataType){case i.ANIMATIONTYPE_FLOAT:this._offsetsCache[p]=g-m;break;case i.ANIMATIONTYPE_QUATERNION:this._offsetsCache[p]=g.subtract(m);break;case i.ANIMATIONTYPE_VECTOR3:this._offsetsCache[p]=g.subtract(m);case i.ANIMATIONTYPE_VECTOR2:this._offsetsCache[p]=g.subtract(m);case i.ANIMATIONTYPE_SIZE:this._offsetsCache[p]=g.subtract(m);case i.ANIMATIONTYPE_COLOR3:this._offsetsCache[p]=g.subtract(m)}this._highLimitsCache[p]=g}d=this._highLimitsCache[p],l=this._offsetsCache[p]}if(void 0===l)switch(this.dataType){case i.ANIMATIONTYPE_FLOAT:l=0;break;case i.ANIMATIONTYPE_QUATERNION:l=new e.Quaternion(0,0,0,0);break;case i.ANIMATIONTYPE_VECTOR3:l=e.Vector3.Zero();break;case i.ANIMATIONTYPE_VECTOR2:l=e.Vector2.Zero();break;case i.ANIMATIONTYPE_SIZE:l=e.Size.Zero();break;case i.ANIMATIONTYPE_COLOR3:l=e.Color3.Black()}var _=f/u>>0,v=h?r+f%u:n,y=this._interpolate(v,_,this.loopMode,l,d);this.setValue(y);for(var x=0;x<this._events.length;x++)if(v>=this._events[x].frame){var b=this._events[x];b.isDone||(b.onlyOnce&&(this._events.splice(x,1),x--),b.isDone=!0,b.action())}else this._events[x].isDone&&!this._events[x].onlyOnce&&(this._events[x].isDone=!1);return h||(this._stopped=!0),h},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n<r.length;n++){var o=r[n],s={};switch(s.frame=o.frame,t){case i.ANIMATIONTYPE_FLOAT:s.values=[o.value];break;case i.ANIMATIONTYPE_QUATERNION:case i.ANIMATIONTYPE_MATRIX:case i.ANIMATIONTYPE_VECTOR3:case i.ANIMATIONTYPE_COLOR3:s.values=o.value.asArray()}e.keys.push(s)}e.ranges=[];for(var a in this._ranges){var h={};h.name=a,h.from=this._ranges[a].from,h.to=this._ranges[a].to,e.ranges.push(h)}return e},Object.defineProperty(i,"ANIMATIONTYPE_FLOAT",{get:function(){return i._ANIMATIONTYPE_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_VECTOR3",{get:function(){return i._ANIMATIONTYPE_VECTOR3},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_VECTOR2",{get:function(){return i._ANIMATIONTYPE_VECTOR2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_SIZE",{get:function(){return i._ANIMATIONTYPE_SIZE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_QUATERNION",{get:function(){return i._ANIMATIONTYPE_QUATERNION},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_MATRIX",{get:function(){return i._ANIMATIONTYPE_MATRIX},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_COLOR3",{get:function(){return i._ANIMATIONTYPE_COLOR3},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_RELATIVE",{get:function(){return i._ANIMATIONLOOPMODE_RELATIVE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_CYCLE",{get:function(){return i._ANIMATIONLOOPMODE_CYCLE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_CONSTANT",{get:function(){return i._ANIMATIONLOOPMODE_CONSTANT},enumerable:!0,configurable:!0}),i.Parse=function(t){var r,n,o=new i(t.name,t.property,t.framePerSecond,t.dataType,t.loopBehavior),s=t.dataType,a=[];for(n=0;n<t.keys.length;n++){var h=t.keys[n];switch(s){case i.ANIMATIONTYPE_FLOAT:r=h.values[0];break;case i.ANIMATIONTYPE_QUATERNION:r=e.Quaternion.FromArray(h.values);break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(h.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(h.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(h.values)}a.push({frame:h.frame,value:r})}if(o.setKeys(a),t.ranges)for(n=0;n<t.ranges.length;n++)r=t.ranges[n],o.createRange(r.name,r.from,r.to);return o},i.AppendSerializedAnimations=function(e,t){if(e.animations){t.animations=[];for(var i=0;i<e.animations.length;i++){var r=e.animations[i];t.animations.push(r.serialize())}}},i._ANIMATIONTYPE_FLOAT=0,i._ANIMATIONTYPE_VECTOR3=1,i._ANIMATIONTYPE_QUATERNION=2,i._ANIMATIONTYPE_MATRIX=3,i._ANIMATIONTYPE_COLOR3=4,i._ANIMATIONTYPE_VECTOR2=5,i._ANIMATIONTYPE_SIZE=6,i._ANIMATIONLOOPMODE_RELATIVE=0,i._ANIMATIONLOOPMODE_CYCLE=1,i._ANIMATIONLOOPMODE_CONSTANT=2,i})();e.Animation=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i,r,n,o,s,a){void 0===i&&(i=0),void 0===r&&(r=100),void 0===n&&(n=!1),void 0===o&&(o=1),this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=n,this.speedRatio=o,this.onAnimationEnd=s,this._animations=new Array,this._paused=!1,this.animationStarted=!1,a&&this.appendAnimations(t,a),this._scene=e,e._activeAnimatables.push(this)}return e.prototype.getAnimations=function(){return this._animations},e.prototype.appendAnimations=function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r._target=e,this._animations.push(r)}},e.prototype.getAnimationByTargetProperty=function(e){for(var t=this._animations,i=0;i<t.length;i++)if(t[i].targetProperty===e)return t[i];return null},e.prototype.reset=function(){for(var e=this._animations,t=0;t<e.length;t++)e[t].reset();this._localDelayOffset=null,this._pausedDelay=null},e.prototype.enableBlending=function(e){for(var t=this._animations,i=0;i<t.length;i++)t[i].enableBlending=!0,t[i].blendingSpeed=e},e.prototype.disableBlending=function(){for(var e=this._animations,t=0;t<e.length;t++)e[t].enableBlending=!1},e.prototype.goToFrame=function(e){var t=this._animations;if(t[0]){var i=t[0].framePerSecond,r=t[0].currentFrame,n=e-r,o=1e3*n/i;this._localDelayOffset-=o}for(var s=0;s<t.length;s++)t[s].goToFrame(e)},e.prototype.pause=function(){this._paused||(this._paused=!0)},e.prototype.restart=function(){this._paused=!1},e.prototype.stop=function(e){var t=this._scene._activeAnimatables.indexOf(this);if(t>-1){for(var i=this._animations,r=0,t=i.length-1;t>=0;t--)"string"==typeof e&&i[t].name!=e||(i[t].reset(),i.splice(t,1),r++);i.length==r&&(this._scene._activeAnimatables.splice(t,1),this.onAnimationEnd&&this.onAnimationEnd())}},e.prototype._animate=function(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay||(this._pausedDelay=e),!0;this._localDelayOffset?this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null):this._localDelayOffset=e;var t,i=!1,r=this._animations;for(t=0;t<r.length;t++){var n=r[t],o=n.animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this.speedRatio);i=i||o}return this.animationStarted=i,i||(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1)),!i&&this.onAnimationEnd&&(this.onAnimationEnd(),this.onAnimationEnd=null),i},e})();e.Animatable=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._easingMode=e.EASINGMODE_EASEIN}return Object.defineProperty(e,"EASINGMODE_EASEIN",{get:function(){return e._EASINGMODE_EASEIN},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EASINGMODE_EASEOUT",{get:function(){return e._EASINGMODE_EASEOUT},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EASINGMODE_EASEINOUT",{get:function(){return e._EASINGMODE_EASEINOUT},enumerable:!0,configurable:!0}),e.prototype.setEasingMode=function(e){var t=Math.min(Math.max(e,0),2);this._easingMode=t},e.prototype.getEasingMode=function(){return this._easingMode},e.prototype.easeInCore=function(e){throw new Error("You must implement this method")},e.prototype.ease=function(t){switch(this._easingMode){case e.EASINGMODE_EASEIN:return this.easeInCore(t);case e.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-t)}return t>=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1),e.call(this),this.amplitude=t}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2),e.call(this),this.bounces=t,this.bounciness=i}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),h=Math.floor(a),c=h+1,l=(1-Math.pow(i,h))/(n*o),u=(1-Math.pow(i,c))/(n*o),f=.5*(l+u),d=e-f,p=f-l;return-Math.pow(1/i,t-h)/(p*p)*(d-p)*(d+p)},t})(t);e.BounceEase=n;var o=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=o;var s=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3),e.call(this),this.oscillations=t,this.springiness=i}return __extends(t,e),t.prototype.easeInCore=function(e){var t,i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return t=0==r?e:(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)},t})(t);e.ElasticEase=s;var a=(function(e){function t(t){void 0===t&&(t=2),e.call(this),this.exponent=t}return __extends(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=a;var h=(function(e){function t(t){void 0===t&&(t=2),e.call(this),this.power=t}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=h;var c=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=c;var l=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=l;var u=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=u;var f=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=f;var d=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1),t.call(this),this.x1=e,this.y1=i,this.x2=r,this.y2=n}return __extends(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=d})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){t.call(this,i,r.getScene()),this.name=i,this.children=new Array,this.animations=new Array,this._worldTransform=new e.Matrix,this._absoluteTransform=new e.Matrix,this._invertedAbsoluteTransform=new e.Matrix,this._scaleMatrix=e.Matrix.Identity(),this._scaleVector=new e.Vector3(1,1,1),this._negateScaleChildren=new e.Vector3(1,1,1),this._scalingDeterminant=1,this._syncScaleVector=function(){var t=this.getLocalMatrix(),i=t.m[0]*t.m[0]+t.m[1]*t.m[1]+t.m[2]*t.m[2],r=t.m[4]*t.m[4]+t.m[5]*t.m[5]+t.m[6]*t.m[6],n=t.m[8]*t.m[8]+t.m[9]*t.m[9]+t.m[10]*t.m[10],o=t.m[0]*t.m[1]*t.m[2]*t.m[3]<0?-1:1,s=t.m[4]*t.m[5]*t.m[6]*t.m[7]<0?-1:1,a=t.m[8]*t.m[9]*t.m[10]*t.m[11]<0?-1:1;this._scaleVector.x=o*Math.sqrt(i),this._scaleVector.y=s*Math.sqrt(r),this._scaleVector.z=a*Math.sqrt(n),this._parent&&(this._scaleVector.x/=this._parent._negateScaleChildren.x,this._scaleVector.y/=this._parent._negateScaleChildren.y,this._scaleVector.z/=this._parent._negateScaleChildren.z),e.Matrix.FromValuesToRef(this._scaleVector.x,0,0,0,0,this._scaleVector.y,0,0,0,0,this._scaleVector.z,0,0,0,0,1,this._scaleMatrix)},this._skeleton=r,this._matrix=o,this._baseMatrix=o,this._restPose=s?s:o.clone(),r.bones.push(this),n?(this._parent=n,n.children.push(this)):this._parent=null,this._updateDifferenceMatrix(),this.getAbsoluteTransform().determinant()<0&&(this._scalingDeterminant*=-1)}return __extends(i,t),i.prototype.getParent=function(){return this._parent},i.prototype.getLocalMatrix=function(){return this._matrix},i.prototype.getBaseMatrix=function(){return this._baseMatrix},i.prototype.getRestPose=function(){return this._restPose},i.prototype.returnToRest=function(){this.updateMatrix(this._restPose.clone())},i.prototype.getWorldMatrix=function(){return this._worldTransform},i.prototype.getInvertedAbsoluteTransform=function(){return this._invertedAbsoluteTransform},i.prototype.getAbsoluteTransform=function(){return this._absoluteTransform},i.prototype.updateMatrix=function(e,t){void 0===t&&(t=!0),this._baseMatrix=e.clone(),this._matrix=e.clone(),this._skeleton._markAsDirty(),t&&this._updateDifferenceMatrix()},i.prototype._updateDifferenceMatrix=function(e){e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);for(var t=0;t<this.children.length;t++)this.children[t]._updateDifferenceMatrix()},i.prototype.markAsDirty=function(){this._currentRenderId++,this._skeleton._markAsDirty()},i.prototype.copyAnimationRange=function(t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=null),0===this.animations.length&&(this.animations.push(new e.Animation(this.name,"_matrix",t.animations[0].framePerSecond,e.Animation.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));var s=t.animations[0].getRange(i);if(!s)return!1;for(var a,h,c,l=s.from,u=s.to,f=t.animations[0].getKeys(),d=t.length,p=t.getParent(),m=this.getParent(),g=n&&p&&d&&this.length&&d!==this.length,_=g?m.length/p.length:null,v=n&&!m&&o&&(1!==o.x||1!==o.y||1!==o.z),y=this.animations[0].getKeys(),x=0,b=f.length;x<b;x++)a=f[x],a.frame>=l&&a.frame<=u&&(n?(c=a.value.clone(),g?(h=c.getTranslation(),c.setTranslation(h.scaleInPlace(_))):v?(h=c.getTranslation(),c.setTranslation(h.multiplyInPlace(o))):c=a.value):c=a.value,y.push({frame:a.frame+r,value:c}));return this.animations[0].createRange(i,l+r,u+r),!0},i.prototype.translate=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix();if(i==e.Space.LOCAL)n.m[12]+=t.x,n.m[13]+=t.y,n.m[14]+=t.z;else{this._skeleton.computeAbsoluteTransforms();
var o=e.Tmp.Matrix[0],s=e.Tmp.Vector3[0];r?(o.copyFrom(this._parent.getAbsoluteTransform()),o.multiplyToRef(r.getWorldMatrix(),o)):o.copyFrom(this._parent.getAbsoluteTransform()),o.m[12]=0,o.m[13]=0,o.m[14]=0,o.invert(),e.Vector3.TransformCoordinatesToRef(t,o,s),n.m[12]+=s.x,n.m[13]+=s.y,n.m[14]+=s.z}this.markAsDirty()},i.prototype.setPosition=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix();if(i==e.Space.LOCAL)n.m[12]=t.x,n.m[13]=t.y,n.m[14]=t.z;else{this._skeleton.computeAbsoluteTransforms();var o=e.Tmp.Matrix[0],s=e.Tmp.Vector3[0];r?(o.copyFrom(this._parent.getAbsoluteTransform()),o.multiplyToRef(r.getWorldMatrix(),o)):o.copyFrom(this._parent.getAbsoluteTransform()),o.invert(),e.Vector3.TransformCoordinatesToRef(t,o,s),n.m[12]=s.x,n.m[13]=s.y,n.m[14]=s.z}this.markAsDirty()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.setScale=function(e,t,i,r){void 0===r&&(r=!1),this.animations[0]&&!this.animations[0].isStopped()&&(r||(this._negateScaleChildren.x=1/e,this._negateScaleChildren.y=1/t,this._negateScaleChildren.z=1/i),this._syncScaleVector()),this.scale(e/this._scaleVector.x,t/this._scaleVector.y,i/this._scaleVector.z,r)},i.prototype.scale=function(t,i,r,n){void 0===n&&(n=!1);var o=this.getLocalMatrix(),s=e.Tmp.Matrix[0];s.copyFrom(o);var a=e.Tmp.Matrix[1];a.copyFrom(s),a.invert();var h=e.Tmp.Matrix[2];e.Matrix.FromValuesToRef(t,0,0,0,0,i,0,0,0,0,r,0,0,0,0,1,h),this._scaleMatrix.multiplyToRef(h,this._scaleMatrix),this._scaleVector.x*=t,this._scaleVector.y*=i,this._scaleVector.z*=r,o.multiplyToRef(a,o),o.multiplyToRef(h,o),o.multiplyToRef(s,o);var c=this.getParent();c?o.multiplyToRef(c.getAbsoluteTransform(),this.getAbsoluteTransform()):this.getAbsoluteTransform().copyFrom(o);var l=this.children.length;h.invert();for(var u=0;u<l;u++){var f=this.children[u],d=f.getLocalMatrix();d.multiplyToRef(h,d);var p=f.getLocalMatrix();p.m[12]*=t,p.m[13]*=i,p.m[14]*=r}if(this.computeAbsoluteTransforms(),n)for(var u=0;u<l;u++)this.children[u].scale(t,i,r,n);this.markAsDirty()},i.prototype.setYawPitchRoll=function(t,i,r,n,o){void 0===n&&(n=e.Space.LOCAL);var s=e.Tmp.Matrix[0];e.Matrix.RotationYawPitchRollToRef(t,i,r,s);var a=e.Tmp.Matrix[1];this._getNegativeRotationToRef(a,n,o),a.multiplyToRef(s,s),this._rotateWithMatrix(s,n,o)},i.prototype.rotate=function(t,i,r,n){void 0===r&&(r=e.Space.LOCAL);var o=e.Tmp.Matrix[0];o.m[12]=0,o.m[13]=0,o.m[14]=0,e.Matrix.RotationAxisToRef(t,i,o),this._rotateWithMatrix(o,r,n)},i.prototype.setAxisAngle=function(t,i,r,n){void 0===r&&(r=e.Space.LOCAL);var o=e.Tmp.Matrix[0];e.Matrix.RotationAxisToRef(t,i,o);var s=e.Tmp.Matrix[1];this._getNegativeRotationToRef(s,r,n),s.multiplyToRef(o,o),this._rotateWithMatrix(o,r,n)},i.prototype.setRotation=function(t,i,r){void 0===i&&(i=e.Space.LOCAL),this.setYawPitchRoll(t.y,t.x,t.z,i,r)},i.prototype.setRotationQuaternion=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=e.Tmp.Matrix[0];this._getNegativeRotationToRef(n,i,r);var o=e.Tmp.Matrix[1];e.Matrix.FromQuaternionToRef(t,o),n.multiplyToRef(o,o),this._rotateWithMatrix(o,i,r)},i.prototype.setRotationMatrix=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=e.Tmp.Matrix[0];this._getNegativeRotationToRef(n,i,r);var o=e.Tmp.Matrix[1];o.copyFrom(t),n.multiplyToRef(t,o),this._rotateWithMatrix(o,i,r)},i.prototype._rotateWithMatrix=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix(),o=n.m[12],s=n.m[13],a=n.m[14],h=this.getParent(),c=e.Tmp.Matrix[3],l=e.Tmp.Matrix[4];h?(i==e.Space.WORLD?r?(c.copyFrom(r.getWorldMatrix()),h.getAbsoluteTransform().multiplyToRef(c,c)):c.copyFrom(h.getAbsoluteTransform()):c=h._scaleMatrix,l.copyFrom(c),l.invert(),n.multiplyToRef(c,n),n.multiplyToRef(t,n),n.multiplyToRef(l,n)):i==e.Space.WORLD&&r?(c.copyFrom(r.getWorldMatrix()),l.copyFrom(c),l.invert(),n.multiplyToRef(c,n),n.multiplyToRef(t,n),n.multiplyToRef(l,n)):n.multiplyToRef(t,n),n.m[12]=o,n.m[13]=s,n.m[14]=a,this.computeAbsoluteTransforms(),this.markAsDirty()},i.prototype._getNegativeRotationToRef=function(t,i,r){if(void 0===i&&(i=e.Space.LOCAL),i==e.Space.WORLD){var n=e.Tmp.Matrix[2];if(n.copyFrom(this._scaleMatrix),t.copyFrom(this.getAbsoluteTransform()),r){t.multiplyToRef(r.getWorldMatrix(),t);var o=e.Tmp.Matrix[3];e.Matrix.ScalingToRef(r.scaling.x,r.scaling.y,r.scaling.z,o),n.multiplyToRef(o,n)}t.invert(),n.m[0]*=this._scalingDeterminant,t.multiplyToRef(n,t)}else{t.copyFrom(this.getLocalMatrix()),t.invert();var n=e.Tmp.Matrix[2];if(n.copyFrom(this._scaleMatrix),this._parent){var s=e.Tmp.Matrix[3];s.copyFrom(this._parent._scaleMatrix),s.invert(),s.multiplyToRef(t,t)}else n.m[0]*=this._scalingDeterminant;t.multiplyToRef(n,t)}},i.prototype.getScale=function(){return this._scaleVector.clone()},i.prototype.getScaleToRef=function(e){e.copyFrom(this._scaleVector)},i.prototype.getPosition=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Vector3.Zero();return this.getPositionToRef(t,i,r),r},i.prototype.getPositionToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL){var n=this.getLocalMatrix();r.x=n.m[12],r.y=n.m[13],r.z=n.m[14]}else{this._skeleton.computeAbsoluteTransforms();var o=e.Tmp.Matrix[0];i?(o.copyFrom(this.getAbsoluteTransform()),o.multiplyToRef(i.getWorldMatrix(),o)):o=this.getAbsoluteTransform(),r.x=o.m[12],r.y=o.m[13],r.z=o.m[14]}},i.prototype.getAbsolutePosition=function(t){var i=e.Vector3.Zero();return this.getPositionToRef(e.Space.WORLD,t,i),i},i.prototype.getAbsolutePositionToRef=function(t,i){this.getPositionToRef(e.Space.WORLD,t,i)},i.prototype.computeAbsoluteTransforms=function(){if(this._parent)this._matrix.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform);else{this._absoluteTransform.copyFrom(this._matrix);var e=this._skeleton.getPoseMatrix();e&&this._absoluteTransform.multiplyToRef(e,this._absoluteTransform)}for(var t=this.children,i=t.length,r=0;r<i;r++)t[r].computeAbsoluteTransforms()},i.prototype.getDirection=function(t,i){var r=e.Vector3.Zero();return this.getDirectionToRef(t,i,r),r},i.prototype.getDirectionToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];n.copyFrom(this.getAbsoluteTransform()),i&&n.multiplyToRef(i.getWorldMatrix(),n),e.Vector3.TransformNormalToRef(t,n,r),r.normalize()},i.prototype.getRotation=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Vector3.Zero();return this.getRotationToRef(t,i,r),r},i.prototype.getRotationToRef=function(t,i,r){void 0===t&&(t=e.Space.LOCAL);var n=e.Tmp.Quaternion[0];this.getRotationQuaternionToRef(t,i,n),n.toEulerAnglesToRef(r)},i.prototype.getRotationQuaternion=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Quaternion.Identity();return this.getRotationQuaternionToRef(t,i,r),r},i.prototype.getRotationQuaternionToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL)this.getLocalMatrix().decompose(e.Tmp.Vector3[0],r,e.Tmp.Vector3[1]);else{var n=e.Tmp.Matrix[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.m[0]*=this._scalingDeterminant,n.m[1]*=this._scalingDeterminant,n.m[2]*=this._scalingDeterminant,n.decompose(e.Tmp.Vector3[0],r,e.Tmp.Vector3[1])}},i.prototype.getRotationMatrix=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Matrix.Identity();return this.getRotationMatrixToRef(t,i,r),r},i.prototype.getRotationMatrixToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(r);else{var n=e.Tmp.Matrix[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.m[0]*=this._scalingDeterminant,n.m[1]*=this._scalingDeterminant,n.m[2]*=this._scalingDeterminant,n.getRotationMatrixToRef(r)}},i.prototype.getAbsolutePositionFromLocal=function(t,i){var r=e.Vector3.Zero();return this.getAbsolutePositionFromLocalToRef(t,i,r),r},i.prototype.getAbsolutePositionFromLocalToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];i?(n.copyFrom(this.getAbsoluteTransform()),n.multiplyToRef(i.getWorldMatrix(),n)):n=this.getAbsoluteTransform(),e.Vector3.TransformCoordinatesToRef(t,n,r)},i.prototype.getLocalPositionFromAbsolute=function(t,i){var r=e.Vector3.Zero();return this.getLocalPositionFromAbsoluteToRef(t,i,r),r},i.prototype.getLocalPositionFromAbsoluteToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];n.copyFrom(this.getAbsoluteTransform()),i&&n.multiplyToRef(i.getWorldMatrix(),n),n.invert(),e.Vector3.TransformCoordinatesToRef(t,n,r)},i})(e.Node);e.Bone=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){if(this.targetPosition=e.Vector3.Zero(),this.poleTargetPosition=e.Vector3.Zero(),this.poleTargetLocalOffset=e.Vector3.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=e.Quaternion.Identity(),this._bone1Mat=e.Matrix.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._tmpVec1=e.Vector3.Zero(),this._tmpVec2=e.Vector3.Zero(),this._tmpVec3=e.Vector3.Zero(),this._tmpVec4=e.Vector3.Zero(),this._tmpVec5=e.Vector3.Zero(),this._tmpMat1=e.Matrix.Identity(),this._tmpMat2=e.Matrix.Identity(),this._tmpQuat1=e.Quaternion.Identity(),this._rightHandedSystem=!1,this._bendAxis=e.Vector3.Right(),this._slerping=!1,this._bone2=i,this._bone1=i.getParent(),this.mesh=t,i.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=1),this._bone1.length){var n=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*n.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*o.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var s=this._bone2.children[0].getAbsolutePosition(t),a=this._bone2.getAbsolutePosition(t),h=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(s,a),this._bone2Length=e.Vector3.Distance(a,h)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var t=this._bone1,i=this.targetPosition,r=this.poleTargetPosition,n=this._tmpMat1,o=this._tmpMat2;this.targetMesh&&i.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,r):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),r);var s=this._tmpVec1,a=this._tmpVec2,h=this._tmpVec3,c=this._tmpVec4,l=this._tmpVec5;t.getAbsolutePositionToRef(this.mesh,s),r.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),i.subtractToRef(s,c),c.normalize(),e.Vector3.CrossToRef(c,l,a),a.normalize(),e.Vector3.CrossToRef(c,a,h),h.normalize(),e.Matrix.FromXYZAxesToRef(h,c,a,n);var u=this._bone1Length,f=this._bone2Length,d=e.Vector3.Distance(s,i);this._maxReach>0&&(d=Math.min(this._maxReach,d));var p=(f*f+d*d-u*u)/(2*f*d),m=(d*d+u*u-f*f)/(2*d*u);p>1&&(p=1),m>1&&(m=1),p<-1&&(p=-1),m<-1&&(m=-1);var g=Math.acos(p),_=Math.acos(m),v=-g-_;this._rightHandedSystem?(e.Matrix.RotationYawPitchRollToRef(0,0,.5*Math.PI,o),o.multiplyToRef(n,n),e.Matrix.RotationAxisToRef(this._bendAxis,_,o),o.multiplyToRef(n,n)):(this._tmpVec1.copyFrom(this._bendAxis),this._tmpVec1.x*=-1,e.Matrix.RotationAxisToRef(this._tmpVec1,-_,o),o.multiplyToRef(n,n)),this.poleAngle&&(e.Matrix.RotationAxisToRef(c,this.poleAngle,o),n.multiplyToRef(o,n)),this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(n,this._tmpQuat1),e.Quaternion.SlerpToRef(this._bone1Quat,this._tmpQuat1,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(n,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(n),this._slerping=!1),this._bone2.setAxisAngle(this._bendAxis,v,e.Space.LOCAL),this._bone2Ang=v},t})();e.BoneIKController=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){this.upAxis=e.Vector3.Up(),this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this._tmpVec1=e.Vector3.Zero(),this._tmpVec2=e.Vector3.Zero(),this._tmpVec3=e.Vector3.Zero(),this._tmpVec4=e.Vector3.Zero(),this._tmpMat1=e.Matrix.Identity(),this._tmpMat2=e.Matrix.Identity(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll))}return t.prototype.update=function(){var t=this.bone,i=this.target,r=this._tmpVec1,n=this._tmpVec2,o=this._tmpVec3,s=this._tmpVec4,a=this._tmpMat1,h=this._tmpMat2;t.getAbsolutePositionToRef(this.mesh,r),i.subtractToRef(r,n),n.normalize(),e.Vector3.CrossToRef(this.upAxis,n,o),o.normalize(),e.Vector3.CrossToRef(n,o,s),s.normalize(),e.Matrix.FromXYZAxesToRef(o,s,n,a),(this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(e.Matrix.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,h),h.multiplyToRef(a,a)),this.bone.setRotationMatrix(a,e.Space.WORLD,this.mesh)},t})();e.BoneLookController=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.id=i,this.bones=new Array,this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=e.Matrix.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this.bones=[],this._scene=r,r.skeletons.push(this),this._isDirty=!0}return t.prototype.getTransformMatrices=function(e){return this.needInitialSkinMatrix&&e._bonesTransformMatrices?e._bonesTransformMatrices:this._transformMatrices},t.prototype.getScene=function(){return this._scene},t.prototype.toString=function(e){var t="Name: "+this.name+", nBones: "+this.bones.length;if(t+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},t.prototype.getBoneIndexByName=function(e){for(var t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1},t.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=new e.AnimationRange(t,i,r);for(var n=0,o=this.bones.length;n<o;n++)this.bones[n].animations[0]&&this.bones[n].animations[0].createRange(t,i,r)}},t.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=void 0},t.prototype.getAnimationRange=function(e){return this._ranges[e]},t.prototype.getAnimationRanges=function(){var e,t=[],i=0;for(e in this._ranges)t[i]=this._ranges[e],i++;return t},t.prototype.copyAnimationRange=function(t,i,r){if(void 0===r&&(r=!1),this._ranges[i]||!t.getAnimationRange(i))return!1;var n,o,s=!0,a=this._getHighestAnimationFrame()+1,h={},c=t.bones;for(o=0,n=c.length;o<n;o++)h[c[o].name]=c[o];this.bones.length!==c.length&&(e.Tools.Warn("copyAnimationRange: this rig has "+this.bones.length+" bones, while source as "+c.length),s=!1);var l=r&&this.dimensionsAtRest&&t.dimensionsAtRest?this.dimensionsAtRest.divide(t.dimensionsAtRest):null;for(o=0,n=this.bones.length;o<n;o++){var u=this.bones[o].name,f=h[u];f?s=s&&this.bones[o].copyAnimationRange(f,i,a,r,l):(e.Tools.Warn("copyAnimationRange: not same rig, missing source bone "+u),s=!1)}var d=t.getAnimationRange(i);return this._ranges[i]=new e.AnimationRange(i,d.from+a,d.to+a),s},t.prototype.returnToRest=function(){for(var e=0;e<this.bones.length;e++)this.bones[e].returnToRest()},t.prototype._getHighestAnimationFrame=function(){for(var e=0,t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){var r=this.bones[t].animations[0].getHighestFrame();e<r&&(e=r)}return e},t.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},t.prototype._markAsDirty=function(){this._isDirty=!0},t.prototype._registerMeshWithPoseMatrix=function(e){this._meshesWithPoseMatrix.push(e)},t.prototype._unregisterMeshWithPoseMatrix=function(e){var t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){for(var i=0;i<this.bones.length;i++){var r=this.bones[i],n=r.getParent();n?r.getLocalMatrix().multiplyToRef(n.getWorldMatrix(),r.getWorldMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getWorldMatrix()):r.getWorldMatrix().copyFrom(r.getLocalMatrix()),r.getInvertedAbsoluteTransform().multiplyToArray(r.getWorldMatrix(),e,16*i)}this._identity.copyToArray(e,16*this.bones.length)},t.prototype.prepare=function(){if(this._isDirty){if(this.needInitialSkinMatrix)for(var t=0;t<this._meshesWithPoseMatrix.length;t++){var i=this._meshesWithPoseMatrix[t];i._bonesTransformMatrices&&i._bonesTransformMatrices.length===16*(this.bones.length+1)||(i._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)));for(var r=i.getPoseMatrix(),n=0;n<this.bones.length;n++){var o=this.bones[n];if(!o.getParent()){var s=o.getBaseMatrix();s.multiplyToRef(r,e.Tmp.Matrix[0]),o._updateDifferenceMatrix(e.Tmp.Matrix[0])}}this._computeTransformMatrices(i._bonesTransformMatrices,r)}else this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1))),this._computeTransformMatrices(this._transformMatrices,null);this._isDirty=!1,this._scene._activeBones.addCount(this.bones.length,!1)}},t.prototype.getAnimatables=function(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(var e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables},t.prototype.clone=function(i,r){var n=new t(i,r||i,this._scene);n.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var o=0;o<this.bones.length;o++){var s=this.bones[o],a=null;if(s.getParent()){var h=this.bones.indexOf(s.getParent());a=n.bones[h]}var c=new e.Bone(s.name,n,a,s.getBaseMatrix().clone(),s.getRestPose().clone());e.Tools.DeepCopy(s.animations,c.animations)}if(this._ranges){n._ranges={};for(var l in this._ranges)n._ranges[l]=this._ranges[l].clone()}return this._isDirty=!0,n},t.prototype.enableBlending=function(e){void 0===e&&(e=.01),this.bones.forEach((function(t){t.animations.forEach((function(t){t.enableBlending=!0,t.blendingSpeed=e}))}))},t.prototype.dispose=function(){this._meshesWithPoseMatrix=[],this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this)},t.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,e.dimensionsAtRest=this.dimensionsAtRest,e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var t=0;t<this.bones.length;t++){var i=this.bones[t],r={parentBoneIndex:i.getParent()?this.bones.indexOf(i.getParent()):-1,name:i.name,matrix:i.getLocalMatrix().toArray(),rest:i.getRestPose().toArray()};e.bones.push(r),i.length&&(r.length=i.length),i.animations&&i.animations.length>0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(var n in this._ranges){var o={};o.name=n,o.from=this._ranges[n].from,o.to=this._ranges[n].to,e.ranges.push(o)}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o<i.bones.length;o++){var s=i.bones[o],a=null;s.parentBoneIndex>-1&&(a=n.bones[s.parentBoneIndex]);var h=s.rest?e.Matrix.FromArray(s.rest):null,c=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),h);s.length&&(c.length=s.length),s.animation&&c.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o<i.ranges.length;o++){var l=i.ranges[o];n.createAnimationRange(l.name,l.from,l.to)}return n},t.prototype.computeAbsoluteTransforms=function(e){void 0===e&&(e=!1);var t=this._scene.getRenderId();(this._lastAbsoluteTransformsUpdateId!=t||e)&&(this.bones[0].computeAbsoluteTransforms(),this._lastAbsoluteTransformsUpdateId=t)},t.prototype.getPoseMatrix=function(){var e;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t})();e.Skeleton=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,h,c,l,u){void 0===a&&(a=e.Texture.NEAREST_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),this.name=t,this.width=-1,this.height=-1,this.enablePixelPerfectMode=!1,this._reusable=!1,this._textures=new e.SmartArray(2),this._currentRenderTextureInd=0,this._scaleRatio=new e.Vector2(1,1),this.onActivateObservable=new e.Observable,this.onSizeChangedObservable=new e.Observable,this.onApplyObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,null!=s?(this._camera=s,this._scene=s.getScene(),s.attachPostProcess(this),this._engine=this._scene.getEngine()):this._engine=h,this._options=o,this.renderTargetSamplingMode=a?a:e.Texture.NEAREST_SAMPLINGMODE,this._reusable=c||!1,this._textureType=u,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=i,this._parameters=r||[],this._parameters.push("scale"),this.updateEffect(l)}return Object.defineProperty(t.prototype,"onActivate",{set:function(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),this._onActivateObserver=this.onActivateObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onSizeChanged",{set:function(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onApply",{set:function(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.updateEffect=function(e){this._effect=this._engine.createEffect({vertex:"postprocess",fragment:this._fragmentUrl},["position"],this._parameters,this._samplers,void 0!==e?e:"")},t.prototype.isReusable=function(){return this._reusable},t.prototype.markTextureDirty=function(){this.width=-1},t.prototype.activate=function(t,i){t=t||this._camera;var r=t.getScene(),n=t.getEngine().getCaps().maxTextureSize,o=(i?i._width:this._engine.getRenderingCanvas().width)*this._options|0,s=(i?i._height:this._engine.getRenderingCanvas().height)*this._options|0,a=this._options.width||o,h=this._options.height||s;if(this.renderTargetSamplingMode!==e.Texture.NEAREST_SAMPLINGMODE&&(this._options.width||(a=e.Tools.GetExponentOfTwo(a,n)),this._options.height||(h=e.Tools.GetExponentOfTwo(h,n))),this.width!==a||this.height!==h){if(this._textures.length>0){for(var c=0;c<this._textures.length;c++)this._engine._releaseTexture(this._textures.data[c]);this._textures.reset()}this.width=a,this.height=h;var l={width:this.width,height:this.height},u={generateMipMaps:!1,generateDepthBuffer:0===t._postProcesses.indexOf(this),generateStencilBuffer:0===t._postProcesses.indexOf(this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType};this._textures.push(this._engine.createRenderTargetTexture(l,u)),this._reusable&&this._textures.push(this._engine.createRenderTargetTexture(l,u)),this.onSizeChangedObservable.notifyObservers(this)}this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/a,s/h),this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd],0,o,s)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd])),this.onActivateObservable.notifyObservers(t),this.clearColor?this._engine.clear(this.clearColor,!0,!0,!0):this._engine.clear(r.clearColor,r.autoClear||r.forceWireframe,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2)},Object.defineProperty(t.prototype,"isSupported",{get:function(){return this._effect.isSupported},enumerable:!0,configurable:!0}),t.prototype.apply=function(){return this._effect.isReady()?(this._engine.enableEffect(this._effect),this._engine.setState(!1),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._effect._bindTexture("textureSampler",this._textures.data[this._currentRenderTextureInd]),this._effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effect),this._effect):null},t.prototype.dispose=function(e){if(e=e||this._camera,this._textures.length>0){for(var t=0;t<this._textures.length;t++)this._engine._releaseTexture(this._textures.data[t]);this._textures.reset()}if(e){e.detachPostProcess(this);var i=e._postProcesses.indexOf(this);0===i&&e._postProcesses.length>0&&this._camera._postProcesses[0].markTextureDirty(),this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,(!1),(!1),2);var i=[];i.push(0),i.push(1),i.push(2),i.push(0),i.push(2),i.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(i)}},t.prototype._prepareFrame=function(e){var t=this._scene.activeCamera._postProcesses;return!(0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(this._scene.activeCamera,e),!0)},t.prototype.directRender=function(e,t){for(var i=this._scene.getEngine(),r=0;r<e.length;r++){r<e.length-1?e[r+1].activate(this._scene.activeCamera,t):t?i.bindFramebuffer(t):i.restoreDefaultFramebuffer();var n=e[r],o=n.apply();o&&(n.onBeforeRenderObservable.notifyObservers(o),this._prepareBuffers(),i.bindBuffers(this._vertexBuffers,this._indexBuffer,o),i.draw(!0,0,6),n.onAfterRenderObservable.notifyObservers(o))}i.setDepthBuffer(!0),i.setDepthWrite(!0)},t.prototype._finalizeFrame=function(e,t,i,r){if(r=r||this._scene.activeCamera._postProcesses,0!==r.length&&this._scene.postProcessesEnabled){for(var n=this._scene.getEngine(),o=0,s=r.length;o<s&&(o<s-1?r[o+1].activate(this._scene.activeCamera,t):t?n.bindFramebuffer(t,i):n.restoreDefaultFramebuffer(),!e);o++){var a=r[o],h=a.apply();h&&(a.onBeforeRenderObservable.notifyObservers(h),this._prepareBuffers(),n.bindBuffers(this._vertexBuffers,this._indexBuffer,h),n.draw(!0,0,6),a.onAfterRenderObservable.notifyObservers(h))}n.setDepthBuffer(!0),n.setDepthWrite(!0)}},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)},t})();e.PostProcessManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"pass",null,null,i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.PassPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}return Object.defineProperty(e.prototype,"physicsJoint",{get:function(){return this._physicsJoint},set:function(e){this._physicsJoint,this._physicsJoint=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"physicsPlugin",{set:function(e){this._physicsPlugin=e},enumerable:!0,configurable:!0}),e.prototype.executeNativeFunction=function(e){e(this._physicsPlugin.world,this._physicsJoint)},e.DistanceJoint=0,e.HingeJoint=1,e.BallAndSocketJoint=2,e.WheelJoint=3,e.SliderJoint=4,e.PrismaticJoint=5,e.UniversalJoint=6,e.Hinge2Joint=e.WheelJoint,e.PointToPointJoint=8,e.SpringJoint=9,e.LockJoint=10,e})();e.PhysicsJoint=t;var i=(function(e){function i(i){e.call(this,t.DistanceJoint,i)}return __extends(i,e),i.prototype.updateDistance=function(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)},i})(t);e.DistanceJoint=i;var r=(function(e){function t(t,i){e.call(this,t,i)}return __extends(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t})(t);e.MotorEnabledJoint=r;var n=(function(e){function i(i){e.call(this,t.HingeJoint,i)}return __extends(i,e),i.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e,t)},i.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},i})(r);e.HingeJoint=n;var o=(function(e){function i(i){e.call(this,t.Hinge2Joint,i)}return __extends(i,e),i.prototype.setMotor=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setMotor(this,e,t,i)},i.prototype.setLimit=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setLimit(this,e,t,i)},i})(r);e.Hinge2Joint=o})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){var o=this;return void 0===r&&(r={mass:0}),this.object=t,this.type=i,this._options=r,this._scene=n,this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=e.Vector3.Zero(),this._tmpPositionWithDelta=e.Vector3.Zero(),this._tmpRotationWithDelta=new e.Quaternion,this.beforeStep=function(){o.object.position.subtractToRef(o._deltaPosition,o._tmpPositionWithDelta),o._deltaRotationConjugated?o.object.rotationQuaternion.multiplyToRef(o._deltaRotationConjugated,o._tmpRotationWithDelta):o._tmpRotationWithDelta.copyFrom(o.object.rotationQuaternion),o._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(o,o._tmpPositionWithDelta,o._tmpRotationWithDelta),o._onBeforePhysicsStepCallbacks.forEach((function(e){e(o)}))},this.afterStep=function(){o._onAfterPhysicsStepCallbacks.forEach((function(e){e(o)})),o._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(o),o.object.position.addInPlace(o._deltaPosition),o._deltaRotation&&o.object.rotationQuaternion.multiplyInPlace(o._deltaRotation)},this.onCollide=function(e){if(o._onPhysicsCollideCallbacks.length){var t=o._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&o._onPhysicsCollideCallbacks.filter((function(e){return e.otherImpostors.indexOf(t)!==-1})).forEach((function(e){
e.callback(o,t)}))}},this.object?(!this._scene&&t.getScene&&(this._scene=t.getScene()),this._physicsEngine=this._scene.getPhysicsEngine(),void(this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new e.Quaternion),this._options.mass=void 0===r.mass?0:r.mass,this._options.friction=void 0===r.friction?.2:r.friction,this._options.restitution=void 0===r.restitution?.2:r.restitution,this._joints=[],this.object.parent||this._init()):e.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):void e.Tools.Error("No object was provided. A physics object is obligatory")}return t.prototype._init=function(){this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this.parent||this._physicsEngine.addImpostor(this)},t.prototype._getPhysicsParent=function(){if(this.object.parent instanceof e.AbstractMesh){var t=this.object.parent;return t.physicsImpostor}},t.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},t.prototype.setScalingUpdated=function(e){this.forceUpdate()},t.prototype.forceUpdate=function(){this._init(),this.parent&&this.parent.forceUpdate()},Object.defineProperty(t.prototype,"physicsBody",{get:function(){return this._parent?this._parent.physicsBody:this._physicsBody},set:function(e){this._physicsBody&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},set:function(e){this._parent=e},enumerable:!0,configurable:!0}),t.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},t.prototype.getObjectExtendSize=function(){return this.object.getBoundingInfo?(this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling)):t.DEFAULT_OBJECT_SIZE},t.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.center:this.object.position},t.prototype.getParam=function(e){return this._options[e]},t.prototype.setParam=function(e,t){this._options[e]=t,this._bodyUpdateRequired=!0},t.prototype.setMass=function(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)},t.prototype.getLinearVelocity=function(){return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this)},t.prototype.setLinearVelocity=function(e){this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)},t.prototype.getAngularVelocity=function(){return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this)},t.prototype.setAngularVelocity=function(e){this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)},t.prototype.executeNativeFunction=function(e){e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},t.prototype.registerBeforePhysicsStep=function(e){this._onBeforePhysicsStepCallbacks.push(e)},t.prototype.unregisterBeforePhysicsStep=function(t){var i=this._onBeforePhysicsStepCallbacks.indexOf(t);i>-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=this._onPhysicsCollideCallbacks.indexOf({callback:i,otherImpostors:r});n>-1?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.applyForce=function(e,t){this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t)},t.prototype.applyImpulse=function(e,t){this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t)},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);this.addJoint(t,n)},t.prototype.addJoint=function(e,t){this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine.addJoint(this,e,t)},t.prototype.sleep=function(){this._physicsEngine.getPhysicsPlugin().sleepBody(this)},t.prototype.wakeUp=function(){this._physicsEngine.getPhysicsPlugin().wakeUpBody(this)},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate())},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,(-9.807),0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t]},t.prototype.getImpostorWithPhysicsBody=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t]},t.NoImpostor=e.PhysicsImpostor.NoImpostor,t.SphereImpostor=e.PhysicsImpostor.SphereImpostor,t.BoxImpostor=e.PhysicsImpostor.BoxImpostor,t.PlaneImpostor=e.PhysicsImpostor.PlaneImpostor,t.MeshImpostor=e.PhysicsImpostor.MeshImpostor,t.CylinderImpostor=e.PhysicsImpostor.CylinderImpostor,t.HeightmapImpostor=e.PhysicsImpostor.HeightmapImpostor,t.CapsuleImpostor=-1,t.ConeImpostor=-1,t.ConvexHullImpostor=-1,t.Epsilon=.001,t})();e.PhysicsEngine=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.prototype.set=function(t,i){switch(i){case e.VertexBuffer.PositionKind:this.positions=t;break;case e.VertexBuffer.NormalKind:this.normals=t;break;case e.VertexBuffer.UVKind:this.uvs=t;break;case e.VertexBuffer.UV2Kind:this.uvs2=t;break;case e.VertexBuffer.UV3Kind:this.uvs3=t;break;case e.VertexBuffer.UV4Kind:this.uvs4=t;break;case e.VertexBuffer.UV5Kind:this.uvs5=t;break;case e.VertexBuffer.UV6Kind:this.uvs6=t;break;case e.VertexBuffer.ColorKind:this.colors=t;break;case e.VertexBuffer.MatricesIndicesKind:this.matricesIndices=t;break;case e.VertexBuffer.MatricesWeightsKind:this.matricesWeights=t;break;case e.VertexBuffer.MatricesIndicesExtraKind:this.matricesIndicesExtra=t;break;case e.VertexBuffer.MatricesWeightsExtraKind:this.matricesWeightsExtra=t}},t.prototype.applyToMesh=function(e,t){this._applyTo(e,t)},t.prototype.applyToGeometry=function(e,t){this._applyTo(e,t)},t.prototype.updateMesh=function(e,t,i){this._update(e)},t.prototype.updateGeometry=function(e,t,i){this._update(e)},t.prototype._applyTo=function(t,i){this.positions&&t.setVerticesData(e.VertexBuffer.PositionKind,this.positions,i),this.normals&&t.setVerticesData(e.VertexBuffer.NormalKind,this.normals,i),this.uvs&&t.setVerticesData(e.VertexBuffer.UVKind,this.uvs,i),this.uvs2&&t.setVerticesData(e.VertexBuffer.UV2Kind,this.uvs2,i),this.uvs3&&t.setVerticesData(e.VertexBuffer.UV3Kind,this.uvs3,i),this.uvs4&&t.setVerticesData(e.VertexBuffer.UV4Kind,this.uvs4,i),this.uvs5&&t.setVerticesData(e.VertexBuffer.UV5Kind,this.uvs5,i),this.uvs6&&t.setVerticesData(e.VertexBuffer.UV6Kind,this.uvs6,i),this.colors&&t.setVerticesData(e.VertexBuffer.ColorKind,this.colors,i),this.matricesIndices&&t.setVerticesData(e.VertexBuffer.MatricesIndicesKind,this.matricesIndices,i),this.matricesWeights&&t.setVerticesData(e.VertexBuffer.MatricesWeightsKind,this.matricesWeights,i),this.matricesIndicesExtra&&t.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,i),this.matricesWeightsExtra&&t.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,i),this.indices&&t.setIndices(this.indices)},t.prototype._update=function(t,i,r){this.positions&&t.updateVerticesData(e.VertexBuffer.PositionKind,this.positions,i,r),this.normals&&t.updateVerticesData(e.VertexBuffer.NormalKind,this.normals,i,r),this.uvs&&t.updateVerticesData(e.VertexBuffer.UVKind,this.uvs,i,r),this.uvs2&&t.updateVerticesData(e.VertexBuffer.UV2Kind,this.uvs2,i,r),this.uvs3&&t.updateVerticesData(e.VertexBuffer.UV3Kind,this.uvs3,i,r),this.uvs4&&t.updateVerticesData(e.VertexBuffer.UV4Kind,this.uvs4,i,r),this.uvs5&&t.updateVerticesData(e.VertexBuffer.UV5Kind,this.uvs5,i,r),this.uvs6&&t.updateVerticesData(e.VertexBuffer.UV6Kind,this.uvs6,i,r),this.colors&&t.updateVerticesData(e.VertexBuffer.ColorKind,this.colors,i,r),this.matricesIndices&&t.updateVerticesData(e.VertexBuffer.MatricesIndicesKind,this.matricesIndices,i,r),this.matricesWeights&&t.updateVerticesData(e.VertexBuffer.MatricesWeightsKind,this.matricesWeights,i,r),this.matricesIndicesExtra&&t.updateVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,i,r),this.matricesWeightsExtra&&t.updateVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,i,r),this.indices&&t.setIndices(this.indices)},t.prototype.transform=function(t){var i,r=e.Vector3.Zero();if(this.positions){var n=e.Vector3.Zero();for(i=0;i<this.positions.length;i+=3)e.Vector3.FromArrayToRef(this.positions,i,n),e.Vector3.TransformCoordinatesToRef(n,t,r),this.positions[i]=r.x,this.positions[i+1]=r.y,this.positions[i+2]=r.z}if(this.normals){var o=e.Vector3.Zero();for(i=0;i<this.normals.length;i+=3)e.Vector3.FromArrayToRef(this.normals,i,o),e.Vector3.TransformNormalToRef(o,t,r),this.normals[i]=r.x,this.normals[i+1]=r.y,this.normals[i+2]=r.z}},t.prototype.merge=function(e){if(e.indices){this.indices||(this.indices=[]);for(var t=this.positions?this.positions.length/3:0,i=0;i<e.indices.length;i++)this.indices.push(e.indices[i]+t)}this.positions=this._mergeElement(this.positions,e.positions),this.normals=this._mergeElement(this.normals,e.normals),this.uvs=this._mergeElement(this.uvs,e.uvs),this.uvs2=this._mergeElement(this.uvs2,e.uvs2),this.uvs3=this._mergeElement(this.uvs3,e.uvs3),this.uvs4=this._mergeElement(this.uvs4,e.uvs4),this.uvs5=this._mergeElement(this.uvs5,e.uvs5),this.uvs6=this._mergeElement(this.uvs6,e.uvs6),this.colors=this._mergeElement(this.colors,e.colors),this.matricesIndices=this._mergeElement(this.matricesIndices,e.matricesIndices),this.matricesWeights=this._mergeElement(this.matricesWeights,e.matricesWeights),this.matricesIndicesExtra=this._mergeElement(this.matricesIndicesExtra,e.matricesIndicesExtra),this.matricesWeightsExtra=this._mergeElement(this.matricesWeightsExtra,e.matricesWeightsExtra)},t.prototype._mergeElement=function(e,t){if(!t)return e;if(!e)return t;var i=t.length+e.length,r=e instanceof Float32Array,n=t instanceof Float32Array;if(r){var o=new Float32Array(i);return o.set(e),o.set(t,e.length),o}if(n){for(var s=e.slice(0),a=0,i=t.length;a<i;a++)s.push(t[a]);return s}return e.concat(t)},t.prototype.serialize=function(){var e=this.serialize();return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e},t.ExtractFromMesh=function(e,i){return t._ExtractFrom(e,i)},t.ExtractFromGeometry=function(e,i){return t._ExtractFrom(e,i)},t._ExtractFrom=function(i,r){var n=new t;return i.isVerticesDataPresent(e.VertexBuffer.PositionKind)&&(n.positions=i.getVerticesData(e.VertexBuffer.PositionKind,r)),i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.normals=i.getVerticesData(e.VertexBuffer.NormalKind,r)),i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.uvs=i.getVerticesData(e.VertexBuffer.UVKind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(n.uvs2=i.getVerticesData(e.VertexBuffer.UV2Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV3Kind)&&(n.uvs3=i.getVerticesData(e.VertexBuffer.UV3Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV4Kind)&&(n.uvs4=i.getVerticesData(e.VertexBuffer.UV4Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV5Kind)&&(n.uvs5=i.getVerticesData(e.VertexBuffer.UV5Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV6Kind)&&(n.uvs6=i.getVerticesData(e.VertexBuffer.UV6Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(n.colors=i.getVerticesData(e.VertexBuffer.ColorKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&(n.matricesIndices=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)&&(n.matricesWeights=i.getVerticesData(e.VertexBuffer.MatricesWeightsKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=i.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,r)),n.indices=i.getIndices(r),n},t.CreateRibbon=function(i){var r=i.pathArray,n=i.closeArray||!1,o=i.closePath||!1,s=i.invertUV||!1,a=Math.floor(r[0].length/2),h=i.offset||a;h=h>a?a:Math.floor(h);var c,l,u,f,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=[],m=[],g=[],_=[],v=[],y=[],x=[],b=[],A=[],T=[];if(r.length<2){var E=[],M=[];for(u=0;u<r[0].length-h;u++)E.push(r[0][u]),M.push(r[0][u+h]);r=[E,M]}var P,S,C=0,R=o?1:0;c=r[0].length;var O,D;for(l=0;l<r.length;l++){for(x[l]=0,v[l]=[0],P=r[l],S=P.length,c=c<S?c:S,f=0;f<S;)p.push(P[f].x,P[f].y,P[f].z),f>0&&(O=P[f].subtract(P[f-1]).length(),D=O+x[l],v[l].push(D),x[l]=D),f++;o&&(f--,p.push(P[0].x,P[0].y,P[0].z),O=P[f].subtract(P[0]).length(),D=O+x[l],v[l].push(D),x[l]=D),A[l]=S+R,T[l]=C,C+=S+R}var I,L,w,B;for(u=0;u<c+R;u++){for(b[u]=0,y[u]=[0],l=0;l<r.length-1;l++)I=r[l],L=r[l+1],u===c?(w=I[0],B=L[0]):(w=I[u],B=L[u]),O=B.subtract(w).length(),D=O+b[u],y[u].push(D),b[u]=D;n&&(I=r[l],L=r[0],u===c&&(B=L[0]),O=B.subtract(w).length(),D=O+b[u],b[u]=D)}var F,V;for(l=0;l<r.length;l++)for(u=0;u<c+R;u++)F=v[l][u]/x[l],V=y[u][l]/b[u],s?_.push(V,F):_.push(F,V);l=0;for(var N=0,U=A[l]-1,z=A[l+1]-1,k=U<z?U:z,W=T[1]-T[0],G=n?A.length:A.length-1;N<=k&&l<G;)m.push(N,N+W,N+1),m.push(N+W+1,N+1,N+W),N+=1,N===k&&(l++,l===A.length-1?(W=T[0]-T[l],U=A[l]-1,z=A[0]-1):(W=T[l+1]-T[l],U=A[l]-1,z=A[l+1]-1),N=T[l],k=U<z?U+N:z+N);if(t.ComputeNormals(p,m,g),o){var Y=0,K=0;for(l=0;l<r.length;l++)Y=3*T[l],K=l+1<r.length?3*(T[l+1]-1):g.length-3,g[Y]=.5*(g[Y]+g[K]),g[Y+1]=.5*(g[Y+1]+g[K+1]),g[Y+2]=.5*(g[Y+2]+g[K+2]),g[K]=g[Y],g[K+1]=g[Y+1],g[K+2]=g[Y+2]}t._ComputeSides(d,p,m,g,_);var X=new t;return X.indices=m,X.positions=p,X.normals=g,X.uvs=_,o&&(X._idx=T),X},t.CreateBox=function(i){for(var r=[new e.Vector3(0,0,1),new e.Vector3(0,0,(-1)),new e.Vector3(1,0,0),new e.Vector3((-1),0,0),new e.Vector3(0,1,0),new e.Vector3(0,(-1),0)],n=[],o=[],s=[],a=[],h=i.width||i.size||1,c=i.height||i.size||1,l=i.depth||i.size||1,u=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,f=i.faceUV||new Array(6),d=i.faceColors,p=[],m=0;m<6;m++)void 0===f[m]&&(f[m]=new e.Vector4(0,0,1,1)),d&&void 0===d[m]&&(d[m]=new e.Color4(1,1,1,1));for(var g=new e.Vector3(h/2,c/2,l/2),_=0;_<r.length;_++){var v=r[_],y=new e.Vector3(v.y,v.z,v.x),x=e.Vector3.Cross(v,y),b=o.length/3;n.push(b),n.push(b+1),n.push(b+2),n.push(b),n.push(b+2),n.push(b+3);var A=v.subtract(y).subtract(x).multiply(g);o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(f[_].z,f[_].w),d&&p.push(d[_].r,d[_].g,d[_].b,d[_].a),A=v.subtract(y).add(x).multiply(g),o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(f[_].x,f[_].w),d&&p.push(d[_].r,d[_].g,d[_].b,d[_].a),A=v.add(y).add(x).multiply(g),o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(f[_].x,f[_].y),d&&p.push(d[_].r,d[_].g,d[_].b,d[_].a),A=v.add(y).subtract(x).multiply(g),o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(f[_].z,f[_].y),d&&p.push(d[_].r,d[_].g,d[_].b,d[_].a)}t._ComputeSides(u,o,n,s,a);var T=new t;if(T.indices=n,T.positions=o,T.normals=s,T.uvs=a,d){var E=u===e.Mesh.DOUBLESIDE?p.concat(p):p;T.colors=E}return T},t.CreateSphere=function(i){for(var r=i.segments||32,n=i.diameterX||i.diameter||1,o=i.diameterY||i.diameter||1,s=i.diameterZ||i.diameter||1,a=i.arc<=0||i.arc>1?1:i.arc||1,h=i.slice<=0?1:i.slice||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,l=new e.Vector3(n/2,o/2,s/2),u=2+r,f=2*u,d=[],p=[],m=[],g=[],_=0;_<=u;_++){for(var v=_/u,y=v*Math.PI*h,x=0;x<=f;x++){var b=x/f,A=b*Math.PI*2*a,T=e.Matrix.RotationZ(-y),E=e.Matrix.RotationY(A),M=e.Vector3.TransformCoordinates(e.Vector3.Up(),T),P=e.Vector3.TransformCoordinates(M,E),S=P.multiply(l),C=P.divide(l).normalize();p.push(S.x,S.y,S.z),m.push(C.x,C.y,C.z),g.push(b,v)}if(_>0)for(var R=p.length/3,O=R-2*(f+1);O+f+2<R;O++)d.push(O),d.push(O+1),d.push(O+f+1),d.push(O+f+1),d.push(O+1),d.push(O+f+2)}t._ComputeSides(c,p,d,m,g);var D=new t;return D.indices=d,D.positions=p,D.normals=m,D.uvs=g,D},t.CreateCylinder=function(i){var r,n=i.height||2,o=0===i.diameterTop?0:i.diameterTop||i.diameter||1,s=0===i.diameterBottom?0:i.diameterBottom||i.diameter||1,a=i.tessellation||24,h=i.subdivisions||1,c=i.hasRings,l=i.enclose,u=i.arc<=0||i.arc>1?1:i.arc||1,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,d=i.faceUV||new Array(3),p=i.faceColors,m=1!==u&&l?2:0,g=c?h:1,_=2+(1+m)*g;for(r=0;r<_;r++)p&&void 0===p[r]&&(p[r]=new e.Color4(1,1,1,1));for(r=0;r<_;r++)d&&void 0===d[r]&&(d[r]=new e.Vector4(0,0,1,1));var v,y,x,b,A,T,E=[],M=[],P=[],S=[],C=[],R=2*Math.PI*u/a,O=(s-o)/2/n,D=e.Vector3.Zero(),I=e.Vector3.Zero(),L=e.Vector3.Zero(),w=e.Vector3.Zero(),B=e.Vector3.Zero(),F=e.Axis.Y,V=1,N=1,U=0,z=0;for(b=0;b<=h;b++)for(y=b/h,x=(y*(o-s)+s)/2,V=c&&0!==b&&b!==h?2:1,T=0;T<V;T++){for(c&&(N+=T),l&&(N+=2*T),A=0;A<=a;A++)v=A*R,D.x=Math.cos(-v)*x,D.y=-n/2+y*n,D.z=Math.sin(-v)*x,0===o&&b===h?(I.x=P[P.length-3*(a+1)],I.y=P[P.length-3*(a+1)+1],I.z=P[P.length-3*(a+1)+2]):(I.x=D.x,I.z=D.z,I.y=Math.sqrt(I.x*I.x+I.z*I.z)*O,I.normalize()),0===A&&(L.copyFrom(D),w.copyFrom(I)),M.push(D.x,D.y,D.z),P.push(I.x,I.y,I.z),z=c?U!==N?d[N].y:d[N].w:d[N].y+(d[N].w-d[N].y)*y,S.push(d[N].x+(d[N].z-d[N].x)*A/a,z),p&&C.push(p[N].r,p[N].g,p[N].b,p[N].a);1!==u&&l&&(M.push(D.x,D.y,D.z),M.push(0,D.y,0),M.push(0,D.y,0),M.push(L.x,L.y,L.z),e.Vector3.CrossToRef(F,I,B),B.normalize(),P.push(B.x,B.y,B.z,B.x,B.y,B.z),e.Vector3.CrossToRef(w,F,B),B.normalize(),P.push(B.x,B.y,B.z,B.x,B.y,B.z),z=c?U!==N?d[N+1].y:d[N+1].w:d[N+1].y+(d[N+1].w-d[N+1].y)*y,S.push(d[N+1].x,z),S.push(d[N+1].z,z),z=c?U!==N?d[N+2].y:d[N+2].w:d[N+2].y+(d[N+2].w-d[N+2].y)*y,S.push(d[N+2].x,z),S.push(d[N+2].z,z),p&&(C.push(p[N+1].r,p[N+1].g,p[N+1].b,p[N+1].a),C.push(p[N+1].r,p[N+1].g,p[N+1].b,p[N+1].a),C.push(p[N+2].r,p[N+2].g,p[N+2].b,p[N+2].a),C.push(p[N+2].r,p[N+2].g,p[N+2].b,p[N+2].a))),U!==N&&(U=N)}var N,k=1!==u&&l?a+4:a;for(b=0,N=0;N<h;N++){for(A=0;A<a;A++){var W=b*(k+1)+A,G=(b+1)*(k+1)+A,Y=b*(k+1)+(A+1),K=(b+1)*(k+1)+(A+1);E.push(W,G,Y),E.push(K,Y,G)}1!==u&&l&&(E.push(W+2,G+2,Y+2),E.push(K+2,Y+2,G+2),E.push(W+4,G+4,Y+4),E.push(K+4,Y+4,G+4)),b=c?b+2:b+1}var X=function(t){var i=t?o/2:s/2;if(0!==i){var r,h,c,l,f=t?d[_-1]:d[0];p&&(l=t?p[_-1]:p[0]);var m=M.length/3,g=t?n/2:-n/2,v=new e.Vector3(0,g,0);M.push(v.x,v.y,v.z),P.push(0,t?1:-1,0),S.push(f.x+.5*(f.z-f.x),f.y+.5*(f.w-f.y)),p&&C.push(l.r,l.g,l.b,l.a);var y=new e.Vector2(.5,.5);for(c=0;c<=a;c++){r=2*Math.PI*c*u/a;var x=Math.cos(-r),b=Math.sin(-r);h=new e.Vector3(x*i,g,b*i);var A=new e.Vector2(x*y.x+.5,b*y.y+.5);M.push(h.x,h.y,h.z),P.push(0,t?1:-1,0),S.push(f.x+(f.z-f.x)*A.x,f.y+(f.w-f.y)*A.y),p&&C.push(l.r,l.g,l.b,l.a)}for(c=0;c<a;c++)t?(E.push(m),E.push(m+(c+2)),E.push(m+(c+1))):(E.push(m),E.push(m+(c+1)),E.push(m+(c+2)))}};X(!1),X(!0),t._ComputeSides(f,M,E,P,S);var H=new t;return H.indices=E,H.positions=M,H.normals=P,H.uvs=S,p&&(H.colors=C),H},t.CreateTorus=function(i){for(var r=[],n=[],o=[],s=[],a=i.diameter||1,h=i.thickness||.5,c=i.tessellation||16,l=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,u=c+1,f=0;f<=c;f++)for(var d=f/c,p=f*Math.PI*2/c-Math.PI/2,m=e.Matrix.Translation(a/2,0,0).multiply(e.Matrix.RotationY(p)),g=0;g<=c;g++){var _=1-g/c,v=g*Math.PI*2/c+Math.PI,y=Math.cos(v),x=Math.sin(v),b=new e.Vector3(y,x,0),A=b.scale(h/2),T=new e.Vector2(d,_);A=e.Vector3.TransformCoordinates(A,m),b=e.Vector3.TransformNormal(b,m),n.push(A.x,A.y,A.z),o.push(b.x,b.y,b.z),s.push(T.x,T.y);var E=(f+1)%u,M=(g+1)%u;r.push(f*u+g),r.push(f*u+M),r.push(E*u+g),r.push(f*u+M),r.push(E*u+M),r.push(E*u+g)}t._ComputeSides(l,n,r,o,s);var P=new t;return P.indices=r,P.positions=n,P.normals=o,P.uvs=s,P},t.CreateLineSystem=function(e){for(var i=[],r=[],n=e.lines,o=0,s=0;s<n.length;s++)for(var a=n[s],h=0;h<a.length;h++)r.push(a[h].x,a[h].y,a[h].z),h>0&&(i.push(o-1),i.push(o)),o++;var c=new t;return c.indices=i,c.positions=r,c},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,h=new Array,c=e.Vector3.Zero(),l=0,u=0,f=0,d=0,p=0,m=0,g=0;for(g=0;g<s.length-1;g++)s[g+1].subtractToRef(s[g],c),l+=c.length();for(f=l/o,d=r*f/(r+n),g=0;g<s.length-1;g++){s[g+1].subtractToRef(s[g],c),u=Math.floor(c.length()/f),c.normalize();for(var _=0;_<u;_++)p=f*_,a.push(s[g].x+p*c.x,s[g].y+p*c.y,s[g].z+p*c.z),a.push(s[g].x+(p+d)*c.x,s[g].y+(p+d)*c.y,s[g].z+(p+d)*c.z),h.push(m,m+1),m+=2}var v=new t;return v.positions=a,v.indices=h,v},t.CreateGround=function(i){var r,n,o=[],s=[],a=[],h=[],c=i.width||1,l=i.height||1,u=i.subdivisionsX||i.subdivisions||1,f=i.subdivisionsY||i.subdivisions||1;for(r=0;r<=f;r++)for(n=0;n<=u;n++){var d=new e.Vector3(n*c/u-c/2,0,(f-r)*l/f-l/2),p=new e.Vector3(0,1,0);s.push(d.x,d.y,d.z),a.push(p.x,p.y,p.z),h.push(n/u,1-r/u)}for(r=0;r<f;r++)for(n=0;n<u;n++)o.push(n+1+(r+1)*(u+1)),o.push(n+1+r*(u+1)),o.push(n+r*(u+1)),o.push(n+(r+1)*(u+1)),o.push(n+1+(r+1)*(u+1)),o.push(n+r*(u+1));var m=new t;return m.indices=o,m.positions=s,m.normals=a,m.uvs=h,m},t.CreateTiledGround=function(i){function r(t,i,r,s){var a=m.length/3,h=d.w+1;for(n=0;n<d.h;n++)for(o=0;o<d.w;o++){var c=[a+o+n*h,a+(o+1)+n*h,a+(o+1)+(n+1)*h,a+o+(n+1)*h];p.push(c[1]),p.push(c[2]),p.push(c[3]),p.push(c[0]),p.push(c[1]),p.push(c[3])}var l=e.Vector3.Zero(),u=new e.Vector3(0,1,0);for(n=0;n<=d.h;n++)for(l.z=n*(s-i)/d.h+i,o=0;o<=d.w;o++)l.x=o*(r-t)/d.w+t,l.y=0,m.push(l.x,l.y,l.z),g.push(u.x,u.y,u.z),_.push(o/d.w,n/d.h)}var n,o,s,a,h=i.xmin||-1,c=i.zmin||-1,l=i.xmax||1,u=i.zmax||1,f=i.subdivisions||{w:1,h:1},d=i.precision||{w:1,h:1},p=[],m=[],g=[],_=[];f.h=f.h<1?1:f.h,f.w=f.w<1?1:f.w,d.w=d.w<1?1:d.w,d.h=d.h<1?1:d.h;var v={w:(l-h)/f.w,h:(u-c)/f.h};for(s=0;s<f.h;s++)for(a=0;a<f.w;a++)r(h+a*v.w,c+s*v.h,h+(a+1)*v.w,c+(s+1)*v.h);var y=new t;return y.indices=p,y.positions=m,y.normals=g,y.uvs=_,y},t.CreateGroundFromHeightMap=function(i){var r,n,o=[],s=[],a=[],h=[];for(r=0;r<=i.subdivisions;r++)for(n=0;n<=i.subdivisions;n++){var c=new e.Vector3(n*i.width/i.subdivisions-i.width/2,0,(i.subdivisions-r)*i.height/i.subdivisions-i.height/2),l=(c.x+i.width/2)/i.width*(i.bufferWidth-1)|0,u=(1-(c.z+i.height/2)/i.height)*(i.bufferHeight-1)|0,f=4*(l+u*i.bufferWidth),d=i.buffer[f]/255,p=i.buffer[f+1]/255,m=i.buffer[f+2]/255,g=.3*d+.59*p+.11*m;c.y=i.minHeight+(i.maxHeight-i.minHeight)*g,s.push(c.x,c.y,c.z),a.push(0,0,0),h.push(n/i.subdivisions,1-r/i.subdivisions)}for(r=0;r<i.subdivisions;r++)for(n=0;n<i.subdivisions;n++)o.push(n+1+(r+1)*(i.subdivisions+1)),o.push(n+1+r*(i.subdivisions+1)),o.push(n+r*(i.subdivisions+1)),o.push(n+(r+1)*(i.subdivisions+1)),o.push(n+1+(r+1)*(i.subdivisions+1)),o.push(n+r*(i.subdivisions+1));t.ComputeNormals(s,o,a);var _=new t;return _.indices=o,_.positions=s,_.normals=a,_.uvs=h,_},t.CreatePlane=function(i){var r=[],n=[],o=[],s=[],a=i.width||i.size||1,h=i.height||i.size||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,l=a/2,u=h/2;n.push(-l,-u,0),o.push(0,0,-1),s.push(0,0),n.push(l,-u,0),o.push(0,0,-1),s.push(1,0),n.push(l,u,0),o.push(0,0,-1),s.push(1,1),n.push(-l,u,0),o.push(0,0,-1),s.push(0,1),r.push(0),r.push(1),r.push(2),r.push(0),r.push(2),r.push(3),t._ComputeSides(c,n,r,o,s);var f=new t;return f.indices=r,f.positions=n,f.normals=o,f.uvs=s,f},t.CreateDisc=function(i){var r=[],n=[],o=[],s=[],a=i.radius||.5,h=i.tessellation||64,c=i.arc<=0||i.arc>1?1:i.arc||1,l=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*c,f=u/h,d=0;d<u;d+=f){var p=Math.cos(d),m=Math.sin(d),g=(p+1)/2,_=(1-m)/2;r.push(a*p,a*m,0),s.push(g,_)}1===c&&(r.push(r[3],r[4],r[5]),s.push(s[2],s[3]));for(var v=r.length/3,y=1;y<v-1;y++)n.push(y+1,0,y);t.ComputeNormals(r,n,o),t._ComputeSides(l,r,n,o,s);var x=new t;return x.indices=n,x.positions=r,x.normals=o,x.uvs=s,x},t.CreateIcoSphere=function(i){var r,n=i.sideOrientation||e.Mesh.DEFAULTSIDE,o=i.radius||1,s=void 0===i.flat||i.flat,a=i.subdivisions||4,h=i.radiusX||o,c=i.radiusY||o,l=i.radiusZ||o,u=(1+Math.sqrt(5))/2,f=[-1,u,-0,1,u,0,-1,-u,0,1,-u,0,0,-1,-u,0,1,-u,0,-1,u,0,1,u,u,0,1,u,0,-1,-u,0,1,-u,0,-1],d=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],p=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],m=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],g=138/1024,_=239/1024,v=60/1024,y=26/1024,x=-40/1024,b=20/1024,A=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],T=[],E=[],M=[],P=[],S=0,C=new Array(3),R=new Array(3);for(r=0;r<3;r++)C[r]=e.Vector3.Zero(),R[r]=e.Vector2.Zero();for(var O=0;O<20;O++){for(r=0;r<3;r++){var D=d[3*O+r];C[r].copyFromFloats(f[3*p[D]],f[3*p[D]+1],f[3*p[D]+2]),C[r].normalize().scaleInPlace(o),R[r].copyFromFloats(m[2*D]*g+v+A[O]*x,m[2*D+1]*_+y+A[O]*b)}for(var I=function(t,i,r,n){var o=e.Vector3.Lerp(C[0],C[2],i/a),u=e.Vector3.Lerp(C[1],C[2],i/a),f=a===i?C[2]:e.Vector3.Lerp(o,u,t/(a-i));f.normalize();var d;if(s){var p=e.Vector3.Lerp(C[0],C[2],n/a),m=e.Vector3.Lerp(C[1],C[2],n/a);d=e.Vector3.Lerp(p,m,r/(a-n))}else d=new e.Vector3(f.x,f.y,f.z);d.x/=h,d.y/=c,d.z/=l,d.normalize();var g=e.Vector2.Lerp(R[0],R[2],i/a),_=e.Vector2.Lerp(R[1],R[2],i/a),v=a===i?R[2]:e.Vector2.Lerp(g,_,t/(a-i));E.push(f.x*h,f.y*c,f.z*l),M.push(d.x,d.y,d.z),P.push(v.x,v.y),T.push(S),S++},L=0;L<a;L++)for(var w=0;w+L<a;w++)I(w,L,w+1/3,L+1/3),I(w+1,L,w+1/3,L+1/3),I(w,L+1,w+1/3,L+1/3),w+L+1<a&&(I(w+1,L,w+2/3,L+2/3),I(w+1,L+1,w+2/3,L+2/3),I(w,L+1,w+2/3,L+2/3))}t._ComputeSides(n,E,T,M,P);var B=new t;return B.indices=T,B.positions=E,B.normals=M,B.uvs=P,B},t.CreatePolyhedron=function(i){var r=[];r[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},r[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},r[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},r[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},r[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},r[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},r[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],
face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},r[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},r[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},r[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},r[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},r[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},r[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},r[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},r[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};var n,o,s,a,h,c,l=i.type<0||i.type>=r.length?0:i.type||0,u=i.size,f=i.sizeX||u||1,d=i.sizeY||u||1,p=i.sizeZ||u||1,m=i.custom||r[l],g=m.face.length,_=i.faceUV||new Array(g),v=i.faceColors,y=void 0===i.flat||i.flat,x=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,b=[],A=[],T=[],E=[],M=[],P=0,S=0,C=[],R=0,O=0;if(y)for(O=0;O<g;O++)v&&void 0===v[O]&&(v[O]=new e.Color4(1,1,1,1)),_&&void 0===_[O]&&(_[O]=new e.Vector4(0,0,1,1));if(y)for(O=0;O<g;O++){var D=m.face[O].length;for(s=2*Math.PI/D,a=.5*Math.tan(s/2),h=.5,R=0;R<D;R++)b.push(m.vertex[m.face[O][R]][0]*f,m.vertex[m.face[O][R]][1]*d,m.vertex[m.face[O][R]][2]*p),C.push(P),P++,n=_[O].x+(_[O].z-_[O].x)*(.5+a),o=_[O].y+(_[O].w-_[O].y)*(h-.5),E.push(n,o),c=a*Math.cos(s)-h*Math.sin(s),h=a*Math.sin(s)+h*Math.cos(s),a=c,v&&M.push(v[O].r,v[O].g,v[O].b,v[O].a);for(R=0;R<D-2;R++)A.push(C[0+S],C[R+2+S],C[R+1+S]);S+=D}else{for(R=0;R<m.vertex.length;R++)b.push(m.vertex[R][0]*f,m.vertex[R][1]*d,m.vertex[R][2]*p),E.push(0,0);for(O=0;O<g;O++)for(R=0;R<m.face[O].length-2;R++)A.push(m.face[O][0],m.face[O][R+2],m.face[O][R+1])}t.ComputeNormals(b,A,T),t._ComputeSides(x,b,A,T,E);var I=new t;return I.positions=b,I.indices=A,I.normals=T,I.uvs=E,v&&y&&(I.colors=M),I},t.CreateTorusKnot=function(i){var r,n,o=[],s=[],a=[],h=[],c=i.radius||2,l=i.tube||.5,u=i.radialSegments||32,f=i.tubularSegments||32,d=i.p||2,p=i.q||3,m=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,g=function(t){var i=Math.cos(t),r=Math.sin(t),n=p/d*t,o=Math.cos(n),s=c*(2+o)*.5*i,a=c*(2+o)*r*.5,h=c*Math.sin(n)*.5;return new e.Vector3(s,a,h)};for(r=0;r<=u;r++){var _=r%u,v=_/u*2*d*Math.PI,y=g(v),x=g(v+.01),b=x.subtract(y),A=x.add(y),T=e.Vector3.Cross(b,A);for(A=e.Vector3.Cross(T,b),T.normalize(),A.normalize(),n=0;n<f;n++){var E=n%f,M=E/f*2*Math.PI,P=-l*Math.cos(M),S=l*Math.sin(M);s.push(y.x+P*A.x+S*T.x),s.push(y.y+P*A.y+S*T.y),s.push(y.z+P*A.z+S*T.z),h.push(r/u),h.push(n/f)}}for(r=0;r<u;r++)for(n=0;n<f;n++){var C=(n+1)%f,R=r*f+n,O=(r+1)*f+n,D=(r+1)*f+C,I=r*f+C;o.push(I),o.push(O),o.push(R),o.push(I),o.push(D),o.push(O)}t.ComputeNormals(s,o,a),t._ComputeSides(m,s,o,a,h);var L=new t;return L.indices=o,L.positions=s,L.normals=a,L.uvs=h,L},t.ComputeNormals=function(e,t,i){var r=0,n=0,o=0,s=0,a=0,h=0,c=0,l=0,u=0,f=0,d=0,p=0,m=0,g=0;for(r=0;r<e.length;r++)i[r]=0;var _=t.length/3;for(r=0;r<_;r++)p=t[3*r],m=t[3*r+1],g=t[3*r+2],n=e[3*p]-e[3*m],o=e[3*p+1]-e[3*m+1],s=e[3*p+2]-e[3*m+2],a=e[3*g]-e[3*m],h=e[3*g+1]-e[3*m+1],c=e[3*g+2]-e[3*m+2],l=o*c-s*h,u=s*a-n*c,f=n*h-o*a,d=Math.sqrt(l*l+u*u+f*f),d=0===d?1:d,l/=d,u/=d,f/=d,i[3*p]+=l,i[3*p+1]+=u,i[3*p+2]+=f,i[3*m]+=l,i[3*m+1]+=u,i[3*m+2]+=f,i[3*g]+=l,i[3*g+1]+=u,i[3*g+2]+=f;for(r=0;r<i.length/3;r++)l=i[3*r],u=i[3*r+1],f=i[3*r+2],d=Math.sqrt(l*l+u*u+f*f),d=0===d?1:d,l/=d,u/=d,f/=d,i[3*r]=l,i[3*r+1]=u,i[3*r+2]=f},t._ComputeSides=function(t,i,r,n,o){var s,a,h=r.length,c=n.length;switch(t=t||e.Mesh.DEFAULTSIDE){case e.Mesh.FRONTSIDE:break;case e.Mesh.BACKSIDE:var l;for(s=0;s<h;s+=3)l=r[s],r[s]=r[s+2],r[s+2]=l;for(a=0;a<c;a++)n[a]=-n[a];break;case e.Mesh.DOUBLESIDE:for(var u=i.length,f=u/3,d=0;d<u;d++)i[u+d]=i[d];for(s=0;s<h;s+=3)r[s+h]=r[s+2]+f,r[s+1+h]=r[s+1]+f,r[s+2+h]=r[s]+f;for(a=0;a<c;a++)n[c+a]=-n[a];for(var p=o.length,m=0;m<p;m++)o[m+p]=o[m]}},t.ImportVertexData=function(i,r){var n=new t,o=i.positions;o&&n.set(o,e.VertexBuffer.PositionKind);var s=i.normals;s&&n.set(s,e.VertexBuffer.NormalKind);var a=i.uvs;a&&n.set(a,e.VertexBuffer.UVKind);var h=i.uv2s;h&&n.set(h,e.VertexBuffer.UV2Kind);var c=i.uv3s;c&&n.set(c,e.VertexBuffer.UV3Kind);var l=i.uv4s;l&&n.set(l,e.VertexBuffer.UV4Kind);var u=i.uv5s;u&&n.set(u,e.VertexBuffer.UV5Kind);var f=i.uv6s;f&&n.set(f,e.VertexBuffer.UV6Kind);var d=i.colors;d&&n.set(e.Color4.CheckColors4(d,o.length/3),e.VertexBuffer.ColorKind);var p=i.matricesIndices;p&&n.set(p,e.VertexBuffer.MatricesIndicesKind);var m=i.matricesWeights;m&&n.set(m,e.VertexBuffer.MatricesWeightsKind);var g=i.indices;g&&(n.indices=g),r.setAllVerticesData(n,i.updatable)},t})();e.VertexData=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){var r=i.split(" ");r.forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){i=i.trim(),""!==i&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.Internals.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i),"true"===t||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var h=0;h<a.length;++h){var c=e._SimplifyNegation(a[h].trim());if(r="true"!==c&&"false"!==c?"!"===c[0]?!i(c.substring(1)):i(c):"true"===c,!r){s="false";break}}if(r||"true"===s){r=!0;break}r="true"!==s&&"false"!==s?"!"===s[0]?!i(s.substring(1)):i(s):"true"===s}return r?"true":"false"},e._SimplifyNegation=function(e){return e=e.replace(/^[\s!]+/,(function(e){return e=e.replace(/[\s]/g,(function(){return""})),e.length%2?"!":""})),e=e.trim(),"!true"===e?e="false":"!false"===e&&(e="true"),e},e})();e.AndOrNotEvaluator=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s){this._enabled=!0,this._refCount=0,this._name=i,this._renderTexture=new e.RenderTargetTexture(i,r,t),this.setRenderList(n),this._renderTexture.onBeforeRenderObservable.add(o),this._renderTexture.onAfterRenderObservable.add(s),this._scene=t,this._renderList=n}return t.prototype._incRefCount=function(){return 0===this._refCount&&this._scene.customRenderTargets.push(this._renderTexture),++this._refCount},t.prototype._decRefCount=function(){return this._refCount--,this._refCount<=0&&this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture),1),this._refCount},t.prototype._update=function(){this.setRenderList(this._renderList)},t.prototype.setRenderList=function(e){this._renderTexture.renderList=e},t.prototype.getRenderTexture=function(){return this._renderTexture},t})();e.PostProcessRenderPass=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this._engine=e,this._name=t,this._singleInstance=r||!0,this._getPostProcess=i,this._cameras=[],this._indicesForCamera=[],this._postProcesses={},this._renderPasses={},this._renderEffectAsPasses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(!this._postProcesses[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype._update=function(){for(var e in this._renderPasses)this._renderPasses[e]._update()},t.prototype.addPass=function(e){this._renderPasses[e._name]=e,this._linkParameters()},t.prototype.removePass=function(e){delete this._renderPasses[e._name],this._linkParameters()},t.prototype.addRenderEffectAsPass=function(e){this._renderEffectAsPasses[e._name]=e,this._linkParameters()},t.prototype.getPass=function(e){for(var t in this._renderPasses)if(t===e)return this._renderPasses[e]},t.prototype.emptyPasses=function(){this._renderPasses={},this._linkParameters()},t.prototype._attachCameras=function(t){for(var i,r=e.Tools.MakeArray(t||this._cameras),n=0;n<r.length;n++){var o=r[n],s=o.name;i=this._singleInstance?0:s,this._postProcesses[i]=this._postProcesses[i]||this._getPostProcess();var a=o.attachPostProcess(this._postProcesses[i]);this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._indicesForCamera[s].push(a),this._cameras.indexOf(o)===-1&&(this._cameras[s]=o);for(var h in this._renderPasses)this._renderPasses[h]._incRefCount()}this._linkParameters()},t.prototype._detachCameras=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){var n=i[r],o=n.name;n.detachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o]);var s=this._cameras.indexOf(o);this._indicesForCamera.splice(s,1),this._cameras.splice(s,1);for(var a in this._renderPasses)this._renderPasses[a]._decRefCount()}},t.prototype._enable=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){for(var n=i[r],o=n.name,s=0;s<this._indicesForCamera[o].length;s++)void 0===n._postProcesses[this._indicesForCamera[o][s]]&&t[r].attachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o][s]);for(var a in this._renderPasses)this._renderPasses[a]._incRefCount()}},t.prototype._disable=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){var n=i[r],o=n.Name;n.detachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o]);for(var s in this._renderPasses)this._renderPasses[s]._decRefCount()}},t.prototype.getPostProcess=function(e){return this._singleInstance?this._postProcesses[0]:this._postProcesses[e.name]},t.prototype._linkParameters=function(){var e=this;for(var t in this._postProcesses)this.applyParameters&&this.applyParameters(this._postProcesses[t]),this._postProcesses[t].onBeforeRenderObservable.add((function(t){e._linkTextures(t)}))},t.prototype._linkTextures=function(e){for(var t in this._renderPasses)e.setTexture(t,this._renderPasses[t].getRenderTexture());for(var i in this._renderEffectAsPasses)e.setTextureFromPostProcess(i+"Sampler",this._renderEffectAsPasses[i].getPostProcess())},t})();e.PostProcessRenderEffect=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass={},this._cameras=[]}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._renderEffects)if(!this._renderEffects[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype.addEffect=function(e){this._renderEffects[e._name]=e},t.prototype._enableEffect=function(t,i){var r=this._renderEffects[t];r&&r._enable(e.Tools.MakeArray(i||this._cameras))},t.prototype._disableEffect=function(t,i){var r=this._renderEffects[t];r&&r._disable(e.Tools.MakeArray(i||this._cameras))},t.prototype._attachCameras=function(t,i){var r,n=e.Tools.MakeArray(t||this._cameras),o=[];for(r=0;r<n.length;r++){var s=n[r],a=s.name;this._cameras.indexOf(s)===-1?this._cameras[a]=s:i&&o.push(r)}for(r=0;r<o.length;r++)t.splice(o[r],1);for(var h in this._renderEffects)this._renderEffects[h]._attachCameras(n)},t.prototype._detachCameras=function(t){var i=e.Tools.MakeArray(t||this._cameras);for(var r in this._renderEffects)this._renderEffects[r]._detachCameras(i);for(var n=0;n<i.length;n++)this._cameras.splice(this._cameras.indexOf(i[n]),1)},t.prototype._enableDisplayOnlyPass=function(i,r){var n,o=this,s=e.Tools.MakeArray(r||this._cameras),a=null;for(n in this._renderEffects)if(a=this._renderEffects[n].getPass(i),null!=a)break;if(null!==a){for(n in this._renderEffects)this._renderEffects[n]._disable(s);a._name=t.PASS_SAMPLER_NAME;for(var h=0;h<s.length;h++){var c=s[h],l=c.name;this._renderEffectsForIsolatedPass[l]=this._renderEffectsForIsolatedPass[l]||new e.PostProcessRenderEffect(this._engine,t.PASS_EFFECT_NAME,function(){return new e.DisplayPassPostProcess(t.PASS_EFFECT_NAME,1,null,null,o._engine,(!0))}),this._renderEffectsForIsolatedPass[l].emptyPasses(),this._renderEffectsForIsolatedPass[l].addPass(a),this._renderEffectsForIsolatedPass[l]._attachCameras(c)}}},t.prototype._disableDisplayOnlyPass=function(i){for(var r=this,n=e.Tools.MakeArray(i||this._cameras),o=0;o<n.length;o++){var s=n[o],a=s.name;this._renderEffectsForIsolatedPass[a]=this._renderEffectsForIsolatedPass[a]||new e.PostProcessRenderEffect(this._engine,t.PASS_EFFECT_NAME,function(){return new e.DisplayPassPostProcess(t.PASS_EFFECT_NAME,1,null,null,r._engine,(!0))}),this._renderEffectsForIsolatedPass[a]._disable(s)}for(var h in this._renderEffects)this._renderEffects[h]._enable(n)},t.prototype._update=function(){for(var e in this._renderEffects)this._renderEffects[e]._update();for(var t=0;t<this._cameras.length;t++){var i=this._cameras[t].name;this._renderEffectsForIsolatedPass[i]&&this._renderEffectsForIsolatedPass[i]._update()}},t.prototype.dispose=function(){},t.PASS_EFFECT_NAME="passEffect",t.PASS_SAMPLER_NAME="passSampler",t})();e.PostProcessRenderPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.enableDisplayOnlyPassInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableDisplayOnlyPass(t,i)},e.prototype.disableDisplayOnlyPassInPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._disableDisplayOnlyPass(t)},e.prototype.update=function(){for(var e in this._renderPipelines){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e})();e.PostProcessRenderPipelineManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.frontColor=new e.Color3(1,1,1),this.backColor=new e.Color3(.1,.1,.1),this.showBackLines=!0,this.renderList=new e.SmartArray(32),this._vertexBuffers={},this._scene=t}return t.prototype._prepareRessources=function(){if(!this._colorShader){this._colorShader=new e.ShaderMaterial("colorShader",this._scene,"color",{attributes:[e.VertexBuffer.PositionKind],uniforms:["worldViewProjection","color"]});var t=this._scene.getEngine(),i=e.VertexData.CreateBox(1);this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(t,i.positions,e.VertexBuffer.PositionKind,(!1)),this._indexBuffer=t.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}},t.prototype.reset=function(){this.renderList.reset()},t.prototype.render=function(){if(0!==this.renderList.length&&(this._prepareRessources(),this._colorShader.isReady())){var t=this._scene.getEngine();t.setDepthWrite(!1),this._colorShader._preBind();for(var i=0;i<this.renderList.length;i++){var r=this.renderList.data[i],n=r.minimum,o=r.maximum,s=o.subtract(n),a=n.add(s.scale(.5)),h=e.Matrix.Scaling(s.x,s.y,s.z).multiply(e.Matrix.Translation(a.x,a.y,a.z)).multiply(r.getWorldMatrix());t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),this.showBackLines&&(t.setDepthFunctionToGreaterOrEqual(),this._scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.backColor.toColor4()),this._colorShader.bind(h),t.draw(!1,0,24)),t.setDepthFunctionToLess(),this._scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.frontColor.toColor4()),this._colorShader.bind(h),t.draw(!1,0,24)}this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0)}},t.prototype.dispose=function(){if(this._colorShader){this._colorShader.dispose();var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._scene.getEngine()._releaseBuffer(this._indexBuffer)}},t})();e.BoundingBoxRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual),t.call(this,e),this.propertyPath=n,this.value=o,this.operator=s,this._target=r,this._effectiveTarget=this._getEffectiveTarget(r,this.propertyPath),this._property=this._getProperty(this.propertyPath)}return __extends(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]<this.value;case i.IsEqual:case i.IsDifferent:var e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===i.IsEqual?e:!e}return!1},i.prototype.serialize=function(){return this._serialize({name:"ValueCondition",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)},{name:"operator",value:i.GetOperatorName(this.operator)}]})},i.GetOperatorName=function(e){switch(e){case i._IsEqual:return"IsEqual";case i._IsDifferent:return"IsDifferent";case i._IsGreater:return"IsGreater";case i._IsLesser:return"IsLesser";default:return""}},i._IsEqual=0,i._IsDifferent=1,i._IsGreater=2,i._IsLesser=3,i})(t);e.ValueCondition=i;var r=(function(e){function t(t,i){e.call(this,t),this.predicate=i}return __extends(t,e),t.prototype.isValid=function(){return this.predicate()},t})(t);e.PredicateCondition=r;var n=(function(t){function i(e,i,r){t.call(this,e),this.value=r,this._target=i}return __extends(i,t),i.prototype.isValid=function(){return this._target.state===this.value},i.prototype.serialize=function(){return this._serialize({name:"StateCondition",properties:[e.Action._GetTargetProperty(this._target),{name:"value",value:this.value}]})},i})(t);e.StateCondition=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this.triggerOptions=e,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):this.trigger=e,this._nextActiveAction=this,this._condition=t}return t.prototype._prepare=function(){},t.prototype.getTriggerParameter=function(){return this._triggerParameter},t.prototype._executeCurrent=function(e){if(this._nextActiveAction._condition){var t=this._nextActiveAction._condition,i=this._actionManager.getScene().getRenderId();if(t._evaluationId===i){if(!t._currentResult)return}else{if(t._evaluationId=i,!t.isValid())return void(t._currentResult=!1);t._currentResult=!0}}this._nextActiveAction.execute(e),this.skipToNextActiveAction()},t.prototype.execute=function(e){},t.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},t.prototype.then=function(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e},t.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},t.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},t.prototype.serialize=function(e){},t.prototype._serialize=function(e,t){var i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){var r=this._condition.serialize();return r.children.push(i),t&&t.children.push(r),r}return t&&t.children.push(i),i},t._SerializeValueAsString=function(t){return"number"==typeof t?t.toString():"boolean"==typeof t?t?"true":"false":t instanceof e.Vector2?t.x+", "+t.y:t instanceof e.Vector3?t.x+", "+t.y+", "+t.z:t instanceof e.Color3?t.r+", "+t.g+", "+t.b:t instanceof e.Color4?t.r+", "+t.g+", "+t.b+", "+t.a:t},t._GetTargetProperty=function(t){return{name:"target",targetType:t instanceof e.Mesh?"MeshProperties":t instanceof e.Light?"LightProperties":t instanceof e.Camera?"CameraProperties":"SceneProperties",value:t instanceof e.Scene?"Scene":t.name}},t})();e.Action=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i,r,n,o){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=n,this.additionalData=o}return e.CreateNew=function(t,i,r){var n=t.getScene();return new e(t,n.pointerX,n.pointerY,n.meshUnderPointer,i,r)},e.CreateNewFromSprite=function(t,i,r,n){return new e(t,i.pointerX,i.pointerY,i.meshUnderPointer,r,n)},e.CreateNewFromScene=function(t,i){return new e(null,t.pointerX,t.pointerY,t.meshUnderPointer,i)},e.CreateNewFromPrimitive=function(t,i,r,n){return new e(t,i.x,i.y,null,r,n)},e})();e.ActionEvent=t;var i=(function(){function t(e){this.actions=new Array,this.hoverCursor="",this._scene=e,e._actionManagers.push(this)}return Object.defineProperty(t,"NothingTrigger",{get:function(){return t._NothingTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickTrigger",{get:function(){return t._OnPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnLeftPickTrigger",{get:function(){return t._OnLeftPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnRightPickTrigger",{get:function(){return t._OnRightPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnCenterPickTrigger",{get:function(){return t._OnCenterPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickDownTrigger",{get:function(){return t._OnPickDownTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickUpTrigger",{get:function(){return t._OnPickUpTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickOutTrigger",{get:function(){return t._OnPickOutTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnLongPressTrigger",{get:function(){return t._OnLongPressTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPointerOverTrigger",{get:function(){return t._OnPointerOverTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPointerOutTrigger",{get:function(){return t._OnPointerOutTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnEveryFrameTrigger",{get:function(){return t._OnEveryFrameTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnIntersectionEnterTrigger",{get:function(){return t._OnIntersectionEnterTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnIntersectionExitTrigger",{get:function(){return t._OnIntersectionExitTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnKeyDownTrigger",{get:function(){return t._OnKeyDownTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnKeyUpTrigger",{get:function(){return t._OnKeyUpTrigger},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var e=this._scene._actionManagers.indexOf(this);e>-1&&this._scene._actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(i.trigger===e)return!0}return!1},Object.defineProperty(t.prototype,"hasPointerTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),i._actionManager=this,i._prepare(),i)},t.prototype.processTrigger=function(e,i){for(var r=0;r<this.actions.length;r++){var n=this.actions[r];if(n.trigger===e){if(e===t.OnKeyUpTrigger||e===t.OnKeyDownTrigger){var o=n.getTriggerParameter();if(o){var s=i.sourceEvent.charCode?i.sourceEvent.charCode:i.sourceEvent.keyCode,a=String.fromCharCode(s).toLowerCase();if(a!==o.toLowerCase())continue}}n._executeCurrent(i)}}},t.prototype._getEffectiveTarget=function(e,t){for(var i=t.split("."),r=0;r<i.length-1;r++)e=e[i[r]];return e},t.prototype._getProperty=function(e){var t=e.split(".");return t[t.length-1]},t.prototype.serialize=function(i){for(var r={children:[],name:i,type:3,properties:[]},n=0;n<this.actions.length;n++){var o={type:0,children:[],name:t.GetTriggerName(this.actions[n].trigger),properties:[]},s=this.actions[n].triggerOptions;if(s&&"number"!=typeof s)if(s.parameter instanceof e.Node)o.properties.push(e.Action._GetTargetProperty(s.parameter));else{var a={};e.Tools.DeepCopy(s.parameter,a,["mesh"]),s.parameter.mesh&&(a._meshId=s.parameter.mesh.id),o.properties.push({name:"parameter",targetType:null,value:a})}this.actions[n].serialize(o),r.children.push(o)}return r},t.Parse=function(i,r,n){var o=new e.ActionManager(n);null===r?n.actionManager=o:r.actionManager=o;for(var s=function(t,i){var r=Object.create(e[t].prototype);return r.constructor.apply(r,i),r},a=function(t,i,r,n){if(null===n){var o=parseFloat(i);return"true"===i||"false"===i?"true"===i:isNaN(o)?i:o}for(var s=n.split("."),a=i.split(","),h=0;h<s.length;h++)r=r[s[h]];if("boolean"==typeof r)return"true"===a[0];if("string"==typeof r)return a[0];for(var c=new Array,h=0;h<a.length;h++)c.push(parseFloat(a[h]));return r instanceof e.Vector3?e.Vector3.FromArray(c):r instanceof e.Vector4?e.Vector4.FromArray(c):r instanceof e.Color3?e.Color3.FromArray(c):r instanceof e.Color4?e.Color4.FromArray(c):parseFloat(a[0])},h=function(i,r,c,l,u){if(void 0===u&&(u=null),!i.detached){var f=new Array,d=null,p=null,m=i.combine&&i.combine.length>0;if(2===i.type?f.push(o):f.push(r),m){for(var g=new Array,_=0;_<i.combine.length;_++)h(i.combine[_],t.NothingTrigger,c,l,g);f.push(g)}else for(var v=0;v<i.properties.length;v++){var y=i.properties[v].value,x=i.properties[v].name,b=i.properties[v].targetType;"target"===x?y=d=null!==b&&"SceneProperties"===b?n:n.getNodeByName(y):"parent"===x?y=n.getNodeByName(y):"sound"===x?y=n.getSoundByName(y):"propertyPath"!==x?y=2===i.type&&"operator"===x?e.ValueCondition[y]:a(x,y,d,"value"===x?p:null):p=y,f.push(y)}if(null===u?f.push(c):f.push(null),"InterpolateValueAction"===i.name){var A=f[f.length-2];f[f.length-1]=A,f[f.length-2]=c}var T=s(i.name,f);if(T instanceof e.Condition&&null!==c){var E=new e.DoNothingAction(r,c);l?l.then(E):o.registerAction(E),l=E}null===u?T instanceof e.Condition?(c=T,T=l):(c=null,l?l.then(T):o.registerAction(T)):u.push(T);for(var v=0;v<i.children.length;v++)h(i.children[v],r,c,T,null)}},c=0;c<i.children.length;c++){var l,u=i.children[c];if(u.properties.length>0){var f=u.properties[0].value,d=null===u.properties[0].targetType?f:n.getMeshByName(f);d._meshId&&(d.mesh=n.getMeshByID(d._meshId)),l={trigger:e.ActionManager[u.name],parameter:d}}else l=e.ActionManager[u.name];for(var p=0;p<u.children.length;p++)u.detached||h(u.children[p],l,null,null);
}},t.GetTriggerName=function(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnPickUpTrigger";case 7:return"OnLongPressTrigger";case 8:return"OnPointerOverTrigger";case 9:return"OnPointerOutTrigger";case 10:return"OnEveryFrameTrigger";case 11:return"OnIntersectionEnterTrigger";case 12:return"OnIntersectionExitTrigger";case 13:return"OnKeyDownTrigger";case 14:return"OnKeyUpTrigger";case 15:return"OnPickOutTrigger";default:return""}},t._NothingTrigger=0,t._OnPickTrigger=1,t._OnLeftPickTrigger=2,t._OnRightPickTrigger=3,t._OnCenterPickTrigger=4,t._OnPickDownTrigger=5,t._OnPickUpTrigger=6,t._OnLongPressTrigger=7,t._OnPointerOverTrigger=8,t._OnPointerOutTrigger=9,t._OnEveryFrameTrigger=10,t._OnIntersectionEnterTrigger=11,t._OnIntersectionExitTrigger=12,t._OnKeyDownTrigger=13,t._OnKeyUpTrigger=14,t._OnPickOutTrigger=15,t.DragMovementThreshold=10,t.LongPressDelay=500,t})();e.ActionManager=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s,a,h){void 0===o&&(o=1e3),t.call(this,e,s),this.propertyPath=r,this.value=n,this.duration=o,this.stopOtherAnimations=a,this.onInterpolationDone=h,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){var t,i=this._actionManager.getScene(),r=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)t=e.Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof e.Color3)t=e.Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof e.Vector3)t=e.Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof e.Matrix)t=e.Animation.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof e.Quaternion))return void e.Tools.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");t=e.Animation.ANIMATIONTYPE_QUATERNION}var n=new e.Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),t,e.Animation.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(r),this.stopOtherAnimations&&i.stopAnimation(this._effectiveTarget),i.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,this.onInterpolationDone)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"InterpolateValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)},{name:"duration",value:e.Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:e.Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},i)},i})(e.Action);e.InterpolateValueAction=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n){t.call(this,e,n),this.propertyPath=r,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SwitchBooleanAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},i)},i})(e.Action);e.SwitchBooleanAction=t;var i=(function(t){function i(e,i,r,n){t.call(this,e,n),this.value=r,this._target=i}return __extends(i,t),i.prototype.execute=function(){this._target.state=this.value},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetStateAction",properties:[e.Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},i)},i})(e.Action);e.SetStateAction=i;var r=(function(t){function i(e,i,r,n,o){t.call(this,e,o),this.propertyPath=r,this.value=n,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)}]},i)},i})(e.Action);e.SetValueAction=r;var n=(function(t){function i(e,i,r,n,o){t.call(this,e,o),this.propertyPath=r,this.value=n,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&e.Tools.Warn("Warning: IncrementValueAction can only be used with number values")},i.prototype.execute=function(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"IncrementValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)}]},i)},i})(e.Action);e.IncrementValueAction=n;var o=(function(t){function i(e,i,r,n,o,s){t.call(this,e,s),this.from=r,this.to=n,this.loop=o,this._target=i}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"PlayAnimationAction",properties:[e.Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:e.Action._SerializeValueAsString(this.loop)||!1}]},i)},i})(e.Action);e.PlayAnimationAction=o;var s=(function(t){function i(e,i,r){t.call(this,e,r),this._target=i}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.stopAnimation(this._target)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"StopAnimationAction",properties:[e.Action._GetTargetProperty(this._target)]},i)},i})(e.Action);e.StopAnimationAction=s;var a=(function(t){function i(i,r){void 0===i&&(i=e.ActionManager.NothingTrigger),t.call(this,i,r)}return __extends(i,t),i.prototype.execute=function(){},i.prototype.serialize=function(e){return t.prototype._serialize.call(this,{name:"DoNothingAction",properties:[]},e)},i})(e.Action);e.DoNothingAction=a;var h=(function(e){function t(t,i,r){e.call(this,t,r),this.children=i}return __extends(t,e),t.prototype._prepare=function(){for(var e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()},t.prototype.execute=function(e){for(var t=0;t<this.children.length;t++)this.children[t].execute(e)},t.prototype.serialize=function(t){for(var i=e.prototype._serialize.call(this,{name:"CombineAction",properties:[],combine:[]},t),r=0;r<this.children.length;r++)i.combine.push(this.children[r].serialize(null));return i},t})(e.Action);e.CombineAction=h;var c=(function(e){function t(t,i,r){e.call(this,t,r),this.func=i}return __extends(t,e),t.prototype.execute=function(e){this.func(e)},t})(e.Action);e.ExecuteCodeAction=c;var l=(function(t){function i(e,i,r,n){t.call(this,e,n),this._target=i,this._parent=r}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){if(this._target.parent!==this._parent){var t=this._parent.getWorldMatrix().clone();t.invert(),this._target.position=e.Vector3.TransformCoordinates(this._target.position,t),this._target.parent=this._parent}},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetParentAction",properties:[e.Action._GetTargetProperty(this._target),e.Action._GetTargetProperty(this._parent)]},i)},i})(e.Action);e.SetParentAction=l;var u=(function(e){function t(t,i,r){e.call(this,t,r),this._sound=i}return __extends(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.play()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t})(e.Action);e.PlaySoundAction=u;var f=(function(e){function t(t,i,r){e.call(this,t,r),this._sound=i}return __extends(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.stop()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t})(e.Action);e.StopSoundAction=f})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this.id=t,this._engine=i.getEngine(),this._meshes=[],this._scene=i,this._vertexBuffers={},this._indices=[],r?this.setAllVerticesData(r,n):(this._totalVertices=0,this._indices=[]),o&&(o instanceof e.LinesMesh&&(this.boundingBias=new e.Vector2(0,o.intersectionThreshold),this.updateExtend()),this.applyToMesh(o),o.computeWorldMatrix(!0))}return Object.defineProperty(t.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(e){this._boundingBias&&this._boundingBias.equals(e)||(this._boundingBias=e.clone(),this.updateBoundingInfo(!0,null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extend",{get:function(){return this._extend},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._engine},t.prototype.isReady=function(){return this.delayLoadState===e.Engine.DELAYLOADSTATE_LOADED||this.delayLoadState===e.Engine.DELAYLOADSTATE_NONE},Object.defineProperty(t.prototype,"doNotSerialize",{get:function(){for(var e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype.setAllVerticesData=function(e,t){e.applyToGeometry(this,t),this.notifyUpdate()},t.prototype.setVerticesData=function(t,i,r,n){var o=new e.VertexBuffer(this._engine,i,t,r,0===this._meshes.length,n);this.setVerticesBuffer(o)},t.prototype.setVerticesBuffer=function(t){var i=t.getKind();if(this._vertexBuffers[i]&&this._vertexBuffers[i].dispose(),this._vertexBuffers[i]=t,i===e.VertexBuffer.PositionKind){var r=t.getData(),n=t.getStrideSize();this._totalVertices=r.length/n,this.updateExtend(r,n);for(var o=this._meshes,s=o.length,a=0;a<s;a++){var h=o[a];h._resetPointsArrayCache(),h._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),h._createGlobalSubMesh(),h.computeWorldMatrix(!0)}}this.notifyUpdate(i)},t.prototype.updateVerticesDataDirectly=function(e,t,i){var r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i),this.notifyUpdate(e))},t.prototype.updateVerticesData=function(t,i,r){var n=this.getVertexBuffer(t);if(n){if(n.update(i),t===e.VertexBuffer.PositionKind){var o=n.getStrideSize();this._totalVertices=i.length/o,this.updateBoundingInfo(r,i)}this.notifyUpdate(t)}},t.prototype.updateBoundingInfo=function(t,i){t&&this.updateExtend(i);for(var r=this._meshes,n=r.length,o=0;o<n;o++){var s=r[o];if(s._resetPointsArrayCache(),t){s._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum);for(var a=0;a<s.subMeshes.length;a++){var h=s.subMeshes[a];h.refreshBoundingInfo()}}}},t.prototype.getTotalVertices=function(){return this.isReady()?this._totalVertices:0},t.prototype.getVerticesData=function(e,t){var i=this.getVertexBuffer(e);if(!i)return null;var r=i.getData();if(t&&1!==this._meshes.length){for(var n=r.length,o=[],s=0;s<n;s++)o.push(r[s]);return o}return r},t.prototype.getVertexBuffer=function(e){return this.isReady()?this._vertexBuffers[e]:null},t.prototype.getVertexBuffers=function(){return this.isReady()?this._vertexBuffers:null},t.prototype.isVerticesDataPresent=function(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&this._delayInfo.indexOf(e)!==-1},t.prototype.getVerticesDataKinds=function(){var e,t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t},t.prototype.setIndices=function(e,t){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),void 0!==t&&(this._totalVertices=t);for(var i=this._meshes,r=i.length,n=0;n<r;n++)i[n]._createGlobalSubMesh();this.notifyUpdate()},t.prototype.getTotalIndices=function(){return this.isReady()?this._indices.length:0},t.prototype.getIndices=function(e){if(!this.isReady())return null;var t=this._indices;if(e&&1!==this._meshes.length){for(var i=t.length,r=[],n=0;n<i;n++)r.push(t[n]);return r}return t},t.prototype.getIndexBuffer=function(){return this.isReady()?this._indexBuffer:null},t.prototype.releaseForMesh=function(e,t){var i=this._meshes,r=i.indexOf(e);if(r!==-1){for(var n in this._vertexBuffers)this._vertexBuffers[n].dispose();this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),i.splice(r,1),e._geometry=null,0===i.length&&t&&this.dispose()}},t.prototype.applyToMesh=function(e){if(e._geometry!==this){var t=e._geometry;t&&t.releaseForMesh(e);var i=this._meshes;e._geometry=this,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):e._boundingInfo=this._boundingInfo}},t.prototype.updateExtend=function(t,i){void 0===t&&(t=null),t||(t=this._vertexBuffers[e.VertexBuffer.PositionKind].getData()),this._extend=e.Tools.ExtractMinAndMax(t,0,this._totalVertices,this.boundingBias,i)},t.prototype._applyToMesh=function(t){var i=this._meshes.length;for(var r in this._vertexBuffers)1===i&&this._vertexBuffers[r].create(),this._vertexBuffers[r].getBuffer().references=i,r===e.VertexBuffer.PositionKind&&(t._resetPointsArrayCache(),this._extend||this.updateExtend(this._vertexBuffers[r].getData()),t._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),t._createGlobalSubMesh(),t._updateBoundingInfo());1===i&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e)},t.prototype.load=function(t,i){if(this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING){if(this.isReady())return void(i&&i());this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t,i)}},t.prototype._queueLoad=function(t,i){var r=this;t._addPendingData(this),e.Tools.LoadFile(this.delayLoadingFile,(function(n){r._delayLoadingFunction(JSON.parse(n),r),r.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,r._delayInfo=[],t._removePendingData(r);for(var o=r._meshes,s=o.length,a=0;a<s;a++)r._applyToMesh(o[a]);i&&i()}),(function(){}),t.database)},t.prototype.toLeftHanded=function(){var t=this.getIndices(!1);if(null!=t&&t.length>0){for(var i=0;i<t.length;i+=3){var r=t[i+0];t[i+0]=t[i+2],t[i+2]=r}this.setIndices(t)}var n=this.getVerticesData(e.VertexBuffer.PositionKind,!1);if(null!=n&&n.length>0){for(var i=0;i<n.length;i+=3)n[i+2]=-n[i+2];this.setVerticesData(e.VertexBuffer.PositionKind,n,!1)}var o=this.getVerticesData(e.VertexBuffer.NormalKind,!1);if(null!=o&&o.length>0){for(var i=0;i<o.length;i+=3)o[i+2]=-o[i+2];this.setVerticesData(e.VertexBuffer.NormalKind,o,!1)}},t.prototype.isDisposed=function(){return this._isDisposed},t.prototype.dispose=function(){var t,i=this._meshes,r=i.length;for(t=0;t<r;t++)this.releaseForMesh(i[t]);this._meshes=[];for(var n in this._vertexBuffers)this._vertexBuffers[n].dispose();this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._isDisposed=!0},t.prototype.copy=function(i){var r=new e.VertexData;r.indices=[];for(var n=this.getIndices(),o=0;o<n.length;o++)r.indices.push(n[o]);var s,a=!1,h=!1;for(s in this._vertexBuffers){var c=this.getVerticesData(s);c instanceof Float32Array?r.set(new Float32Array(c),s):r.set(c.slice(0),s),h||(a=this.getVertexBuffer(s).isUpdatable(),h=!a)}var l=new t(i,this._scene,r,a,null);l.delayLoadState=this.delayLoadState,l.delayLoadingFile=this.delayLoadingFile,l._delayLoadingFunction=this._delayLoadingFunction;for(s in this._delayInfo)l._delayInfo=l._delayInfo||[],l._delayInfo.push(s);return l._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),l},t.prototype.serialize=function(){var t={};return t.id=this.id,e.Tags.HasTags(this)&&(t.tags=e.Tags.GetTags(this)),t},t.prototype.serializeVerticeData=function(){var t=this.serialize();return this.isVerticesDataPresent(e.VertexBuffer.PositionKind)&&(t.positions=this.getVerticesData(e.VertexBuffer.PositionKind)),this.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(t.normals=this.getVerticesData(e.VertexBuffer.NormalKind)),this.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(t.uvs=this.getVerticesData(e.VertexBuffer.UVKind)),this.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(t.uv2s=this.getVerticesData(e.VertexBuffer.UV2Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV3Kind)&&(t.uv3s=this.getVerticesData(e.VertexBuffer.UV3Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV4Kind)&&(t.uv4s=this.getVerticesData(e.VertexBuffer.UV4Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV5Kind)&&(t.uv5s=this.getVerticesData(e.VertexBuffer.UV5Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV6Kind)&&(t.uv6s=this.getVerticesData(e.VertexBuffer.UV6Kind)),this.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(t.colors=this.getVerticesData(e.VertexBuffer.ColorKind)),this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&(t.matricesIndices=this.getVerticesData(e.VertexBuffer.MatricesIndicesKind),t.matricesIndices._isExpanded=!0),this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)&&(t.matricesWeights=this.getVerticesData(e.VertexBuffer.MatricesWeightsKind)),t.indices=this.getIndices(),t},t.ExtractFromMesh=function(e,t){var i=e._geometry;return i?i.copy(t):null},t.RandomId=function(){return e.Tools.RandomId()},t.ImportGeometry=function(t,i){var r=i.getScene(),n=t.geometryId;if(n){var o=r.getGeometryByID(n);o&&o.applyToMesh(i)}else if(t instanceof ArrayBuffer){var s=i._binaryInfo;if(s.positionsAttrDesc&&s.positionsAttrDesc.count>0){var a=new Float32Array(t,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);i.setVerticesData(e.VertexBuffer.PositionKind,a,!1)}if(s.normalsAttrDesc&&s.normalsAttrDesc.count>0){var h=new Float32Array(t,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);i.setVerticesData(e.VertexBuffer.NormalKind,h,!1)}if(s.uvsAttrDesc&&s.uvsAttrDesc.count>0){var c=new Float32Array(t,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);i.setVerticesData(e.VertexBuffer.UVKind,c,!1)}if(s.uvs2AttrDesc&&s.uvs2AttrDesc.count>0){var l=new Float32Array(t,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV2Kind,l,!1)}if(s.uvs3AttrDesc&&s.uvs3AttrDesc.count>0){var u=new Float32Array(t,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV3Kind,u,!1)}if(s.uvs4AttrDesc&&s.uvs4AttrDesc.count>0){var f=new Float32Array(t,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV4Kind,f,!1)}if(s.uvs5AttrDesc&&s.uvs5AttrDesc.count>0){var d=new Float32Array(t,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV5Kind,d,!1)}if(s.uvs6AttrDesc&&s.uvs6AttrDesc.count>0){var p=new Float32Array(t,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV6Kind,p,!1)}if(s.colorsAttrDesc&&s.colorsAttrDesc.count>0){var m=new Float32Array(t,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);i.setVerticesData(e.VertexBuffer.ColorKind,m,!1,s.colorsAttrDesc.stride)}if(s.matricesIndicesAttrDesc&&s.matricesIndicesAttrDesc.count>0){var g=new Int32Array(t,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count);i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,g,!1)}if(s.matricesWeightsAttrDesc&&s.matricesWeightsAttrDesc.count>0){var _=new Float32Array(t,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);i.setVerticesData(e.VertexBuffer.MatricesWeightsKind,_,!1)}if(s.indicesAttrDesc&&s.indicesAttrDesc.count>0){var v=new Int32Array(t,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);i.setIndices(v)}if(s.subMeshesAttrDesc&&s.subMeshesAttrDesc.count>0){var y=new Int32Array(t,s.subMeshesAttrDesc.offset,5*s.subMeshesAttrDesc.count);i.subMeshes=[];for(var x=0;x<s.subMeshesAttrDesc.count;x++){var b=y[5*x+0],A=y[5*x+1],T=y[5*x+2],E=y[5*x+3],M=y[5*x+4];new e.SubMesh(b,A,T,E,M,i)}}}else if(t.positions&&t.normals&&t.indices){if(i.setVerticesData(e.VertexBuffer.PositionKind,t.positions,!1),i.setVerticesData(e.VertexBuffer.NormalKind,t.normals,!1),t.uvs&&i.setVerticesData(e.VertexBuffer.UVKind,t.uvs,!1),t.uvs2&&i.setVerticesData(e.VertexBuffer.UV2Kind,t.uvs2,!1),t.uvs3&&i.setVerticesData(e.VertexBuffer.UV3Kind,t.uvs3,!1),t.uvs4&&i.setVerticesData(e.VertexBuffer.UV4Kind,t.uvs4,!1),t.uvs5&&i.setVerticesData(e.VertexBuffer.UV5Kind,t.uvs5,!1),t.uvs6&&i.setVerticesData(e.VertexBuffer.UV6Kind,t.uvs6,!1),t.colors&&i.setVerticesData(e.VertexBuffer.ColorKind,e.Color4.CheckColors4(t.colors,t.positions.length/3),!1),t.matricesIndices)if(t.matricesIndices._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,t.matricesIndices,!1);else{for(var P=[],x=0;x<t.matricesIndices.length;x++){var S=t.matricesIndices[x];P.push(255&S),P.push((65280&S)>>8),P.push((16711680&S)>>16),P.push(S>>24)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,P,!1)}if(t.matricesIndicesExtra)if(t.matricesIndicesExtra._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,t.matricesIndicesExtra,!1);else{for(var P=[],x=0;x<t.matricesIndicesExtra.length;x++){var S=t.matricesIndicesExtra[x];P.push(255&S),P.push((65280&S)>>8),P.push((16711680&S)>>16),P.push(S>>24)}i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,P,!1)}t.matricesWeights&&i.setVerticesData(e.VertexBuffer.MatricesWeightsKind,t.matricesWeights,!1),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,t.matricesWeightsExtra,!1),i.setIndices(t.indices)}if(t.subMeshes){i.subMeshes=[];for(var C=0;C<t.subMeshes.length;C++){var R=t.subMeshes[C];new e.SubMesh(R.materialIndex,R.verticesStart,R.verticesCount,R.indexStart,R.indexCount,i)}}i._shouldGenerateFlatShading&&(i.convertToFlatShadedMesh(),delete i._shouldGenerateFlatShading),i.computeWorldMatrix(!0),r._selectionOctree&&r._selectionOctree.addMesh(i)},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r);return e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var t;!(function(t){var i;!(function(i){var r=(function(e){function t(t,i,r,n){e.call(this,t,i,null,!1,n),this._canBeRegenerated=r,this._beingRegenerated=!0,this.regenerate(),this._beingRegenerated=!1}return __extends(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);i._Primitive=r;var n=(function(t){function i(i,r,n,o,s,a,h,c,l){void 0===l&&(l=e.Mesh.DEFAULTSIDE),t.call(this,i,r,h,c),this.pathArray=n,this.closeArray=o,this.closePath=s,this.offset=a,this.side=l}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),null,this.side)},i})(r);i.Ribbon=n;var o=(function(i){function r(t,r,n,o,s,a){void 0===a&&(a=e.Mesh.DEFAULTSIDE),i.call(this,t,r,o,s),this.size=n,this.side=a}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.size=this.size,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Box(i.id,r,i.size,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Box=o;var s=(function(i){function r(t,r,n,o,s,a,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE),i.call(this,t,r,s,a),this.segments=n,this.diameter=o,this.side=h}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Sphere(i.id,r,i.segments,i.diameter,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Sphere=s;var a=(function(t){function i(i,r,n,o,s,a,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE),t.call(this,i,r,s,a),this.radius=n,this.tessellation=o,this.side=h}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(r);i.Disc=a;var h=(function(i){function r(t,r,n,o,s,a,h,c,l,u){void 0===h&&(h=1),void 0===u&&(u=e.Mesh.DEFAULTSIDE),i.call(this,t,r,c,l),this.height=n,this.diameterTop=o,this.diameterBottom=s,this.tessellation=a,this.subdivisions=h,this.side=u}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Cylinder(i.id,r,i.height,i.diameterTop,i.diameterBottom,i.tessellation,i.subdivisions,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Cylinder=h;var c=(function(i){function r(t,r,n,o,s,a,h,c){void 0===c&&(c=e.Mesh.DEFAULTSIDE),i.call(this,t,r,a,h),this.diameter=n,this.thickness=o,this.tessellation=s,this.side=c}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Torus(i.id,r,i.diameter,i.thickness,i.tessellation,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Torus=c;var l=(function(i){function r(e,t,r,n,o,s,a){i.call(this,e,t,s,a),this.width=r,this.height=n,this.subdivisions=o}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Ground(i.id,r,i.width,i.height,i.subdivisions,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Ground=l;var u=(function(t){function i(e,i,r,n,o,s,a,h,c,l){t.call(this,e,i,c,l),this.xmin=r,this.zmin=n,this.xmax=o,this.zmax=s,this.subdivisions=a,this.precision=h}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(r);i.TiledGround=u;var f=(function(i){function r(t,r,n,o,s,a){void 0===a&&(a=e.Mesh.DEFAULTSIDE),i.call(this,t,r,o,s),this.size=n,this.side=a}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);
return e.size=this.size,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Plane(i.id,r,i.size,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Plane=f;var d=(function(i){function r(t,r,n,o,s,a,h,c,l,u,f){void 0===f&&(f=e.Mesh.DEFAULTSIDE),i.call(this,t,r,l,u),this.radius=n,this.tube=o,this.radialSegments=s,this.tubularSegments=a,this.p=h,this.q=c,this.side=f}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.TorusKnot(i.id,r,i.radius,i.tube,i.radialSegments,i.tubularSegments,i.p,i.q,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.TorusKnot=d})(i=t.Primitives||(t.Primitives={}))})(t=e.Geometry||(e.Geometry={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,i,r),this.generateOctree=!1,this._worldInverse=new e.Matrix}return __extends(i,t),Object.defineProperty(i.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!0,configurable:!0}),i.prototype.optimize=function(e,t){void 0===t&&(t=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e),this.createOrUpdateSubmeshesOctree(t)},i.prototype.getHeightAtCoordinates=function(e,t){if(e-=this.position.x,t-=this.position.z,e/=this.scaling.x,t/=this.scaling.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var i=this._getFacetAt(e,t),r=-(i.x*e+i.z*t+i.w)/i.y;return r*this.scaling.y+this.position.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(e,t,i){if(e-=this.position.x,t-=this.position.z,e/=this.scaling.x,t/=this.scaling.z,!(e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)){this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var r=this._getFacetAt(e,t);i.x=r.x,i.y=r.y,i.z=r.z}},i.prototype.updateCoordinateHeights=function(){this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads()},i.prototype._getFacetAt=function(e,t){var i,r=(this._subdivisionsX,this._subdivisionsY,Math.floor((e+this._maxX)*this._subdivisionsX/this._width)),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),o=this._heightQuads[n*this._subdivisionsX+r];return i=t<o.slope.x*e+o.slope.y?o.facet1:o.facet2},i.prototype._initHeightQuads=function(){var t=this._subdivisionsX,i=this._subdivisionsY;this._heightQuads=new Array;for(var r=0;r<i;r++)for(var n=0;n<t;n++){var o={slope:e.Vector2.Zero(),facet1:new e.Vector4(0,0,0,0),facet2:new e.Vector4(0,0,0,0)};this._heightQuads[r*t+n]=o}},i.prototype._computeHeightQuads=function(){for(var t=this.getVerticesData(e.VertexBuffer.PositionKind),i=e.Tmp.Vector3[3],r=e.Tmp.Vector3[2],n=e.Tmp.Vector3[1],o=e.Tmp.Vector3[0],s=e.Tmp.Vector3[4],a=e.Tmp.Vector3[5],h=e.Tmp.Vector3[6],c=e.Tmp.Vector3[7],l=e.Tmp.Vector3[8],u=0,f=0,d=0,p=0,m=0,g=0,_=0,v=this._subdivisionsX,y=this._subdivisionsY,x=0;x<y;x++)for(var b=0;b<v;b++){u=3*b,f=x*(v+1)*3,d=(x+1)*(v+1)*3,i.x=t[f+u],i.y=t[f+u+1],i.z=t[f+u+2],r.x=t[f+u+3],r.y=t[f+u+4],r.z=t[f+u+5],n.x=t[d+u],n.y=t[d+u+1],n.z=t[d+u+2],o.x=t[d+u+3],o.y=t[d+u+4],o.z=t[d+u+5],p=(o.z-i.z)/(o.x-i.x),m=i.z-p*i.x,r.subtractToRef(i,s),n.subtractToRef(i,a),o.subtractToRef(i,h),e.Vector3.CrossToRef(h,a,c),e.Vector3.CrossToRef(s,h,l),c.normalize(),l.normalize(),g=-(c.x*i.x+c.y*i.y+c.z*i.z),_=-(l.x*r.x+l.y*r.y+l.z*r.z);var A=this._heightQuads[x*v+b];A.slope.copyFromFloats(p,m),A.facet1.copyFromFloats(c.x,c.y,c.z,g),A.facet2.copyFromFloats(l.x,l.y,l.z,_)}},i})(e.Mesh);e.GroundMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===n&&(n=null),t.call(this,i,r,n,o,s),this.color=new e.Color3(1,1,1),this.alpha=1,this._positionBuffer={},o&&(this.color=o.color.clone(),this.alpha=o.alpha),this._intersectionThreshold=.1,this._colorShader=new e.ShaderMaterial("colorShader",r,"color",{attributes:[e.VertexBuffer.PositionKind],uniforms:["worldViewProjection","color"],needAlphaBlending:!0}),this._positionBuffer[e.VertexBuffer.PositionKind]=null}return __extends(i,t),Object.defineProperty(i.prototype,"intersectionThreshold",{get:function(){return this._intersectionThreshold},set:function(t){this._intersectionThreshold!==t&&(this._intersectionThreshold=t,this.geometry&&(this.geometry.boundingBias=new e.Vector2(0,t)))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._colorShader},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.createInstance=function(t){return e.Tools.Log("LinesMeshes do not support createInstance."),null},i.prototype._bind=function(t,i,r){var n=this.getScene().getEngine();this._positionBuffer[e.VertexBuffer.PositionKind]=this._geometry.getVertexBuffer(e.VertexBuffer.PositionKind),n.bindBuffers(this._positionBuffer,this._geometry.getIndexBuffer(),this._colorShader.getEffect()),this._colorShader.setColor4("color",this.color.toColor4(this.alpha))},i.prototype._draw=function(e,t,i){if(this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){var r=this.getScene().getEngine();r.draw(!1,e.indexStart,e.indexCount)}},i.prototype.dispose=function(e){this._colorShader.dispose(),t.prototype.dispose.call(this,e)},i.prototype.clone=function(e,t,r){return new i(e,this.getScene(),t,this,r)},i})(e.Mesh);e.LinesMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){var r=this;void 0===t&&(t=""),void 0===i&&(i="black"),this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=function(){var e=r._renderingCanvas.getBoundingClientRect();r._loadingDiv.style.position="absolute",r._loadingDiv.style.left=e.left+"px",r._loadingDiv.style.top=e.top+"px",r._loadingDiv.style.width=e.width+"px",r._loadingDiv.style.height=e.height+"px"}}return e.prototype.displayLoadingUI=function(){var e=this;if(!this._loadingDiv){this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText;var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==",t.style.position="absolute",t.style.left="50%",t.style.top="50%",t.style.marginLeft="-50px",t.style.marginTop="-50px",t.style.transition="transform 1.0s ease",t.style.webkitTransition="-webkit-transform 1.0s ease";var i=360,r=function(){i+=360,t.style.transform="rotateZ("+i+"deg)",t.style.webkitTransform="rotateZ("+i+"deg)"};t.addEventListener("transitionend",r),t.addEventListener("webkitTransitionEnd",r),this._loadingDiv.appendChild(t);var n=new Image;n.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=",n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.marginLeft="-50px",n.style.marginTop="-50px",this._loadingDiv.appendChild(n),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),setTimeout((function(){e._loadingDiv.style.opacity="1",t.style.transform="rotateZ(360deg)",t.style.webkitTransform="rotateZ(360deg)"}),0)}},e.prototype.hideLoadingUI=function(){var e=this;if(this._loadingDiv){var t=function(){e._loadingDiv&&(document.body.removeChild(e._loadingDiv),window.removeEventListener("resize",e._resizeLoadingUI),e._loadingDiv=null)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",t)}},Object.defineProperty(e.prototype,"loadingUIText",{set:function(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loadingUIBackgroundColor",{get:function(){return this._loadingDivBackgroundColor},set:function(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)},enumerable:!0,configurable:!0}),e})();e.DefaultLoadingScreen=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._audioContext=null,this._audioContextInitialized=!1,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.unlocked=!1,this.isMP3supported=!1,this.isOGGsupported=!1,"undefined"==typeof window.AudioContext&&"undefined"==typeof window.webkitAudioContext||(window.AudioContext=window.AudioContext||window.webkitAudioContext,this.canUseWebAudio=!0);var e=document.createElement("audio");e&&e.canPlayType&&e.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")&&(this.isMP3supported=!0),e&&e.canPlayType&&e.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0),/iPad|iPhone|iPod/.test(navigator.platform)?this._unlockiOSaudio():this.unlocked=!0}return Object.defineProperty(t.prototype,"audioContext",{get:function(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext},enumerable:!0,configurable:!0}),t.prototype._unlockiOSaudio=function(){var e=this,t=function(){var i=e.audioContext.createBuffer(1,1,22050),r=e.audioContext.createBufferSource();r.buffer=i,r.connect(e.audioContext.destination),r.start(0),setTimeout((function(){r.playbackState!==r.PLAYING_STATE&&r.playbackState!==r.FINISHED_STATE||(e.unlocked=!0,window.removeEventListener("touchend",t,!1),e.onAudioUnlocked&&e.onAudioUnlocked())}),0)};window.addEventListener("touchend",t,!1)},t.prototype._initializeAudioContext=function(){try{this.canUseWebAudio&&(this._audioContext=new AudioContext,this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this._audioContext.destination),this._audioContextInitialized=!0)}catch(t){this.canUseWebAudio=!1,e.Tools.Error("Web Audio: "+t.message)}},t.prototype.dispose=function(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1},t.prototype.getGlobalVolume=function(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1},t.prototype.setGlobalVolume=function(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)},t.prototype.connectToAnalyser=function(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))},t})();e.AudioEngine=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){var s=this;if(this.autoplay=!1,this.loop=!1,this.useCustomAttenuation=!1,this.spatialSound=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._startOffset=0,this._position=e.Vector3.Zero(),this._localDirection=new e.Vector3(1,0,0),this._volume=1,this._isLoaded=!1,this._isReadyToPlay=!1,this.isPlaying=!1,this.isPaused=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=t,this._scene=r,this._readyToPlayCallback=n,this._customAttenuationFunction=function(e,t,i,r,n){return t<i?e*(1-t/i):0},o&&(this.autoplay=o.autoplay||!1,this.loop=o.loop||!1,void 0!==o.volume&&(this._volume=o.volume),this.spatialSound=o.spatialSound||!1,this.maxDistance=o.maxDistance||100,this.useCustomAttenuation=o.useCustomAttenuation||!1,this.rolloffFactor=o.rolloffFactor||1,this.refDistance=o.refDistance||1,this.distanceModel=o.distanceModel||"linear",this._playbackRate=o.playbackRate||1,this._streaming=o.streaming||!1),e.Engine.audioEngine.canUseWebAudio){this._soundGain=e.Engine.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._ouputAudioNode=this._soundGain,this.spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.AddSound(this);var a=!0;if(i){"string"==typeof i&&(this._urlType="String"),Array.isArray(i)&&(this._urlType="Array"),i instanceof ArrayBuffer&&(this._urlType="ArrayBuffer");var h=[],c=!1;switch(this._urlType){case"ArrayBuffer":i.byteLength>0&&(c=!0,this._soundLoaded(i));break;case"String":h.push(i);case"Array":0===h.length&&(h=i);for(var l=0;l<h.length;l++){var u=h[l];if(u.indexOf(".mp3",u.length-4)!==-1&&e.Engine.audioEngine.isMP3supported&&(c=!0),u.indexOf(".ogg",u.length-4)!==-1&&e.Engine.audioEngine.isOGGsupported&&(c=!0),u.indexOf(".wav",u.length-4)!==-1&&(c=!0),c){this._streaming?(this._htmlAudioElement=new Audio(u),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,this._htmlAudioElement.crossOrigin="anonymous",this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(function(){s._isReadyToPlay=!0,s.autoplay&&s.play(),s._readyToPlayCallback&&s._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement)):e.Tools.LoadFile(u,(function(e){s._soundLoaded(e)}),null,this._scene.database,!0);break}}break;default:a=!1}a?c||(this._isReadyToPlay=!0,this._readyToPlayCallback&&window.setTimeout((function(){s._readyToPlayCallback()}),1e3)):e.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}}else this._scene.mainSoundTrack.AddSound(this),e.Engine.audioEngine.WarnedWebAudioUnsupported||(e.Tools.Error("Web Audio is not supported by your browser."),e.Engine.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&window.setTimeout((function(){s._readyToPlayCallback()}),1e3)}return t.prototype.dispose=function(){e.Engine.audioEngine.canUseWebAudio&&this._isReadyToPlay&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.RemoveSound(this):this._scene.soundTracks[this.soundTrackId].RemoveSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedMesh=null))},t.prototype._soundLoaded=function(t){var i=this;this._isLoaded=!0,e.Engine.audioEngine.audioContext.decodeAudioData(t,(function(e){i._audioBuffer=e,i._isReadyToPlay=!0,i.autoplay&&i.play(),i._readyToPlayCallback&&i._readyToPlayCallback()}),(function(t){e.Tools.Error("Error while decoding audio data for: "+i.name+" / Error: "+t)}))},t.prototype.setAudioBuffer=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._audioBuffer=t,this._isReadyToPlay=!0)},t.prototype.updateOptions=function(e){e&&(this.loop=e.loop||this.loop,this.maxDistance=e.maxDistance||this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation||this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor||this.rolloffFactor,this.refDistance=e.refDistance||this.refDistance,this.distanceModel=e.distanceModel||this.distanceModel,this._playbackRate=e.playbackRate||this._playbackRate,this._updateSpatialParameters(),this.isPlaying&&(this._streaming?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource.playbackRate.value=this._playbackRate))},t.prototype._createSpatialParameters=function(){e.Engine.audioEngine.canUseWebAudio&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=e.Engine.audioEngine.audioContext.createPanner(),this._updateSpatialParameters(),this._soundPanner.connect(this._ouputAudioNode),this._inputAudioNode=this._soundPanner)},t.prototype._updateSpatialParameters=function(){this.spatialSound&&(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel))},t.prototype.switchPanningModelToHRTF=function(){this._panningModel="HRTF",this._switchPanningModel()},t.prototype.switchPanningModelToEqualPower=function(){this._panningModel="equalpower",this._switchPanningModel()},t.prototype._switchPanningModel=function(){e.Engine.audioEngine.canUseWebAudio&&this.spatialSound&&(this._soundPanner.panningModel=this._panningModel)},t.prototype.connectToSoundTrackAudioNode=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._isOutputConnected&&this._ouputAudioNode.disconnect(),this._ouputAudioNode.connect(t),this._isOutputConnected=!0)},t.prototype.setDirectionalCone=function(t,i,r){return i<t?void e.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=t,this._coneOuterAngle=i,this._coneOuterGain=r,this._isDirectional=!0,void(this.isPlaying&&this.loop&&(this.stop(),this.play())))},t.prototype.setPosition=function(t){this._position=t,e.Engine.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z)},t.prototype.setLocalDirectionToMesh=function(t){this._localDirection=t,e.Engine.audioEngine.canUseWebAudio&&this._connectedMesh&&this.isPlaying&&this._updateDirection()},t.prototype._updateDirection=function(){var t=this._connectedMesh.getWorldMatrix(),i=e.Vector3.TransformNormal(this._localDirection,t);i.normalize(),this._soundPanner.setOrientation(i.x,i.y,i.z)},t.prototype.updateDistanceFromListener=function(){if(e.Engine.audioEngine.canUseWebAudio&&this._connectedMesh&&this.useCustomAttenuation){var t=this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,t,this.maxDistance,this.refDistance,this.rolloffFactor)}},t.prototype.setAttenuationFunction=function(e){this._customAttenuationFunction=e},t.prototype.play=function(t,i){var r=this;if(this._isReadyToPlay&&this._scene.audioEnabled)try{this._startOffset<0&&(t=-this._startOffset,this._startOffset=0);var n=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource&&this._streamingSource||this.spatialSound&&(this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedMesh?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming?(this._streamingSource||(this._streamingSource=e.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=function(){r._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement.play()):(this._soundSource=e.Engine.audioEngine.audioContext.createBufferSource(),this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=function(){r._onended()},this._soundSource.start(n,this.isPaused?this._startOffset%this._soundSource.buffer.duration:i?i:0)),this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(o){e.Tools.Error("Error while trying to play audio: "+this.name+", "+o.message)}},t.prototype._onended=function(){this.isPlaying=!1,this.onended&&this.onended()},t.prototype.stop=function(t){if(this.isPlaying){if(this._streaming)this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0);else{var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=null,this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement.pause():(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&(i?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource.playbackRate.value=this._playbackRate)},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){this.setPosition(t.getBoundingInfo().boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var h,c={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var l=function(){o._isReadyToPlay?(h._audioBuffer=o.getAudioBuffer(),h._isReadyToPlay=!0,h.autoplay&&h.play()):window.setTimeout(l,300)};h=new t(a,new ArrayBuffer(0),r,null,c),l()}else h=new t(a,s,r,function(){r._removePendingData(h)},c),r._addPendingData(h);if(i.position){var u=e.Vector3.FromArray(i.position);h.setPosition(u)}if(i.isDirectional&&(h.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var f=e.Vector3.FromArray(i.localDirectionToMesh);h.setLocalDirectionToMesh(f)}if(i.connectedMeshId){var d=r.getMeshByID(i.connectedMeshId);d&&h.attachToMesh(d)}return h},t})();e.Sound=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(t.soundTrackId===-1?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),
t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);t!==-1&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToHRTF()},t.prototype.switchPanningModelToEqualPower=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToEqualPower()},t.prototype.connectToAnalyser=function(t){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=t,e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,e.Engine.audioEngine.masterGain))},t})();e.SoundTrack=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,i,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,o,s,a,h,c),this.direction=r,this.blurWidth=n,this.onApplyObservable.add((function(e){e.setFloat2("screenSize",l.width,l.height),e.setVector2("direction",l.direction),e.setFloat("blurWidth",l.blurWidth)}))}return __extends(i,t),i})(e.PostProcess),i=(function(){function i(t,r,n){this._vertexBuffers={},this._mainTextureDesiredSize={width:0,height:0},this._meshes={},this._maxSize=0,this._shouldRender=!1,this._instanceGlowingMeshStencilReference=i.glowingMeshStencilReference++,this._excludedMeshes={},this.innerGlow=!0,this.outerGlow=!0,this.isEnabled=!0,this.onDisposeObservable=new e.Observable,this.onBeforeRenderMainTextureObservable=new e.Observable,this.onBeforeBlurObservable=new e.Observable,this.onAfterBlurObservable=new e.Observable,this.onBeforeComposeObservable=new e.Observable,this.onAfterComposeObservable=new e.Observable,this.onSizeChangedObservable=new e.Observable,this._scene=r;var o=r.getEngine();this._engine=o,this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.highlightLayers.push(this),this._engine.isStencilEnable||e.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }"),this._options=n||{mainTextureRatio:.25,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:e.Engine.ALPHA_COMBINE},this._options.mainTextureRatio=this._options.mainTextureRatio||.25,this._options.blurTextureSizeRatio=this._options.blurTextureSizeRatio||.5,this._options.blurHorizontalSize=this._options.blurHorizontalSize||1,this._options.blurVerticalSize=this._options.blurVerticalSize||1,this._options.alphaBlendingMode=this._options.alphaBlendingMode||e.Engine.ALPHA_COMBINE;var s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1);var a=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,(!1),(!1),2);this._vertexBuffers[e.VertexBuffer.PositionKind]=a;var h=[];h.push(0),h.push(1),h.push(2),h.push(0),h.push(2),h.push(3),this._indexBuffer=o.createIndexBuffer(h),this._glowMapMergeEffect=o.createEffect("glowMapMerge",[e.VertexBuffer.PositionKind],["offset"],["textureSampler"],""),this.setMainTextureSize(),this.createTextureAndPostProcesses()}return Object.defineProperty(i.prototype,"blurHorizontalSize",{get:function(){return this._horizontalBlurPostprocess.blurWidth},set:function(e){this._horizontalBlurPostprocess.blurWidth=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurVerticalSize",{get:function(){return this._verticalBlurPostprocess.blurWidth},set:function(e){this._verticalBlurPostprocess.blurWidth=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"camera",{get:function(){return this._options.camera},enumerable:!0,configurable:!0}),i.prototype.createTextureAndPostProcesses=function(){var r=this,n=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,o=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;n=e.Tools.GetExponentOfTwo(n,this._maxSize),o=e.Tools.GetExponentOfTwo(o,this._maxSize),this._mainTexture=new e.RenderTargetTexture("HighlightLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._mainTexture.activeCamera=this._options.camera,this._mainTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._blurTexture=new e.RenderTargetTexture("HighlightLayerBlurRTT",{width:n,height:o},this._scene,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._blurTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(e.Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._downSamplePostprocess=new e.PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",r._mainTexture)})),this._options.alphaBlendingMode===e.Engine.ALPHA_COMBINE?(this._horizontalBlurPostprocess=new t("HighlightLayerHBP",new e.Vector2(1,0),this._options.blurHorizontalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)})),this._verticalBlurPostprocess=new t("HighlightLayerVBP",new e.Vector2(0,1),this._options.blurVerticalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)}))):(this._horizontalBlurPostprocess=new e.BlurPostProcess("HighlightLayerHBP",new e.Vector2(1,0),this._options.blurHorizontalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)})),this._verticalBlurPostprocess=new e.BlurPostProcess("HighlightLayerVBP",new e.Vector2(0,1),this._options.blurVerticalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)}))),this._mainTexture.onAfterUnbindObservable.add((function(){r.onBeforeBlurObservable.notifyObservers(r),r._scene.postProcessManager.directRender([r._downSamplePostprocess,r._horizontalBlurPostprocess,r._verticalBlurPostprocess],r._blurTexture.getInternalTexture()),r.onAfterBlurObservable.notifyObservers(r)}));var s=function(t){var n=t.getRenderingMesh(),o=r._scene,s=o.getEngine();s.setState(t.getMaterial().backFaceCulling);var a=n._getInstancesRenderList(t._id);if(!a.mustReturn&&!r._excludedMeshes[n.id]){var h=null!==s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id]&&void 0!==a.visibleInstances[t._id],c=r._meshes[n.id],l=t.getMaterial(),u=null;if(c&&c.glowEmissiveOnly&&l&&(u=l.emissiveTexture),r.isReady(t,h,u)){if(s.enableEffect(r._glowMapGenerationEffect),n._bind(t,r._glowMapGenerationEffect,e.Material.TriangleFillMode),r._glowMapGenerationEffect.setMatrix("viewProjection",o.getTransformMatrix()),c?r._glowMapGenerationEffect.setFloat4("color",c.color.r,c.color.g,c.color.b,1):r._glowMapGenerationEffect.setFloat4("color",i.neutralColor.r,i.neutralColor.g,i.neutralColor.b,i.neutralColor.a),l&&l.needAlphaTesting()){var f=l.getAlphaTestTexture();r._glowMapGenerationEffect.setTexture("diffuseSampler",f),r._glowMapGenerationEffect.setMatrix("diffuseMatrix",f.getTextureMatrix())}u&&(r._glowMapGenerationEffect.setTexture("emissiveSampler",u),r._glowMapGenerationEffect.setMatrix("emissiveMatrix",u.getTextureMatrix())),n.useBones&&n.computeBonesUsingShaders&&r._glowMapGenerationEffect.setMatrices("mBones",n.skeleton.getTransformMatrices(n)),n._processRendering(t,r._glowMapGenerationEffect,e.Material.TriangleFillMode,a,h,(function(e,t){return r._glowMapGenerationEffect.setMatrix("world",t)}))}else r._mainTexture.resetRefreshCounter()}};this._mainTexture.customRenderFunction=function(e,t,i){r.onBeforeRenderMainTextureObservable.notifyObservers(r);var n;for(n=0;n<e.length;n++)s(e.data[n]);for(n=0;n<t.length;n++)s(t.data[n]);for(n=0;n<i.length;n++)s(i.data[n])},this._mainTexture.onClearObservable.add((function(e){e.clear(i.neutralColor,!0,!0,!0)}))},i.prototype.isReady=function(t,i,r){if(!t.getMaterial().isReady(t.getMesh(),i))return!1;var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMesh(),a=t.getMaterial(),h=!1,c=!1;if(a&&a.needAlphaTesting()){var l=a.getAlphaTestTexture();l&&(n.push("#define ALPHATEST"),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===l.coordinatesIndex?(n.push("#define DIFFUSEUV2"),c=!0):s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push("#define DIFFUSEUV1"),h=!0))}r&&(n.push("#define EMISSIVE"),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===r.coordinatesIndex?(n.push("#define EMISSIVEUV2"),c=!0):s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push("#define EMISSIVEUV1"),h=!0)),h&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),c&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2")),s.useBones&&s.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),s.numBoneInfluencers>4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var u=n.join("\n");return this._cachedDefines!==u&&(this._cachedDefines=u,this._glowMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",o,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix"],["diffuseSampler","emissiveSampler"],u)),this._glowMapGenerationEffect.isReady()},i.prototype.render=function(){var t=this._glowMapMergeEffect;if(t.isReady()&&this._blurTexture.isReady()){var i=this._scene.getEngine();this.onBeforeComposeObservable.notifyObservers(this),i.enableEffect(t),i.setState(!1);var r=i.getStencilBuffer(),n=i.getStencilFunction(),o=i.getStencilMask(),s=i.getAlphaMode();t.setTexture("textureSampler",this._blurTexture),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t),i.setAlphaMode(this._options.alphaBlendingMode),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&(t.setFloat("offset",0),i.setStencilFunction(e.Engine.NOTEQUAL),i.draw(!0,0,6)),this.innerGlow&&(t.setFloat("offset",1),i.setStencilFunction(e.Engine.EQUAL),i.draw(!0,0,6)),i.setStencilFunction(n),i.setStencilMask(o),i.setAlphaMode(s),i.setStencilBuffer(r),this.onAfterComposeObservable.notifyObservers(this);var a=this._mainTexture.getSize();this.setMainTextureSize(),a.width===this._mainTextureDesiredSize.width&&a.height===this._mainTextureDesiredSize.height||(this.onSizeChangedObservable.notifyObservers(this),this.disposeTextureAndPostProcesses(),this.createTextureAndPostProcesses())}},i.prototype.addExcludedMesh=function(e){var t=this._excludedMeshes[e.id];t||(this._excludedMeshes[e.id]={mesh:e,beforeRender:e.onBeforeRenderObservable.add((function(e){e.getEngine().setStencilBuffer(!1)})),afterRender:e.onAfterRenderObservable.add((function(e){e.getEngine().setStencilBuffer(!0)}))})},i.prototype.removeExcludedMesh=function(e){var t=this._excludedMeshes[e.id];t&&(e.onBeforeRenderObservable.remove(t.beforeRender),e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.id]=void 0},i.prototype.addMesh=function(e,t,i){var r=this;void 0===i&&(i=!1);var n=this._meshes[e.id];n?n.color=t:this._meshes[e.id]={mesh:e,color:t,observerHighlight:e.onBeforeRenderObservable.add((function(e){r._excludedMeshes[e.id]?r.defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(r._instanceGlowingMeshStencilReference)})),observerDefault:e.onAfterRenderObservable.add(this.defaultStencilReference),glowEmissiveOnly:i},this._shouldRender=!0},i.prototype.removeMesh=function(e){var t=this._meshes[e.id];t&&(e.onBeforeRenderObservable.remove(t.observerHighlight),e.onAfterRenderObservable.remove(t.observerDefault)),this._meshes[e.id]=void 0,this._shouldRender=!1;for(var i in this._meshes)if(i){this._shouldRender=!0;break}},i.prototype.shouldRender=function(){return this.isEnabled&&this._shouldRender},i.prototype.setMainTextureSize=function(){this._options.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._options.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._options.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderingCanvas().width*this._options.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderingCanvas().height*this._options.mainTextureRatio,this._mainTextureDesiredSize.width=e.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize),this._mainTextureDesiredSize.height=e.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize))},i.prototype.defaultStencilReference=function(e){e.getScene().getEngine().setStencilFunctionReference(i.normalMeshStencilReference)},i.prototype.disposeTextureAndPostProcesses=function(){this._blurTexture.dispose(),this._mainTexture.dispose(),this._downSamplePostprocess.dispose(),this._horizontalBlurPostprocess.dispose(),this._verticalBlurPostprocess.dispose()},i.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.disposeTextureAndPostProcesses();for(var i in this._meshes){var r=this._meshes[i];r&&r.mesh&&(r.mesh.onBeforeRenderObservable.remove(r.observerHighlight),r.mesh.onAfterRenderObservable.remove(r.observerDefault))}this._meshes=null;for(var i in this._excludedMeshes){var r=this._excludedMeshes[i];r&&(r.mesh.onBeforeRenderObservable.remove(r.beforeRender),r.mesh.onAfterRenderObservable.remove(r.afterRender))}this._excludedMeshes=null;var n=this._scene.highlightLayers.indexOf(this,0);n>-1&&this._scene.highlightLayers.splice(n,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeBlurObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},i.neutralColor=new e.Color4(0,0,0,0),i.glowingMeshStencilReference=2,i.normalMeshStencilReference=1,i})();e.HighlightLayer=i})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore={anaglyphPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}",blackAndWhitePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}",blurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",chromaticAberrationPixelShader:"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}",colorPixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",colorVertexShader:"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}",colorCorrectionPixelShader:"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}",convolutionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}",defaultPixelShader:"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}",defaultVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}",
depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",depthOfFieldPixelShader:"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n",displayPassPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}",filterPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}",fxaaPixelShader:"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}",glowBlurPostProcessPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",glowMapGenerationPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}",glowMapGenerationVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",glowMapMergePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}",glowMapMergeVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",hdrPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n",layerPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}",layerVertexShader:"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}",lensFlarePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}",lensFlareVertexShader:"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}",lensHighlightsPixelShader:"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}",linePixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",lineVertexShader:"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}",outlinePixelShader:"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}",outlineVertexShader:"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",pbrPixelShader:"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}",
pbrVertexShader:"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",refractionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}",shadowMapPixelShader:"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n",ssaoCombinePixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n",standardPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n",stereoscopicInterlacePixelShader:"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}",tonemapPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}",volumetricLightScatteringPixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n",volumetricLightScatteringPassPixelShader:"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n",vrDistortionCorrectionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"},BABYLON.Effect.IncludesShadersStore={bonesDeclaration:"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif",bonesVertex:"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif",bumpFragment:"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif",bumpFragmentFunctions:"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif",clipPlaneFragment:"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif",clipPlaneFragmentDeclaration:"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif",clipPlaneVertex:"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif",clipPlaneVertexDeclaration:"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif",colorCurves:"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}",colorCurvesDefinition:"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;",colorGrading:"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}",colorGradingDefinition:"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;",fogFragment:"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif",fogFragmentDeclaration:"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif",fogVertex:"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif",fogVertexDeclaration:"#ifdef FOG\nvarying float fFogDistance;\n#endif",fresnelFunction:"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif",harmonicsFunctions:"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif",helperFunctions:"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}",instancesDeclaration:"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif",instancesVertex:"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif",lightFragment:"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif",lightFragmentDeclaration:"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif",lightsFragmentFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n",
logDepthDeclaration:"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif",logDepthFragment:"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif",logDepthVertex:"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif",pbrFunctions:"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif",pbrLightFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}",pbrLightFunctionsCall:"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif",pbrShadowFunctions:"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif",pointCloudVertex:"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif",pointCloudVertexDeclaration:"#ifdef POINTSIZE\nuniform float pointSize;\n#endif",reflectionFunction:"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}",shadowsFragmentFunctions:"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif",shadowsVertex:"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif",shadowsVertexDeclaration:"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"},("undefined"!=typeof window&&window.module||"undefined"!=typeof module)&&"undefined"!=typeof module.exports&&(module.exports=BABYLON);
 
Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.js

Statements: 3.89% (500 / 12865)      Branches: 0.26% (32 / 12390)      Functions: 1.19% (56 / 4700)      Lines: 97.06% (33 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 3945 24 3 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1          
var __decorate=this&&this.__decorate||function(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},__extends=this&&this.__extends||function(e,t){function i(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);i.prototype=t.prototype,e.prototype=new i},BABYLON;!(function(e){e.ToGammaSpace=1/2.2,e.ToLinearSpace=2.2,e.Epsilon=.001;var t=(function(){function e(){}return e.WithinEpsilon=function(e,t,i){void 0===i&&(i=1.401298e-45);var r=e-t;return-i<=r&&r<=i},e.ToHex=function(e){var t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()},e.Sign=function(e){return e=+e,0===e||isNaN(e)?e:e>0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e})();e.MathTools=t;var i=(function(){function i(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.r=e,this.g=t,this.b=i}return i.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},i.prototype.getClassName=function(){return"Color3"},i.prototype.getHashCode=function(){var e=this.r||0;return e=397*e^(this.g||0),e=397*e^(this.b||0)},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this},i.prototype.toColor4=function(e){return void 0===e&&(e=1),new r(this.r,this.g,this.b,e)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(e){return new i(this.r*e.r,this.g*e.g,this.b*e.b)},i.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this},i.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b},i.prototype.equalsFloats=function(e,t,i){return this.r===e&&this.g===t&&this.b===i},i.prototype.scale=function(e){return new i(this.r*e,this.g*e,this.b*e)},i.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this},i.prototype.add=function(e){return new i(this.r+e.r,this.g+e.g,this.b+e.b)},i.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this},i.prototype.subtract=function(e){return new i(this.r-e.r,this.g-e.g,this.b-e.b)},i.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},i.prototype.copyFromFloats=function(e,t,i){return this.r=e,this.g=t,this.b=i,this},i.prototype.toHexString=function(){var e=255*this.r|0,i=255*this.g|0,r=255*this.b|0;return"#"+t.ToHex(e)+t.ToHex(i)+t.ToHex(r)},i.prototype.toLinearSpace=function(){var e=new i;return this.toLinearSpaceToRef(e),e},i.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,e.ToLinearSpace),t.g=Math.pow(this.g,e.ToLinearSpace),t.b=Math.pow(this.b,e.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var e=new i;return this.toGammaSpaceToRef(e),e},i.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,e.ToGammaSpace),t.g=Math.pow(this.g,e.ToGammaSpace),t.b=Math.pow(this.b,e.ToGammaSpace),this},i.FromHexString=function(e){if("#"!==e.substring(0,1)||7!==e.length)return new i(0,0,0);var t=parseInt(e.substring(1,3),16),r=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return i.FromInts(t,r,n)},i.FromArray=function(e,t){return void 0===t&&(t=0),new i(e[t],e[t+1],e[t+2])},i.FromInts=function(e,t,r){return new i(e/255,t/255,r/255)},i.Lerp=function(e,t,r){var n=e.r+(t.r-e.r)*r,o=e.g+(t.g-e.g)*r,s=e.b+(t.b-e.b)*r;return new i(n,o,s)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i})();e.Color3=i;var r=(function(){function e(e,t,i,r){this.r=e,this.g=t,this.b=i,this.a=r}return e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this},e.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t,this.a*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t},e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},e.prototype.getClassName=function(){return"Color4"},e.prototype.getHashCode=function(){var e=this.r||0;return e=397*e^(this.g||0),e=397*e^(this.b||0),e=397*e^(this.a||0)},e.prototype.clone=function(){return new e(this.r,this.g,this.b,this.a)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},e.prototype.toHexString=function(){var e=255*this.r|0,i=255*this.g|0,r=255*this.b|0,n=255*this.a|0;return"#"+t.ToHex(e)+t.ToHex(i)+t.ToHex(r)+t.ToHex(n)},e.FromHexString=function(t){if("#"!==t.substring(0,1)||9!==t.length)return new e(0,0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16),o=parseInt(t.substring(7,9),16);return e.FromInts(i,r,n,o)},e.Lerp=function(t,i,r){var n=new e(0,0,0,0);return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromInts=function(t,i,r,n){return new e(t/255,i/255,r/255,n/255)},e.CheckColors4=function(e,t){if(e.length===3*t){for(var i=[],r=0;r<e.length;r+=3){var n=r/3*4;i[n]=e[r],i[n+1]=e[r+1],i[n+2]=e[r+2],i[n+3]=1}return i}return e},e})();e.Color4=r;var n=(function(){function i(e,t){this.x=e,this.y=t}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+"}"},i.prototype.getClassName=function(){return"Vector2"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0)},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,this},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this},i.prototype.copyFromFloats=function(e,t){return this.x=e,this.y=t,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,this},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this},i.prototype.addVector3=function(e){return new i(this.x+e.x,this.y+e.y)},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,this},i.prototype.multiplyByFloats=function(e,t){return new i(this.x*e,this.y*t)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,this},i.prototype.negate=function(){return new i((-this.x),(-this.y))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e)},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(e,t){return void 0===t&&(t=0),new i(e[t],e[t+1])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1]},i.CatmullRom=function(e,t,r,n,o){var s=o*o,a=o*s,h=.5*(2*t.x+(-e.x+r.x)*o+(2*e.x-5*t.x+4*r.x-n.x)*s+(-e.x+3*t.x-3*r.x+n.x)*a),c=.5*(2*t.y+(-e.y+r.y)*o+(2*e.y-5*t.y+4*r.y-n.y)*s+(-e.y+3*t.y-3*r.y+n.y)*a);return new i(h,c)},i.Clamp=function(e,t,r){var n=e.x;n=n>r.x?r.x:n,n=n<t.x?t.x:n;var o=e.y;return o=o>r.y?r.y:o,o=o<t.y?t.y:o,new i(n,o)},i.Hermite=function(e,t,r,n,o){var s=o*o,a=o*s,h=2*a-3*s+1,c=-2*a+3*s,l=a-2*s+o,u=a-s,d=e.x*h+r.x*c+t.x*l+n.x*u,f=e.y*h+r.y*c+t.y*l+n.y*u;return new i(d,f)},i.Lerp=function(e,t,r){var n=e.x+(t.x-e.x)*r,o=e.y+(t.y-e.y)*r;return new i(n,o)},i.Dot=function(e,t){return e.x*t.x+e.y*t.y},i.Normalize=function(e){var t=e.clone();return t.normalize(),t},i.Minimize=function(e,t){var r=e.x<t.x?e.x:t.x,n=e.y<t.y?e.y:t.y;return new i(r,n)},i.Maximize=function(e,t){var r=e.x>t.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new i(r,n)},i.Transform=function(e,t){var r=i.Zero();return i.TransformToRef(e,t,r),r},i.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},i.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i.DistanceOfPointFromSegment=function(e,t,r){var n=i.DistanceSquared(t,r);if(0===n)return i.Distance(e,t);var o=r.subtract(t),s=Math.max(0,Math.min(1,i.Dot(e.subtract(t),o)/n)),a=t.add(o.multiplyByFloats(s,s));return i.Distance(e,a)},i})();e.Vector2=n;var o=(function(){function i(e,t,i){this.x=e,this.y=t,this.z=i}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},i.prototype.getClassName=function(){return"Vector3"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},i.prototype.toQuaternion=function(){var e=new h(0,0,0,1),t=Math.cos(.5*(this.x+this.z)),i=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),o=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return e.x=r*s,e.y=-n*s,e.z=i*o,e.w=t*o,e},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y,this.z+e.z)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y,this.z-e.z)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},i.prototype.subtractFromFloats=function(e,t,r){return new i(this.x-e,this.y-t,this.z-r)},i.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},i.prototype.negate=function(){return new i((-this.x),(-this.y),(-this.z))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e,this.z*e)},i.prototype.scaleToRef=function(e,t){t.x=this.x*e,t.y=this.y*e,t.z=this.z*e},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)&&t.WithinEpsilon(this.z,i.z,r)},i.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y,this.z*e.z)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},i.prototype.multiplyByFloats=function(e,t,r){return new i(this.x*e,this.y*t,this.z*r)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y,this.z/e.z)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},i.prototype.MinimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this},i.prototype.MaximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},i.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},i.GetClipFactor=function(e,t,r,n){var o=i.Dot(e,r)-n,s=i.Dot(t,r)-n,a=o/(o-s);return a},i.FromArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2])},i.FromFloatArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},i.FromFloatArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},i.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.Forward=function(){return new i(0,0,1)},i.Right=function(){return new i(1,0,0)},i.Left=function(){return new i((-1),0,0)},i.TransformCoordinates=function(e,t){var r=i.Zero();return i.TransformCoordinatesToRef(e,t,r),r},i.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},i.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],h=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/h,n.y=s/h,n.z=a/h},i.TransformNormal=function(e,t){var r=i.Zero();return i.TransformNormalToRef(e,t,r),r},i.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},i.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},i.CatmullRom=function(e,t,r,n,o){var s=o*o,a=o*s,h=.5*(2*t.x+(-e.x+r.x)*o+(2*e.x-5*t.x+4*r.x-n.x)*s+(-e.x+3*t.x-3*r.x+n.x)*a),c=.5*(2*t.y+(-e.y+r.y)*o+(2*e.y-5*t.y+4*r.y-n.y)*s+(-e.y+3*t.y-3*r.y+n.y)*a),l=.5*(2*t.z+(-e.z+r.z)*o+(2*e.z-5*t.z+4*r.z-n.z)*s+(-e.z+3*t.z-3*r.z+n.z)*a);return new i(h,c,l)},i.Clamp=function(e,t,r){var n=e.x;n=n>r.x?r.x:n,n=n<t.x?t.x:n;var o=e.y;o=o>r.y?r.y:o,o=o<t.y?t.y:o;var s=e.z;return s=s>r.z?r.z:s,s=s<t.z?t.z:s,new i(n,o,s)},i.Hermite=function(e,t,r,n,o){var s=o*o,a=o*s,h=2*a-3*s+1,c=-2*a+3*s,l=a-2*s+o,u=a-s,d=e.x*h+r.x*c+t.x*l+n.x*u,f=e.y*h+r.y*c+t.y*l+n.y*u,p=e.z*h+r.z*c+t.z*l+n.z*u;return new i(d,f,p)},i.Lerp=function(e,t,r){var n=e.x+(t.x-e.x)*r,o=e.y+(t.y-e.y)*r,s=e.z+(t.z-e.z)*r;return new i(n,o,s)},i.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z},i.Cross=function(e,t){var r=i.Zero();return i.CrossToRef(e,t,r),r},i.CrossToRef=function(e,t,i){P.Vector3[0].x=e.y*t.z-e.z*t.y,P.Vector3[0].y=e.z*t.x-e.x*t.z,P.Vector3[0].z=e.x*t.y-e.y*t.x,i.copyFrom(P.Vector3[0])},i.Normalize=function(e){var t=i.Zero();return i.NormalizeToRef(e,t),t},i.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},i.Project=function(e,t,r,n){var o=n.width,s=n.height,a=n.x,h=n.y,l=i._viewportMatrixCache?i._viewportMatrixCache:i._viewportMatrixCache=new c;c.FromValuesToRef(o/2,0,0,0,0,-s/2,0,0,0,0,1,0,a+o/2,s/2+h,0,1,l);var u=i._matrixCache?i._matrixCache:i._matrixCache=new c;return t.multiplyToRef(r,u),u.multiplyToRef(l,u),i.TransformCoordinates(e,u)},i.UnprojectFromTransform=function(e,r,n,o,s){var a=i._matrixCache?i._matrixCache:i._matrixCache=new c;o.multiplyToRef(s,a),a.invert(),e.x=e.x/r*2-1,e.y=-(e.y/n*2-1);var h=i.TransformCoordinates(e,a),l=e.x*a.m[3]+e.y*a.m[7]+e.z*a.m[11]+a.m[15];return t.WithinEpsilon(l,1)&&(h=h.scale(1/l)),h},i.Unproject=function(e,r,n,o,s,a){var h=i._matrixCache?i._matrixCache:i._matrixCache=new c;o.multiplyToRef(s,h),h.multiplyToRef(a,h),h.invert();var l=new i(e.x/r*2-1,(-(e.y/n*2-1)),e.z),u=i.TransformCoordinates(l,h),d=l.x*h.m[3]+l.y*h.m[7]+l.z*h.m[11]+h.m[15];return t.WithinEpsilon(d,1)&&(u=u.scale(1/d)),u},i.Minimize=function(e,t){var i=e.clone();return i.MinimizeInPlace(t),i},i.Maximize=function(e,t){var i=e.clone();return i.MaximizeInPlace(t),i},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z;return i*i+r*r+n*n},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i.RotationFromAxis=function(e,t,r){var n=i.Zero();return i.RotationFromAxisToRef(e,t,r,n),n},i.RotationFromAxisToRef=function(r,n,o,s){var a=r.normalize(),h=o.normalize(),c=f.X,l=f.Y,u=0,d=0,p=0,m=0,_=0,g=0,v=0,y=-1,x=0,b=P.Vector3[0],T=0,A=P.Vector3[1];t.WithinEpsilon(h.z,0,e.Epsilon)?g=1:t.WithinEpsilon(h.x,0,e.Epsilon)?m=1:(v=h.z/h.x,m=-v*Math.sqrt(1/(1+v*v)),g=Math.sqrt(1/(1+v*v))),A.x=m,A.y=_,A.z=g,A.normalize(),i.CrossToRef(a,A,b),b.normalize(),i.Dot(h,b)<0&&(y=1),T=i.Dot(a,A),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*y,i.Dot(A,c)<0&&(p=Math.PI+p,A=A.scaleInPlace(-1),x++);var E=P.Vector3[2],M=P.Vector3[3];m=0,_=0,g=0,y=-1,t.WithinEpsilon(h.z,0,e.Epsilon)?m=1:(v=A.z/A.x,m=-v*Math.sqrt(1/(1+v*v)),g=Math.sqrt(1/(1+v*v))),E.x=m,E.y=_,E.z=g,E.normalize(),i.CrossToRef(E,A,M),M.normalize(),i.CrossToRef(h,E,b),b.normalize(),i.Dot(A,b)<0&&(y=1),T=i.Dot(h,E),T=Math.min(1,Math.max(-1,T)),d=Math.acos(T)*y,i.Dot(M,l)<0&&(d=Math.PI+d,x++),y=-1,i.CrossToRef(c,A,b),b.normalize(),i.Dot(b,l)<0&&(y=1),T=i.Dot(A,c),T=Math.min(1,Math.max(-1,T)),u=-Math.acos(T)*y,T<0&&x<2&&(u=Math.PI+u),s.x=d,s.y=u,s.z=p},i})();e.Vector3=o;var s=(function(){function i(e,t,i,r){this.x=e,this.y=t,this.z=i,this.w=r}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},i.prototype.getClassName=function(){return"Vector4"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,this},i.prototype.subtractFromFloats=function(e,t,r,n){return new i(this.x-e,this.y-t,this.z-r,this.w-n)},i.prototype.subtractFromFloatsToRef=function(e,t,i,r,n){return n.x=this.x-e,n.y=this.y-t,n.z=this.z-i,n.w=this.w-r,this},i.prototype.negate=function(){return new i((-this.x),(-this.y),(-this.z),(-this.w))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e,this.z*e,this.w*e)},i.prototype.scaleToRef=function(e,t){t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)&&t.WithinEpsilon(this.z,i.z,r)&&t.WithinEpsilon(this.w,i.w,r)},i.prototype.equalsToFloats=function(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,this},i.prototype.multiplyByFloats=function(e,t,r,n){return new i(this.x*e,this.y*t,this.z*r,this.w*n)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,this},i.prototype.MinimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this},i.prototype.MaximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toVector3=function(){return new o(this.x,this.y,this.z)},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},i.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},i.FromArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2],e[t+3])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},i.FromFloatArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},i.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(e){var t=i.Zero();return i.NormalizeToRef(e,t),t},i.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},i.Minimize=function(e,t){var i=e.clone();return i.MinimizeInPlace(t),i},i.Maximize=function(e,t){var i=e.clone();return i.MaximizeInPlace(t),i},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i})();e.Vector4=s;var a=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){this.width=e,this.height=t},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){var i=new e(this.width+t.width,this.height+t.height);return i},e.prototype.substract=function(t){var i=new e(this.width-t.width,this.height-t.height);return i},e.Lerp=function(t,i,r){var n=t.width+(i.width-t.width)*r,o=t.height+(i.height-t.height)*r;return new e(n,o)},e})();e.Size=a;var h=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){var t=new e((-this.x),(-this.y),(-this.z),this.w);return t},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=o.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,h=r*r,c=n*n,l=n*i-r*o,u=.4999999;return l<-u?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):l>u?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-h+c+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-h-c+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,h=this.y*this.z,c=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(h+c),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(h-c),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],h=r[5],c=r[9],l=r[2],u=r[6],d=r[10],f=n+h+d;f>0?(i=.5/Math.sqrt(f+1),t.w=.25/i,t.x=(u-c)*i,t.y=(s-l)*i,t.z=(a-o)*i):n>h&&n>d?(i=2*Math.sqrt(1+n-h-d),t.w=(u-c)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+l)/i):h>d?(i=2*Math.sqrt(1+h-n-d),t.w=(s-l)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(c+u)/i):(i=2*Math.sqrt(1+d-n-h),t.w=(a-o)/i,t.x=(s+l)/i,t.y=(c+u)/i,t.z=.25*i)},e.Inverse=function(t){return new e((-t.x),(-t.y),(-t.z),t.w)},e.Identity=function(){return new e(0,0,0,1)},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),h=Math.cos(n),c=Math.sin(o),l=Math.cos(o),u=Math.sin(s),d=Math.cos(s);r.x=d*c*h+u*l*a,r.y=u*l*h-d*c*a,r.z=d*l*a-u*c*h,r.w=d*l*h+u*c*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=i,a=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,h=!1;if(a<0&&(h=!0,a=-a),a>.999999)o=1-s,n=h?-s:s;else{var c=Math.acos(a),l=1/Math.sin(c);o=Math.sin((1-s)*c)*l,n=h?-Math.sin(s*c)*l:Math.sin(s*c)*l}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e})();e.Quaternion=h;var c=(function(){function e(){this.m=new Float32Array(16)}return e.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],h=this.m[7],c=this.m[8],l=this.m[9],u=this.m[10],d=this.m[11],f=this.m[12],p=this.m[13],m=this.m[14],_=this.m[15],g=u*_-d*m,v=l*_-d*p,y=l*m-u*p,x=c*_-d*f,b=c*m-u*f,T=c*p-l*f,A=s*g-a*v+h*y,E=-(o*g-a*x+h*b),P=o*v-s*x+h*T,M=-(o*y-s*b+a*T),S=1/(t*A+i*E+r*P+n*M),C=a*_-h*m,R=s*_-h*p,O=s*m-a*p,D=o*_-h*f,I=o*m-a*f,w=o*p-s*f,L=a*d-h*u,B=s*d-h*l,F=s*u-a*l,V=o*d-h*c,N=o*u-a*c,z=o*l-s*c;return e.m[0]=A*S,e.m[4]=E*S,e.m[8]=P*S,e.m[12]=M*S,e.m[1]=-(i*g-r*v+n*y)*S,e.m[5]=(t*g-r*x+n*b)*S,e.m[9]=-(t*v-i*x+n*T)*S,e.m[13]=(t*y-i*b+r*T)*S,e.m[2]=(i*C-r*R+n*O)*S,
e.m[6]=-(t*C-r*D+n*I)*S,e.m[10]=(t*R-i*D+n*w)*S,e.m[14]=-(t*O-i*I+r*w)*S,e.m[3]=-(i*L-r*B+n*F)*S,e.m[7]=(t*L-r*V+n*N)*S,e.m[11]=-(t*B-i*V+n*z)*S,e.m[15]=(t*F-i*N+r*z)*S,this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this},e.prototype.getTranslation=function(){return new o(this.m[12],this.m[13],this.m[14])},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],h=this.m[5],c=this.m[6],l=this.m[7],u=this.m[8],d=this.m[9],f=this.m[10],p=this.m[11],m=this.m[12],_=this.m[13],g=this.m[14],v=this.m[15],y=e.m[0],x=e.m[1],b=e.m[2],T=e.m[3],A=e.m[4],E=e.m[5],P=e.m[6],M=e.m[7],S=e.m[8],C=e.m[9],R=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],w=e.m[14],L=e.m[15];return t[i]=r*y+n*A+o*S+s*D,t[i+1]=r*x+n*E+o*C+s*I,t[i+2]=r*b+n*P+o*R+s*w,t[i+3]=r*T+n*M+o*O+s*L,t[i+4]=a*y+h*A+c*S+l*D,t[i+5]=a*x+h*E+c*C+l*I,t[i+6]=a*b+h*P+c*R+l*w,t[i+7]=a*T+h*M+c*O+l*L,t[i+8]=u*y+d*A+f*S+p*D,t[i+9]=u*x+d*E+f*C+p*I,t[i+10]=u*b+d*P+f*R+p*w,t[i+11]=u*T+d*M+f*O+p*L,t[i+12]=m*y+_*A+g*S+v*D,t[i+13]=m*x+_*E+g*C+v*I,t[i+14]=m*b+_*P+g*R+v*w,t[i+15]=m*T+_*M+g*O+v*L,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(i,r,n){n.x=this.m[12],n.y=this.m[13],n.z=this.m[14];var o=t.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=t.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return i.x=o*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),i.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),i.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===i.x||0===i.y||0===i.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(e.FromValuesToRef(this.m[0]/i.x,this.m[1]/i.x,this.m[2]/i.x,0,this.m[4]/i.y,this.m[5]/i.y,this.m[6]/i.y,0,this.m[8]/i.z,this.m[9]/i.z,this.m[10]/i.z,0,0,0,0,1,P.Matrix[0]),h.FromRotationMatrixToRef(P.Matrix[0],r),!0)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=i[0]*i[1]*i[2]*i[3]<0?-1:1,n=i[4]*i[5]*i[6]*i[7]<0?-1:1,o=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=r*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),a=n*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),h=o*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);e.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/a,i[5]/a,i[6]/a,0,i[8]/h,i[9]/h,i[10]/h,0,0,0,0,1,t)},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t]},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,h,c,l,u,d,f,p,m,_){_.m[0]=e,_.m[1]=t,_.m[2]=i,_.m[3]=r,_.m[4]=n,_.m[5]=o,_.m[6]=s,_.m[7]=a,_.m[8]=h,_.m[9]=c,_.m[10]=l,_.m[11]=u,_.m[12]=d,_.m[13]=f,_.m[14]=p,_.m[15]=m},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new s(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this},e.FromValues=function(t,i,r,n,o,s,a,h,c,l,u,d,f,p,m,_){var g=new e;return g.m[0]=t,g.m[1]=i,g.m[2]=r,g.m[3]=n,g.m[4]=o,g.m[5]=s,g.m[6]=a,g.m[7]=h,g.m[8]=c,g.m[9]=l,g.m[10]=u,g.m[11]=d,g.m[12]=f,g.m[13]=p,g.m[14]=m,g.m[15]=_,g},e.Compose=function(t,i,r){var n=e.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),o=e.Identity();return i.toRotationMatrix(o),n=n.multiply(o),n.setTranslation(r),n},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0,i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){h.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){for(var n=e.Zero(),o=0;o<16;o++)n.m[o]=t.m[o]*(1-r)+i.m[o]*r;return n},e.DecomposeLerp=function(t,i,r){var n=new o(0,0,0),s=new h,a=new o(0,0,0);t.decompose(n,s,a);var c=new o(0,0,0),l=new h,u=new o(0,0,0);i.decompose(c,l,u);var d=o.Lerp(n,c,r),f=h.Slerp(s,l,r),p=o.Lerp(a,u,r);return e.Compose(d,f,p)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,n){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-o.Dot(this._xAxis,t),a=-o.Dot(this._yAxis,t),h=-o.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,h,1,n)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,n){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-o.Dot(this._xAxis,t),a=-o.Dot(this._yAxis,t),h=-o.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,h,1,n)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=2/t,a=2/i,h=1/(n-r),c=r/(r-n);e.FromValuesToRef(s,0,0,0,0,a,0,0,0,0,h,0,0,0,c,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(e,t,i,r,n,o,s){s.m[0]=2/(t-e),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-i),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(o-n),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(e+t)/(e-t),s.m[13]=(r+i)/(i-r),s.m[14]=-n/(o-n),s.m[15]=1},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero();return o.m[0]=2*r/t,o.m[1]=o.m[2]=o.m[3]=0,o.m[5]=2*r/i,o.m[4]=o.m[6]=o.m[7]=0,o.m[10]=-n/(r-n),o.m[8]=o.m[9]=0,o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(e,t,i,r,n,o){void 0===o&&(o=!0);var s=1/Math.tan(.5*e);o?n.m[0]=s/t:n.m[0]=s,n.m[1]=n.m[2]=n.m[3]=0,o?n.m[5]=s:n.m[5]=s*t,n.m[4]=n.m[6]=n.m[7]=0,n.m[8]=n.m[9]=0,n.m[10]=r/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(i*r)/(r-i)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(e,t,i,r,n,o){void 0===o&&(o=!0);var s=1/Math.tan(.5*e);o?n.m[0]=s/t:n.m[0]=s,n.m[1]=n.m[2]=n.m[3]=0,o?n.m[5]=s:n.m[5]=s*t,n.m[4]=n.m[6]=n.m[7]=0,n.m[8]=n.m[9]=0,n.m[10]=r/(i-r),n.m[11]=-1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!0);var o=Math.tan(e.upDegrees*Math.PI/180),s=Math.tan(e.downDegrees*Math.PI/180),a=Math.tan(e.leftDegrees*Math.PI/180),h=Math.tan(e.rightDegrees*Math.PI/180),c=2/(a+h),l=2/(o+s);r.m[0]=c,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=l,r.m[6]=r.m[7]=0,r.m[8]=(a-h)*c*.5,r.m[9]=-((o-s)*l*.5),r.m[10]=-i/(t-i),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=t*i/(t-i)},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,h=t.height,c=t.x,l=t.y,u=e.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,s-o,0,c+a/2,h/2+l,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,h=e.y*e.w,c=e.y*e.z,l=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(c+l),t.m[7]=0,t.m[8]=2*(a+h),t.m[9]=2*(c-l),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1},e._tempQuaternion=new h,e._xAxis=o.Zero(),e._yAxis=o.Zero(),e._zAxis=o.Zero(),e})();e.Matrix=c;var l=(function(){function e(e,t,i,r){this.normal=new o(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=c.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d,a=r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],h=r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],l=r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],u=r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15];return new e(a,h,l,u)},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,h=i.y-e.y,c=i.z-e.z,l=o*c-s*h,u=s*a-n*c,d=n*h-o*a,f=Math.sqrt(l*l+u*u+d*d);return r=0!==f?1/f:0,this.normal.x=l*r,this.normal.y=u*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){var i=o.Dot(this.normal,e);return i<=t},e.prototype.signedDistanceTo=function(e){return o.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return o.Dot(i,t)+r},e})();e.Plane=l;var u=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){return new e(this.x*t,this.y*i,this.width*t,this.height*i)},e})();e.Viewport=u;var d=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new l(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetPlanesToRef=function(e,t){t[0].normal.x=e.m[3]+e.m[2],t[0].normal.y=e.m[7]+e.m[6],t[0].normal.z=e.m[11]+e.m[10],t[0].d=e.m[15]+e.m[14],t[0].normalize(),t[1].normal.x=e.m[3]-e.m[2],t[1].normal.y=e.m[7]-e.m[6],t[1].normal.z=e.m[11]-e.m[10],t[1].d=e.m[15]-e.m[14],t[1].normalize(),t[2].normal.x=e.m[3]+e.m[0],t[2].normal.y=e.m[7]+e.m[4],t[2].normal.z=e.m[11]+e.m[8],t[2].d=e.m[15]+e.m[12],t[2].normalize(),t[3].normal.x=e.m[3]-e.m[0],t[3].normal.y=e.m[7]-e.m[4],t[3].normal.z=e.m[11]-e.m[8],t[3].d=e.m[15]-e.m[12],t[3].normalize(),t[4].normal.x=e.m[3]-e.m[1],t[4].normal.y=e.m[7]-e.m[5],t[4].normal.z=e.m[11]-e.m[9],t[4].d=e.m[15]-e.m[13],t[4].normalize(),t[5].normal.x=e.m[3]+e.m[1],t[5].normal.y=e.m[7]+e.m[5],t[5].normal.z=e.m[11]+e.m[9],t[5].d=e.m[15]+e.m[13],t[5].normalize()},e})();e.Frustum=d,(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD"})(e.Space||(e.Space={}));var f=(e.Space,(function(){function e(){}return e.X=new o(1,0,0),e.Y=new o(0,1,0),e.Z=new o(0,0,1),e})());e.Axis=f;var p=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,h=e,c=0;c<5;c++){var l=h*h,u=l*h,d=o*u+s*l+a*h,f=1/(3*o*l+2*s*h+a);h-=(d-e)*f,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*i+3*(1-h)*Math.pow(h,2)*n+Math.pow(h,3)},e})();e.BezierCurve=p,(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(e.Orientation||(e.Orientation={}));var m=e.Orientation,_=(function(){function e(e){var t=this;this.degrees=function(){return 180*t._radians/Math.PI},this.radians=function(){return t._radians},this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.BetweenTwoPoints=function(t,i){var r=i.subtract(t),n=Math.atan2(r.y,r.x);return new e(n)},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=_;var g=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var r=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,s=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new n((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=_.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),c=_.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=_.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-h>180&&(c-=360),c-h<-180&&(c+=360),l-c>180&&(l-=360),l-c<-180&&(l+=360),this.orientation=c-h<0?m.CW:m.CCW,this.angle=_.FromDegrees(this.orientation===m.CW?h-l:l-h)}return e})();e.Arc2=g;var v=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(e,t))}return e.prototype.addLineTo=function(e,t){if(closed)return this;var i=new n(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this},e.prototype.addArcTo=function(e,t,i,r,o){if(void 0===o&&(o=36),closed)return this;var s=this._points[this._points.length-1],a=new n(e,t),h=new n(i,r),c=new g(s,a,h),l=c.angle.radians()/o;c.orientation===m.CW&&(l*=-1);for(var u=c.startAngle.radians()+l,d=0;d<o;d++){var f=Math.cos(u)*c.radius+c.centerPoint.x,p=Math.sin(u)*c.radius+c.centerPoint.y;this.addLineTo(f,p),u+=l}return this},e.prototype.close=function(){return this.closed=!0,this},e.prototype.length=function(){var e=this._length;if(!this.closed){var t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e},e.prototype.getPoints=function(){return this._points},e.prototype.getPointAtLengthPosition=function(e){if(e<0||e>1)return n.Zero();for(var t=e*this.length(),i=0,r=0;r<this._points.length;r++){var o=(r+1)%this._points.length,s=this._points[r],a=this._points[o],h=a.subtract(s),c=h.length()+i;if(t>=i&&t<=c){var l=h.normalize(),u=t-i;return new n(s.x+l.x*u,s.y+l.y*u)}i=c}return n.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=v;var y=(function(){function i(e,t,i){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<e.length;r++)this._curve[r]=e[r].clone();this._raw=i||!1,this._compute(t)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(e,t){for(var i=0;i<e.length;i++)this._curve[i].x=e[i].x,this._curve[i].y=e[i].y,this._curve[i].z=e[i].z;return this._compute(t),this},i.prototype._compute=function(e){var t=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[t-1]=this._curve[t-1].subtract(this._curve[t-2]),this._raw||this._tangents[t-1].normalize();var i=this._tangents[0],r=this._normalVector(this._curve[0],i,e);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(i,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var n,s,a,h,c=1;c<t;c++)n=this._getLastNonNullVector(c),c<t-1&&(s=this._getFirstNonNullVector(c),this._tangents[c]=n.add(s),this._tangents[c].normalize()),this._distances[c]=this._distances[c-1]+n.length(),a=this._tangents[c],h=this._binormals[c-1],this._normals[c]=o.Cross(h,a),this._raw||this._normals[c].normalize(),this._binormals[c]=o.Cross(a,this._normals[c]),this._raw||this._binormals[c].normalize()},i.prototype._getFirstNonNullVector=function(e){for(var t=1,i=this._curve[e+t].subtract(this._curve[e]);0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i},i.prototype._getLastNonNullVector=function(e){for(var t=1,i=this._curve[e].subtract(this._curve[e-t]);0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},i.prototype._normalVector=function(i,r,n){var s,a=r.length();if(0===a&&(a=1),void 0===n||null===n){var h;t.WithinEpsilon(Math.abs(r.y)/a,1,e.Epsilon)?t.WithinEpsilon(Math.abs(r.x)/a,1,e.Epsilon)?t.WithinEpsilon(Math.abs(r.z)/a,1,e.Epsilon)||(h=new o(0,0,1)):h=new o(1,0,0):h=new o(0,(-1),0),s=o.Cross(r,h)}else s=o.Cross(r,n),o.CrossToRef(s,r,s);return s.normalize(),s},i})();e.Path3D=y;var x=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,n){n=n>2?n:3;for(var s=new Array,a=function(e,t,i,r){var n=(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;return n},h=0;h<=n;h++)s.push(new o(a(h/n,t.x,i.x,r.x),a(h/n,t.y,i.y,r.y),a(h/n,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,n,s){s=s>3?s:4;for(var a=new Array,h=function(e,t,i,r,n){var o=(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n;return o},c=0;c<=s;c++)a.push(new o(h(c/s,t.x,i.x,r.x,n.x),h(c/s,t.y,i.y,r.y,n.y),h(c/s,t.z,i.z,r.z,n.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,n,s){for(var a=new Array,h=1/s,c=0;c<=s;c++)a.push(o.Hermite(t,i,r,n,c*h));return new e(a)},e.prototype.getPoints=function(){return this._points},e.prototype.length=function(){return this._length},e.prototype["continue"]=function(t){for(var i=this._points[this._points.length-1],r=this._points.slice(),n=t.getPoints(),o=1;o<n.length;o++)r.push(n[o].subtract(n[0]).add(i));var s=new e(r);return s},e.prototype._computeLength=function(e){for(var t=0,i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t},e})();e.Curve3=x;var b=(function(){function e(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return e.prototype.addLight=function(e,t,i){var r=new o(t.r,t.g,t.b),n=r.scale(i);this.L00=this.L00.add(n.scale(.282095)),this.L1_1=this.L1_1.add(n.scale(.488603*e.y)),this.L10=this.L10.add(n.scale(.488603*e.z)),this.L11=this.L11.add(n.scale(.488603*e.x)),this.L2_2=this.L2_2.add(n.scale(1.092548*e.x*e.y)),this.L2_1=this.L2_1.add(n.scale(1.092548*e.y*e.z)),this.L21=this.L21.add(n.scale(1.092548*e.x*e.z)),this.L20=this.L20.add(n.scale(.315392*(3*e.z*e.z-1))),this.L22=this.L22.add(n.scale(.546274*(e.x*e.x-e.y*e.y)))},e.prototype.scale=function(e){this.L00=this.L00.scale(e),this.L1_1=this.L1_1.scale(e),this.L10=this.L10.scale(e),this.L11=this.L11.scale(e),this.L2_2=this.L2_2.scale(e),this.L2_1=this.L2_1.scale(e),this.L20=this.L20.scale(e),this.L21=this.L21.scale(e),this.L22=this.L22.scale(e)},e})();e.SphericalHarmonics=b;var T=(function(){function e(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return e.prototype.addAmbient=function(e){var t=new o(e.r,e.g,e.b);this.xx=this.xx.add(t),this.yy=this.yy.add(t),this.zz=this.zz.add(t)},e.getSphericalPolynomialFromHarmonics=function(t){var i=new e;return i.x=t.L11.scale(1.02333),i.y=t.L1_1.scale(1.02333),i.z=t.L10.scale(1.02333),i.xx=t.L00.scale(.886277).subtract(t.L20.scale(.247708)).add(t.L22.scale(.429043)),i.yy=t.L00.scale(.886277).subtract(t.L20.scale(.247708)).subtract(t.L22.scale(.429043)),i.zz=t.L00.scale(.886277).add(t.L20.scale(.495417)),i.yz=t.L2_1.scale(.858086),i.zx=t.L21.scale(.858086),i.xy=t.L2_2.scale(.858086),i},e})();e.SphericalPolynomial=T;var A=(function(){function e(e,t){void 0===e&&(e=o.Zero()),void 0===t&&(t=o.Up()),this.position=e,this.normal=t}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone())},e})();e.PositionNormalVertex=A;var E=(function(){function e(e,t,i){void 0===e&&(e=o.Zero()),void 0===t&&(t=o.Up()),void 0===i&&(i=n.Zero()),this.position=e,this.normal=t,this.uv=i}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone(),this.uv.clone())},e})();e.PositionNormalTextureVertex=E;var P=(function(){function e(){}return e.Color3=[i.Black(),i.Black(),i.Black()],e.Vector2=[n.Zero(),n.Zero(),n.Zero()],e.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],e.Vector4=[s.Zero(),s.Zero(),s.Zero()],e.Quaternion=[new h(0,0,0,0)],e.Matrix=[c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero()],e})();e.Tmp=P})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){function t(e,t){return function(i,r){i.__serializableMembers||(i.__serializableMembers={}),i.__serializableMembers[r]||(i.__serializableMembers[r]={type:e,sourceName:t})}}function i(e){return t(0,e)}function r(e){return t(1,e)}function n(e){return t(2,e)}function o(e){return t(3,e)}function s(e){return t(4,e)}function a(e){return t(5,e)}function h(e){return t(6,e)}function c(e){return t(7,e)}e.serialize=i,e.serializeAsTexture=r,e.serializeAsColor3=n,e.serializeAsFresnelParameters=o,e.serializeAsVector2=s,e.serializeAsVector3=a,e.serializeAsMeshReference=h,e.serializeAsColorCurves=c;var l=(function(){function t(){}return t.Serialize=function(t,i){i||(i={}),i.tags=e.Tags.GetTags(t);for(var r in t.__serializableMembers){var n=t.__serializableMembers[r],o=n.sourceName||r,s=n.type,a=t[r];if(void 0!==a&&null!==a)switch(s){case 0:i[o]=a;break;case 1:i[o]=a.serialize();break;case 2:i[o]=a.asArray();break;case 3:i[o]=a.serialize();break;case 4:i[o]=a.asArray();break;case 5:i[o]=a.asArray();break;case 6:i[o]=a.id;break;case 7:i[o]=a.serialize()}}return i},t.Parse=function(t,i,r,n){var o=t();e.Tags.AddTagsTo(o,i.tags);for(var s in o.__serializableMembers){var a=o.__serializableMembers[s],h=i[a.sourceName||s],c=a.type;if(void 0!==h&&null!==h)switch(c){case 0:o[s]=h;break;case 1:o[s]=e.Texture.Parse(h,r,n);break;case 2:o[s]=e.Color3.FromArray(h);break;case 3:o[s]=e.FresnelParameters.Parse(h);break;case 4:o[s]=e.Vector2.FromArray(h);break;case 5:o[s]=e.Vector3.FromArray(h);break;case 6:o[s]=r.getLastMeshByID(h);break;case 7:o[s]=e.ColorCurves.Parse(h)}}return o},t.Clone=function(t,i){var r=t();e.Tags.AddTagsTo(r,i.tags);for(var n in r.__serializableMembers){var o=r.__serializableMembers[n],s=i[n],a=o.type;if(void 0!==s&&null!==s)switch(a){case 0:case 6:r[n]=s;break;case 1:case 2:case 3:case 4:case 5:case 7:r[n]=s.clone()}}return r},t})();e.SerializationHelper=l})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t){void 0===t&&(t=!1),this.initalize(e,t)}return e.prototype.initalize=function(e,t){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this},e})();e.EventState=t;var i=(function(){function e(e,t){this.callback=e,this.mask=t}return e})();e.Observer=i;var r=(function(){function e(){this._observers=new Array,this._eventState=new t(0)}return e.prototype.add=function(e,t,r){if(void 0===t&&(t=-1),void 0===r&&(r=!1),!e)return null;var n=new i(e,t);return r?this._observers.unshift(n):this._observers.push(n),n},e.prototype.remove=function(e){var t=this._observers.indexOf(e);return t!==-1&&(this._observers.splice(t,1),!0)},e.prototype.removeCallback=function(e){for(var t=0;t<this._observers.length;t++)if(this._observers[t].callback===e)return this._observers.splice(t,1),!0;return!1},e.prototype.notifyObservers=function(e,t){void 0===t&&(t=-1);var i=this._eventState;i.mask=t,i.skipNextObservers=!1;for(var r=0,n=this._observers;r<n.length;r++){var o=n[r];if(o.mask&t&&o.callback(e,i),i.skipNextObservers)return!1}return!0},e.prototype.hasObservers=function(){return this._observers.length>0},e.prototype.clear=function(){this._observers=new Array},e.prototype.clone=function(){var t=new e;return t._observers=this._observers.slice(0),t},e})();e.Observable=r})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,i){this.idbFactory=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,this.callbackManifestChecked=i,this.currentSceneUrl=t.ReturnFullUrlLocation(e),this.db=null,this.enableSceneOffline=!1,this.enableTexturesOffline=!1,this.manifestVersionFound=0,this.mustUpdateRessources=!1,this.hasReachedQuota=!1,t.IDBStorageEnabled?this.checkManifestFile():this.callbackManifestChecked(!0)}return t.prototype.checkManifestFile=function(){function t(){r.enableSceneOffline=!1,r.enableTexturesOffline=!1,r.callbackManifestChecked(!1)}var i=this,r=this,n=!1,o=this.currentSceneUrl+".manifest",s=new XMLHttpRequest;navigator.onLine&&(n=!0,o=o+(null==o.match(/\?/)?"?":"&")+(new Date).getTime()),s.open("GET",o,!0),s.addEventListener("load",(function(){if(200===s.status||e.Tools.ValidateXHRData(s,1))try{var r=JSON.parse(s.response);i.enableSceneOffline=r.enableSceneOffline,i.enableTexturesOffline=r.enableTexturesOffline,r.version&&!isNaN(parseInt(r.version))&&(i.manifestVersionFound=r.version),i.callbackManifestChecked&&i.callbackManifestChecked(!0)}catch(n){t()}else t()}),!1),s.addEventListener("error",(function(e){if(n){n=!1;var r=i.currentSceneUrl+".manifest";s.open("GET",r,!0),s.send()}else t()}),!1);try{s.send()}catch(a){e.Tools.Error("Error on XHR send request."),r.callbackManifestChecked(!1)}},t.prototype.openAsync=function(t,i){function r(){o.isSupported=!1,i&&i()}var n=this,o=this;if(this.idbFactory&&(this.enableSceneOffline||this.enableTexturesOffline))if(this.db)t&&t();else{this.hasReachedQuota=!1,this.isSupported=!0;var s=this.idbFactory.open("babylonjs",1);s.onerror=function(e){r()},s.onblocked=function(t){e.Tools.Error("IDB request blocked. Please reload the page."),r()},s.onsuccess=function(e){n.db=s.result,t()},s.onupgradeneeded=function(t){n.db=t.target.result;try{n.db.createObjectStore("scenes",{keyPath:"sceneUrl"}),n.db.createObjectStore("versions",{keyPath:"sceneUrl"}),n.db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(i){e.Tools.Error("Error while creating object stores. Exception: "+i.message),r()}}}else this.isSupported=!1,i&&i()},t.prototype.loadImageFromDB=function(e,i){var r=this,n=t.ReturnFullUrlLocation(e),o=function(){r.hasReachedQuota||null===r.db?i.src=e:r._saveImageIntoDBAsync(n,i)};this.mustUpdateRessources?o():this._loadImageFromDBAsync(n,i,o)},t.prototype._loadImageFromDBAsync=function(t,i,r){if(this.isSupported&&null!==this.db){var n,o=this.db.transaction(["textures"]);o.onabort=function(e){i.src=t},o.oncomplete=function(o){var s;if(n){var a=window.URL||window.webkitURL;s=a.createObjectURL(n.data,{oneTimeOnly:!0}),i.onerror=function(){e.Tools.Error("Error loading image from blob URL: "+s+" switching back to web url: "+t),i.src=t},i.src=s}else r()};var s=o.objectStore("textures").get(t);s.onsuccess=function(e){n=e.target.result},s.onerror=function(r){e.Tools.Error("Error loading texture "+t+" from DB."),i.src=t}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i.src=t},t.prototype._saveImageIntoDBAsync=function(i,r){var n=this;if(this.isSupported){var o=function(){var e;if(s){var t=window.URL||window.webkitURL;try{e=t.createObjectURL(s,{oneTimeOnly:!0})}catch(i){e=t.createObjectURL(s)}}r.src=e};if(t.IsUASupportingBlobStorage){var s,a=new XMLHttpRequest;a.open("GET",i,!0),a.responseType="blob",a.addEventListener("load",(function(){if(200===a.status){s=a.response;var e=n.db.transaction(["textures"],"readwrite");e.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(n.hasReachedQuota=!0)}catch(t){}o()},e.oncomplete=function(e){o()};var h={textureUrl:i,data:s};try{var c=e.objectStore("textures").put(h);c.onsuccess=function(e){},c.onerror=function(e){o()}}catch(l){25===l.code&&(t.IsUASupportingBlobStorage=!1),r.src=i}}else r.src=i}),!1),a.addEventListener("error",(function(t){e.Tools.Error("Error in XHR request in BABYLON.Database."),r.src=i}),!1),a.send()}else r.src=i}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),
r.src=i},t.prototype._checkVersionFromDB=function(e,t){var i=this,r=function(r){i._saveVersionIntoDBAsync(e,t)};this._loadVersionFromDBAsync(e,t,r)},t.prototype._loadVersionFromDBAsync=function(t,i,r){var n=this;if(this.isSupported){var o;try{var s=this.db.transaction(["versions"]);s.oncomplete=function(e){o?n.manifestVersionFound>o.data?(n.mustUpdateRessources=!0,r()):i(o.data):(n.mustUpdateRessources=!0,r())},s.onabort=function(e){i(-1)};var a=s.objectStore("versions").get(t);a.onsuccess=function(e){o=e.target.result},a.onerror=function(r){e.Tools.Error("Error loading version for scene "+t+" from DB."),i(-1)}}catch(h){e.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: "+h.message),i(-1)}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i(-1)},t.prototype._saveVersionIntoDBAsync=function(t,i){var r=this;if(this.isSupported&&!this.hasReachedQuota)try{var n=this.db.transaction(["versions"],"readwrite");n.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(r.hasReachedQuota=!0)}catch(t){}i(-1)},n.oncomplete=function(e){i(r.manifestVersionFound)};var o={sceneUrl:t,data:this.manifestVersionFound},s=n.objectStore("versions").put(o);s.onsuccess=function(e){},s.onerror=function(t){e.Tools.Error("Error in DB add version request in BABYLON.Database.")}}catch(a){e.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+a.message),i(-1)}else i(-1)},t.prototype.loadFileFromDB=function(e,i,r,n,o){var s=this,a=t.ReturnFullUrlLocation(e),h=function(e){s._saveFileIntoDBAsync(a,i,r)};this._checkVersionFromDB(a,(function(e){e!==-1?s.mustUpdateRessources?s._saveFileIntoDBAsync(a,i,r,o):s._loadFileFromDBAsync(a,i,h,o):n()}))},t.prototype._loadFileFromDBAsync=function(t,i,r,n){if(this.isSupported){var o;o=t.indexOf(".babylon")!==-1?"scenes":"textures";var s,a=this.db.transaction([o]);a.oncomplete=function(e){s?i(s.data):r()},a.onabort=function(e){r()};var h=a.objectStore(o).get(t);h.onsuccess=function(e){s=e.target.result},h.onerror=function(i){e.Tools.Error("Error loading file "+t+" from DB."),r()}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.prototype._saveFileIntoDBAsync=function(t,i,r,n){var o=this;if(this.isSupported){var s;s=t.indexOf(".babylon")!==-1?"scenes":"textures";var a,h=new XMLHttpRequest;h.open("GET",t,!0),n&&(h.responseType="arraybuffer"),h.onprogress=r,h.addEventListener("load",(function(){if(200===h.status||e.Tools.ValidateXHRData(h,n?6:1))if(a=n?h.response:h.responseText,o.hasReachedQuota)i(a);else{var r=o.db.transaction([s],"readwrite");r.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(o.hasReachedQuota=!0)}catch(t){}i(a)},r.oncomplete=function(e){i(a)};var c;c="scenes"===s?{sceneUrl:t,data:a,version:o.manifestVersionFound}:{textureUrl:t,data:a};try{var l=r.objectStore(s).put(c);l.onsuccess=function(e){},l.onerror=function(t){e.Tools.Error("Error in DB add file request in BABYLON.Database.")}}catch(u){i(a)}}else i()}),!1),h.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),h.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t.parseURL=function(e){var t=document.createElement("a");t.href=e;var i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),n=e.substring(0,e.indexOf(r,0));return n},t.ReturnFullUrlLocation=function(e){return e.indexOf("http:/")===-1?t.parseURL(window.location.href)+e:e},t})();e.Database=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0,i={id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]};return i},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,h=!1,c=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:h=!0;break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:c=!0}var l,u,d=(15&o.flags,o.pixel_size>>3),f=o.width*o.height*d;if(a&&(u=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){l=new Uint8Array(f);for(var p,m,_,g=0,v=new Uint8Array(d);n<f&&g<f;)if(p=r[n++],m=(127&p)+1,128&p){for(_=0;_<d;++_)v[_]=r[n++];for(_=0;_<m;++_)l.set(v,g+_*d);g+=d*m}else{for(m*=d,_=0;_<m;++_)l[g+_]=r[n++];g+=m}}else l=r.subarray(n,n+=a?o.width*o.height:f);var y,x,b,T,A,E;switch((o.flags&t._ORIGIN_MASK)>>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:y=0,b=1,E=o.width,x=0,T=1,A=o.height;break;case t._ORIGIN_BL:y=0,b=1,E=o.width,x=o.height-1,T=-1,A=-1;break;case t._ORIGIN_UR:y=o.width-1,b=-1,E=-1,x=0,T=1,A=o.height;break;case t._ORIGIN_BR:y=o.width-1,b=-1,E=-1,x=o.height-1,T=-1,A=-1}var P="_getImageData"+(c?"Grey":"")+o.pixel_size+"bits",M=t[P](o,u,l,x,T,A,y,b,E);i.texImage2D(i.TEXTURE_2D,0,i.RGBA,o.width,o.height,0,i.RGBA,i.UNSIGNED_BYTE,M)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,d=i,f=t,p=e.width,m=e.height,_=0,g=new Uint8Array(p*m*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,_++)c=d[_],g[4*(l+p*u)+3]=255,g[4*(l+p*u)+2]=f[3*c+0],g[4*(l+p*u)+1]=f[3*c+1],g[4*(l+p*u)+0]=f[3*c+2];return g},t._getImageData16bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,d=i,f=e.width,p=e.height,m=0,_=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,m+=2)c=d[m+0]+(d[m+1]<<8),_[4*(l+f*u)+0]=(31744&c)>>7,_[4*(l+f*u)+1]=(992&c)>>2,_[4*(l+f*u)+2]=(31&c)>>3,_[4*(l+f*u)+3]=32768&c?0:255;return _},t._getImageData24bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,d=e.width,f=e.height,p=0,m=new Uint8Array(d*f*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=3)m[4*(c+d*l)+3]=255,m[4*(c+d*l)+2]=u[p+0],m[4*(c+d*l)+1]=u[p+1],m[4*(c+d*l)+0]=u[p+2];return m},t._getImageData32bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,d=e.width,f=e.height,p=0,m=new Uint8Array(d*f*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=4)m[4*(c+d*l)+2]=u[p+0],m[4*(c+d*l)+1]=u[p+1],m[4*(c+d*l)+0]=u[p+2],m[4*(c+d*l)+3]=u[p+3];return m},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,d=i,f=e.width,p=e.height,m=0,_=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,m++)c=d[m],_[4*(l+f*u)+0]=c,_[4*(l+f*u)+1]=c,_[4*(l+f*u)+2]=c,_[4*(l+f*u)+3]=255;return _},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,d=e.width,f=e.height,p=0,m=new Uint8Array(d*f*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=2)m[4*(c+d*l)+0]=u[p+0],m[4*(c+d*l)+1]=u[p+0],m[4*(c+d*l)+2]=u[p+0],m[4*(c+d*l)+3]=u[p+1];return m},t._TYPE_NO_DATA=0,t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();t.TGATools=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(t){this.length=0,this._duplicateId=0,this.data=new Array(t),this._id=e._GlobalId++}return e.prototype.push=function(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId},e.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},e.prototype.sort=function(e){this.data.sort(e)},e.prototype.reset=function(){this.length=0,this._duplicateId++},e.prototype.concat=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}},e.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++){var i=(e.data||e)[t];this.pushNoDuplicate(i)}}},e.prototype.indexOf=function(e){var t=this.data.indexOf(e);return t>=this.length?-1:t},e._GlobalId=0,e})();e.SmartArray=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._count=0,this._data={}}return e.prototype.copyFrom=function(e){var t=this;this.clear(),e.forEach((function(e,i){return t.add(e,i)}))},e.prototype.get=function(e){var t=this._data[e];if(void 0!==t)return t},e.prototype.getOrAddWithFactory=function(e,t){var i=this.get(e);return void 0!==i?i:(i=t(e),i&&this.add(e,i),i)},e.prototype.getOrAdd=function(e,t){var i=this.get(e);return void 0!==i?i:(this.add(e,t),t)},e.prototype.contains=function(e){return void 0!==this._data[e]},e.prototype.add=function(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)},e.prototype.set=function(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)},e.prototype.getAndRemove=function(e){var t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null},e.prototype.remove=function(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)},e.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(e.prototype,"count",{get:function(){return this._count},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e){for(var t in this._data){var i=this._data[t];e(t,i)}},e.prototype.first=function(e){for(var t in this._data){var i=this._data[t],r=e(t,i);if(r)return r}return null},e})();e.StringDictionary=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){function t(e,t){return function(i){i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}var i,r=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},n=(function(){function t(){}return t.Instantiate=function(e){for(var t=e.split("."),i=window||this,r=0,n=t.length;r<n;r++)i=i[t[r]];return"function"!=typeof i?null:i},t.SetImmediate=function(e){window.setImmediate?window.setImmediate(e):setTimeout(e,1)},t.IsExponentOfTwo=function(e){var t=1;do t*=2;while(t<e);return t===e},t.GetExponentOfTwo=function(e,t){var i=1;do i*=2;while(i<e);return i>t&&(i=t),i},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",l=0,u=new Uint8Array(e);l<u.length;)t=u[l++],i=l<u.length?u[l++]:Number.NaN,r=l<u.length?u[l++]:Number.NaN,n=t>>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),c+=h.charAt(n)+h.charAt(o)+h.charAt(s)+h.charAt(a);return"data:image/png;base64,"+c},t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null);for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE)),h=r;h<r+n;h++){var c=new e.Vector3(t[3*i[h]],t[3*i[h]+1],t[3*i[h]+2]);s=e.Vector3.Minimize(c,s),a=e.Vector3.Maximize(c,a)}return o&&(s.x-=s.x*o.x+o.y,s.y-=s.y*o.x+o.y,s.z-=s.z*o.x+o.y,a.x+=a.x*o.x+o.y,a.y+=a.y*o.x+o.y,a.z+=a.z*o.x+o.y),{minimum:s,maximum:a}},t.ExtractMinAndMax=function(t,i,r,n,o){void 0===n&&(n=null);var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE));o||(o=3);for(var h=i;h<i+r;h++){var c=new e.Vector3(t[h*o],t[h*o+1],t[h*o+2]);s=e.Vector3.Minimize(c,s),a=e.Vector3.Maximize(c,a)}return n&&(s.x-=s.x*n.x+n.y,s.y-=s.y*n.x+n.y,s.z-=s.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:s,maximum:a}},t.Vector2ArrayFeeder=function(t){return function(i){var r=void 0!==t.BYTES_PER_ELEMENT,n=r?t.length/2:t.length;if(i>=n)return null;if(r){var o=t;return new e.Vector2(o[2*i+0],o[2*i+1])}var s=t;return s[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2((-Number.MAX_VALUE),(-Number.MAX_VALUE)),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){if(t===!0||void 0!==e&&null!=e)return Array.isArray(e)?e:[e]},t.GetPointerPrefix=function(){var e="pointer";return window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,t){void 0===t&&(t=window),t.requestAnimationFrame?t.requestAnimationFrame(e):t.msRequestAnimationFrame?t.msRequestAnimationFrame(e):t.webkitRequestAnimationFrame?t.webkitRequestAnimationFrame(e):t.mozRequestAnimationFrame?t.mozRequestAnimationFrame(e):t.oRequestAnimationFrame?t.oRequestAnimationFrame(e):window.setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if(t.CorsBehavior)switch(typeof t.CorsBehavior){case"function":var r=t.CorsBehavior(e);if(r)return r;break;case"string":default:i.crossOrigin=t.CorsBehavior}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){i instanceof ArrayBuffer&&(i=t.EncodeArrayBufferTobase64(i)),i=t.CleanUrl(i);var s=new Image;"data:"!==i.substr(0,5)&&t.SetCorsBehavior(i,s),s.onload=function(){r(s)},s.onerror=function(e){t.Error("Error while trying to load texture: "+i),t.UseFallbackTexture?(s.src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",r(s)):n()};var a=function(){s.src=i},h=function(){o.loadImageFromDB(i,s)};if("data:"!==i.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(h,a);else if(i.indexOf("file:")===-1)a();else try{var c,l=i.substring(5).toLowerCase();try{c=URL.createObjectURL(e.FilesInput.FilesTextures[l],{oneTimeOnly:!0})}catch(u){c=URL.createObjectURL(e.FilesInput.FilesTextures[l])}s.src=c}catch(d){s.src=null}return s},t.LoadFile=function(i,r,n,o,s,a){i=t.CleanUrl(i);var h=function(){var e=new XMLHttpRequest,o=t.BaseUrl+i;e.open("GET",o,!0),s&&(e.responseType="arraybuffer"),e.onprogress=n,e.onreadystatechange=function(){if(4===e.readyState)if(e.onreadystatechange=null,e.status>=200&&e.status<300||navigator.isCocoonJS&&0===e.status)r(s?e.response:e.responseText);else{if(!a)throw new Error("Error status: "+e.status+" - Unable to load "+o);a()}},e.send(null)},c=function(){o.loadFileFromDB(i,r,n,h,s)};if(i.indexOf("file:")!==-1){var l=i.substring(5).toLowerCase();t.ReadFile(e.FilesInput.FilesToLoad[l],r,n,s)}else o&&o.enableSceneOffline?o.openAsync(c,h):h()},t.ReadFileAsDataURL=function(e,t,i){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onprogress=i,r.readAsDataURL(e)},t.ReadFile=function(e,i,r,n){var o=new FileReader;o.onerror=function(r){t.Log("Error while reading file: "+e.name),i(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},o.onload=function(e){i(e.target.result)},o.onprogress=r,n?o.readAsArrayBuffer(e):o.readAsText(e)},t.FileAsURL=function(e){var t=new Blob([e]),i=window.URL||window.webkitURL,r=i.createObjectURL(t);return r},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.x<t.x&&(t.x=e.x),e.y<t.y&&(t.y=e.y),e.z<t.z&&(t.z=e.z),e.x>i.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,n){for(var o in e)if(("_"!==o[0]||n&&n.indexOf(o)!==-1)&&(!i||i.indexOf(o)===-1)){var s=e[o],a=typeof s;if("function"!==a)if("object"===a)if(s instanceof Array){if(t[o]=[],s.length>0)if("object"==typeof s[0])for(var h=0;h<s.length;h++){var c=r(s[h],t);t[o].indexOf(c)===-1&&t[o].push(c)}else t[o]=s.slice(0)}else t[o]=r(s,t);else t[o]=s}},t.IsEmpty=function(e){for(var t in e)return!1;return!0},t.RegisterTopRootEvents=function(e){for(var t=0;t<e.length;t++){var i=e[t];window.addEventListener(i.name,i.handler,!1);try{window.parent&&window.parent.addEventListener(i.name,i.handler,!1)}catch(r){}}},t.UnregisterTopRootEvents=function(e){for(var t=0;t<e.length;t++){var i=e[t];window.removeEventListener(i.name,i.handler);try{window.parent&&window.parent.removeEventListener(i.name,i.handler)}catch(r){}}},t.DumpFramebuffer=function(e,r,n,o,s){void 0===s&&(s="image/png");for(var a=4*e,h=r/2,c=n.readPixels(0,0,e,r),l=0;l<h;l++)for(var u=0;u<a;u++){var d=u+l*a,f=r-l-1,p=u+f*a,m=c[d];c[d]=c[p],c[p]=m}i||(i=document.createElement("canvas")),i.width=e,i.height=r;var _=i.getContext("2d"),g=_.createImageData(e,r),v=g.data;v.set(c),_.putImageData(g,0,0),t.EncodeScreenshotCanvasData(o,s)},t.EncodeScreenshotCanvasData=function(e,t){void 0===t&&(t="image/png");var r=i.toDataURL(t);if(e)e(r);else if("download"in document.createElement("a")){var n=window.document.createElement("a");n.href=r;var o=new Date,s=(o.getFullYear()+"-"+(o.getMonth()+1)).slice(-2)+"-"+o.getDate()+"_"+o.getHours()+"-"+("0"+o.getMinutes()).slice(-2);n.setAttribute("download","screenshot_"+s+".png"),window.document.body.appendChild(n),n.addEventListener("click",(function(){n.parentElement.removeChild(n)})),n.click()}else{var a=window.open(""),h=a.document.createElement("img");h.src=r,a.document.body.appendChild(h)}},t.CreateScreenshot=function(e,r,n,o,s){void 0===s&&(s="image/png");var a,h;if(n.precision)a=Math.round(e.getRenderWidth()*n.precision),h=Math.round(a/e.getAspectRatio(r));else if(n.width&&n.height)a=n.width,h=n.height;else if(n.width&&!n.height)a=n.width,h=Math.round(a/e.getAspectRatio(r));else if(n.height&&!n.width)h=n.height,a=Math.round(h*e.getAspectRatio(r));else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");h=n,a=n}i||(i=document.createElement("canvas")),i.width=a,i.height=h;var c=i.getContext("2d");c.drawImage(e.getRenderingCanvas(),0,0,a,h),t.EncodeScreenshotCanvasData(o,s)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s){void 0===s&&(s="image/png");var a,h;if(n.precision)a=Math.round(i.getRenderWidth()*n.precision),h=Math.round(a/i.getAspectRatio(r)),n={width:a,height:h};else if(n.width&&n.height)a=n.width,h=n.height;else if(n.width&&!n.height)a=n.width,h=Math.round(a/i.getAspectRatio(r)),n={width:a,height:h};else if(n.height&&!n.width)h=n.height,a=Math.round(h*i.getAspectRatio(r)),n={width:a,height:h};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");h=n,a=n}var c=r.getScene(),l=null;c.activeCamera!==r&&(l=c.activeCamera,c.activeCamera=r);var u=new e.RenderTargetTexture("screenShot",n,c,(!1),(!1));u.renderList=c.meshes,u.onAfterRenderObservable.add((function(){t.DumpFramebuffer(a,h,i,o,s)})),c.incrementRenderId(),c.resetCachedMaterial(),u.render(!0),u.dispose(),l&&(c.activeCamera=l),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.Internals.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(o){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0,i="x"===e?t:3&t|8;return i.toString(16)}))},Object.defineProperty(t,"NoneLogLevel",{get:function(){return t._NoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MessageLogLevel",{get:function(){return t._MessageLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WarningLogLevel",{get:function(){return t._WarningLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ErrorLogLevel",{get:function(){return t._ErrorLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"AllLogLevel",{get:function(){return t._MessageLogLevel|t._WarningLogLevel|t._ErrorLogLevel},enumerable:!0,configurable:!0}),t._AddLogEntry=function(e){t._LogCache=e+t._LogCache,t.OnNewCacheEntry&&t.OnNewCacheEntry(e)},t._FormatMessage=function(e){var t=function(e){return e<10?"0"+e:""+e},i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e},t._LogDisabled=function(e){},t._LogEnabled=function(e){var i=t._FormatMessage(e);console.log("BJS - "+i);var r="<div style='color:white'>"+i+"</div><br>";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="<div style='color:orange'>"+i+"</div><br>";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="<div style='color:red'>"+i+"</div><br>";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return window.performance&&window.performance.now?window.performance.now():(new Date).getTime()},enumerable:!0,configurable:!0}),t.getClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i},t.first=function(e,t){for(var i=0,r=e;i<r.length;i++){var n=r[i];if(t(n))return n}},t.getFullClassName=function(e,t){void 0===t&&(t=!1);var i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,r=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null},t.arrayOrStringFeeder=function(e){return function(i){if(i>=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.BaseUrl="",t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t._performance=window.performance,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=n;var o=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(e,t){this._current+=e,t&&this._fetchResult()},e.prototype.beginMonitoring=function(){this._startMonitoringTime=n.Now},e.prototype.endMonitoring=function(e){void 0===e&&(e=!0),e&&this.fetchNewFrame();var t=n.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=n.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e})();e.PerfCounter=o,e.className=t;var s=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())},e.prototype.breakLoop=function(){this._done=!0,this._successCallback()},e.Run=function(t,i,r,n){void 0===n&&(n=0);var o=new e(t,i,r,n);return o.executeNext(),o},e.SyncAsyncForLoop=function(t,i,r,n,o,s){void 0===s&&(s=0),e.Run(Math.ceil(t/i),(function(e){o&&o()?e.breakLoop():setTimeout((function(){for(var n=0;n<i;++n){var s=e.index*i+n;if(s>=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._alphaBlend=!1,this._blendFunctionParameters=new Array(4),this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)},enumerable:!0,configurable:!0
}),e.prototype.setAlphaBlendFunctionParameters=function(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)},e.prototype.reset=function(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1))},e})();e._AlphaState=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,0)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1))},e})();e._DepthCullingState=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.reset()}return Object.defineProperty(t.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFunc",{get:function(){return this._stencilFunc},set:function(e){this._stencilFunc!==e&&(this._stencilFunc=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFuncRef",{get:function(){return this._stencilFuncRef},set:function(e){this._stencilFuncRef!==e&&(this._stencilFuncRef=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFuncMask",{get:function(){return this._stencilFuncMask},set:function(e){this._stencilFuncMask!==e&&(this._stencilFuncMask=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpStencilFail",{get:function(){return this._stencilOpStencilFail},set:function(e){this._stencilOpStencilFail!==e&&(this._stencilOpStencilFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpDepthFail",{get:function(){return this._stencilOpDepthFail},set:function(e){this._stencilOpDepthFail!==e&&(this._stencilOpDepthFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpStencilDepthPass",{get:function(){return this._stencilOpStencilDepthPass},set:function(e){this._stencilOpStencilDepthPass!==e&&(this._stencilOpStencilDepthPass=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilMask",{get:function(){return this._stencilMask},set:function(e){this._stencilMask!==e&&(this._stencilMask=e,this._isStencilMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilTest",{get:function(){return this._stencilTest},set:function(e){this._stencilTest!==e&&(this._stencilTest=e,this._isStencilTestDirty=!0)},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=e.Engine.ALWAYS,this._stencilFuncRef=1,this._stencilFuncMask=255,this._stencilOpStencilFail=e.Engine.KEEP,this._stencilOpDepthFail=e.Engine.KEEP,this._stencilOpStencilDepthPass=e.Engine.REPLACE,this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},t.prototype.apply=function(e){this.isDirty&&(this._isStencilTestDirty&&(this.stencilTest?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.stencilMask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.stencilFunc,this.stencilFuncRef,this.stencilFuncMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.stencilOpStencilFail,this.stencilOpDepthFail,this.stencilOpStencilDepthPass),this._isStencilOpDirty=!1))},t})();t._StencilState=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t,i,r){var n=e.createShader("vertex"===i?e.VERTEX_SHADER:e.FRAGMENT_SHADER);if(e.shaderSource(n,(r?r+"\n":"")+t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error(e.getShaderInfoLog(n));return n},i=36193,r=function(e,t){return t===l.TEXTURETYPE_FLOAT?e.FLOAT:t===l.TEXTURETYPE_HALF_FLOAT?i:e.UNSIGNED_BYTE},n=function(t,i,r){var n=r.NEAREST,o=r.NEAREST;return t===e.Texture.BILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=i?r.LINEAR_MIPMAP_NEAREST:r.LINEAR):t===e.Texture.TRILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=i?r.LINEAR_MIPMAP_LINEAR:r.LINEAR):t===e.Texture.NEAREST_SAMPLINGMODE&&(n=r.NEAREST,o=i?r.NEAREST_MIPMAP_LINEAR:r.NEAREST),{min:o,mag:n}},o=function(t,i,r,o,s,a,h,c,l,u){void 0===u&&(u=e.Texture.TRILINEAR_SAMPLINGMODE);var d=r.getEngine(),f=e.Tools.GetExponentOfTwo(o,d.getCaps().maxTextureSize),p=e.Tools.GetExponentOfTwo(s,d.getCaps().maxTextureSize);d._bindTextureDirectly(i.TEXTURE_2D,t),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,void 0===a?1:a?1:0),t._baseWidth=o,t._baseHeight=s,t._width=f,t._height=p,t.isReady=!0,l(f,p);var m=n(u,!h,i);i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,m.mag),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,m.min),h||c||i.generateMipmap(i.TEXTURE_2D),d._bindTextureDirectly(i.TEXTURE_2D,null),d.resetTextureCache(),r._removePendingData(t),t.onLoadedCallbacks.forEach((function(e){e()})),t.onLoadedCallbacks=[]},s=function(t,i,r,n,o,s){void 0===s&&(s=null);var a,h=function(){r[i]=a,r._internalCount++,n._removePendingData(a),6===r._internalCount&&o(r)},c=function(){n._removePendingData(a),s&&s()};a=e.Tools.LoadImage(t,h,c,n.database),n._addPendingData(a)},a=function(e,t,i,r,n){void 0===n&&(n=null);var o=[];o._internalCount=0;for(var a=0;a<6;a++)s(r[a],a,o,t,i,n)},h=(function(){function e(){}return e})();e.InstancingAttributeInfo=h;var c=(function(){function e(){}return e})();e.EngineCapabilities=c;var l=(function(){function s(t,i,r,n){var o=this;void 0===n&&(n=!0),this.isFullscreen=!1,this.isPointerLock=!1,this.cullBackFaces=!0,this.renderEvenInBackground=!0,this.enableOfflineSupport=!0,this.scenes=new Array,this._windowIsBackground=!1,this._webGLVersion="1.0",this._badOS=!1,this._drawCalls=new e.PerfCounter,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.fpsRange=60,this.previousFramesDuration=[],this.fps=60,this.deltaTime=0,this._depthCullingState=new e.Internals._DepthCullingState,this._stencilState=new e.Internals._StencilState,this._alphaState=new e.Internals._AlphaState,this._alphaMode=s.ALPHA_DISABLE,this._loadedTexturesCache=new Array,this._maxTextureChannels=16,this._activeTexturesCache=new Array(this._maxTextureChannels),this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentBufferPointers=[],this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._texturesSupported=new Array,this._onVRFullScreenTriggered=function(){if(o._vrDisplayEnabled&&o._vrDisplayEnabled.isPresenting){o._oldSize=new e.Size(o.getRenderWidth(),o.getRenderHeight()),o._oldHardwareScaleFactor=o.getHardwareScalingLevel();var t=o._vrDisplayEnabled.getEyeParameters("left");o.setHardwareScalingLevel(1),o.setSize(2*t.renderWidth,t.renderHeight)}else o.setHardwareScalingLevel(o._oldHardwareScaleFactor),o.setSize(o._oldSize.width,o._oldSize.height),o._vrDisplayEnabled=void 0},this._renderingCanvas=t,this._externalData=new e.StringDictionary,r=r||{},null!=i&&(r.antialias=i),void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1);var a=this._canRenderToFloatTexture(),h=this._canRenderToHalfFloatTexture();if(!this._gl){if(!t)throw new Error("The provided canvas is null or undefined.");try{this._gl=t.getContext("webgl",r)||t.getContext("experimental-webgl",r)}catch(l){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported");this._onBlur=function(){o._windowIsBackground=!0},this._onFocus=function(){o._windowIsBackground=!1},window.addEventListener("blur",this._onBlur),window.addEventListener("focus",this._onFocus);var u=r.limitDeviceRatio||window.devicePixelRatio||1;this._hardwareScalingLevel=n?1/Math.min(u,window.devicePixelRatio||1):1,this.resize(),this._isStencilEnable=r.stencil,this._caps=new c,this._caps.maxTexturesImageUnits=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),this._caps.maxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._caps.maxCubemapTextureSize=this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),this._caps.maxRenderTextureSize=this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),this._caps.maxVertexAttribs=this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),this._glVersion=this._gl.getParameter(this._gl.VERSION);var d=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=d&&(this._glRenderer=this._gl.getParameter(d.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(d.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor="Unknown vendor"),this._glRenderer||(this._glRenderer="Unknown renderer"),this._caps.standardDerivatives=null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureFloat=null!==this._gl.getExtension("OES_texture_float"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.instancedArrays=this._gl.getExtension("ANGLE_instanced_arrays"),this._caps.uintIndices=null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.drawBuffersExtension=this._gl.getExtension("WEBGL_draw_buffers"),this._caps.textureFloatLinearFiltering=this._gl.getExtension("OES_texture_float_linear"),this._caps.textureLOD=this._gl.getExtension("EXT_shader_texture_lod"),this._caps.textureFloatRender=a,this._caps.textureHalfFloat=null!==this._gl.getExtension("OES_texture_half_float"),this._caps.textureHalfFloatLinearFiltering=this._gl.getExtension("OES_texture_half_float_linear"),this._caps.textureHalfFloatRender=h,this._caps.astc&&this.texturesSupported.push(".astc"),this._caps.s3tc&&this.texturesSupported.push(".dds"),this._caps.pvrtc&&this.texturesSupported.push(".pvr"),this._caps.etc2&&this.texturesSupported.push(".etc2"),this._caps.etc1&&this.texturesSupported.push(".etc1"),this._gl.getShaderPrecisionFormat){var f=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);this._caps.highPrecisionShaderSupported=0!==f.precision}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._onFullscreenChange=function(){void 0!==document.fullscreen?o.isFullscreen=document.fullscreen:void 0!==document.mozFullScreen?o.isFullscreen=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o.isFullscreen=document.webkitIsFullScreen:void 0!==document.msIsFullScreen&&(o.isFullscreen=document.msIsFullScreen),o.isFullscreen&&o._pointerLockRequested&&(t.requestPointerLock=t.requestPointerLock||t.msRequestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock&&t.requestPointerLock())},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=function(){o.isPointerLock=document.mozPointerLockElement===t||document.webkitPointerLockElement===t||document.msPointerLockElement===t||document.pointerLockElement===t},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("mspointerlockchange",this._onPointerLockChange,!1),document.addEventListener("mozpointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1),e.AudioEngine&&!s.audioEngine&&(s.audioEngine=new e.AudioEngine),this._loadingScreen=new e.DefaultLoadingScreen(this._renderingCanvas),r.autoEnableWebVR&&this.initWebVR();var p=/AppleWebKit.*10.[\d] Mobile/;this._badOS=p.test(navigator.userAgent),e.Tools.Log("Babylon.js engine (v"+s.Version+") launched")}return Object.defineProperty(s,"NEVER",{get:function(){return s._NEVER},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALWAYS",{get:function(){return s._ALWAYS},enumerable:!0,configurable:!0}),Object.defineProperty(s,"LESS",{get:function(){return s._LESS},enumerable:!0,configurable:!0}),Object.defineProperty(s,"EQUAL",{get:function(){return s._EQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"LEQUAL",{get:function(){return s._LEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"GREATER",{get:function(){return s._GREATER},enumerable:!0,configurable:!0}),Object.defineProperty(s,"GEQUAL",{get:function(){return s._GEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"NOTEQUAL",{get:function(){return s._NOTEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"KEEP",{get:function(){return s._KEEP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"REPLACE",{get:function(){return s._REPLACE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INCR",{get:function(){return s._INCR},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DECR",{get:function(){return s._DECR},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INVERT",{get:function(){return s._INVERT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INCR_WRAP",{get:function(){return s._INCR_WRAP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DECR_WRAP",{get:function(){return s._DECR_WRAP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_DISABLE",{get:function(){return s._ALPHA_DISABLE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_ONEONE",{get:function(){return s._ALPHA_ONEONE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_ADD",{get:function(){return s._ALPHA_ADD},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_COMBINE",{get:function(){return s._ALPHA_COMBINE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_SUBTRACT",{get:function(){return s._ALPHA_SUBTRACT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_MULTIPLY",{get:function(){return s._ALPHA_MULTIPLY},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_MAXIMIZED",{get:function(){return s._ALPHA_MAXIMIZED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_NONE",{get:function(){return s._DELAYLOADSTATE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_LOADED",{get:function(){return s._DELAYLOADSTATE_LOADED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_LOADING",{get:function(){return s._DELAYLOADSTATE_LOADING},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_NOTLOADED",{get:function(){return s._DELAYLOADSTATE_NOTLOADED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_ALPHA",{get:function(){return s._TEXTUREFORMAT_ALPHA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_LUMINANCE",{get:function(){return s._TEXTUREFORMAT_LUMINANCE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_LUMINANCE_ALPHA",{get:function(){return s._TEXTUREFORMAT_LUMINANCE_ALPHA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_RGB",{get:function(){return s._TEXTUREFORMAT_RGB},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_RGBA",{get:function(){return s._TEXTUREFORMAT_RGBA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_UNSIGNED_INT",{get:function(){return s._TEXTURETYPE_UNSIGNED_INT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_FLOAT",{get:function(){return s._TEXTURETYPE_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_HALF_FLOAT",{get:function(){return s._TEXTURETYPE_HALF_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"Version",{get:function(){return"2.5"},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"webGLVersion",{get:function(){return this._webGLVersion},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"isStencilEnable",{get:function(){return this._isStencilEnable},enumerable:!0,configurable:!0}),s.prototype._prepareWorkingCanvas=function(){this._workingCanvas||(this._workingCanvas=document.createElement("canvas"),this._workingContext=this._workingCanvas.getContext("2d"))},s.prototype.resetTextureCache=function(){for(var e=0;e<this._maxTextureChannels;e++)this._activeTexturesCache[e]=null},s.prototype.getGlInfo=function(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}},s.prototype.getAspectRatio=function(e,t){void 0===t&&(t=!1);var i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},s.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget._width:this._renderingCanvas.width},s.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget._height:this._renderingCanvas.height},s.prototype.getRenderingCanvas=function(){return this._renderingCanvas},s.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas.getBoundingClientRect()},s.prototype.setHardwareScalingLevel=function(e){this._hardwareScalingLevel=e,this.resize()},s.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel},s.prototype.getLoadedTexturesCache=function(){return this._loadedTexturesCache},s.prototype.getCaps=function(){return this._caps},Object.defineProperty(s.prototype,"drawCalls",{get:function(){return this._drawCalls.current},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"drawCallsPerfCounter",{get:function(){return this._drawCalls},enumerable:!0,configurable:!0}),s.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},s.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},s.prototype.setDepthFunctionToGreater=function(){this._depthCullingState.depthFunc=this._gl.GREATER},s.prototype.setDepthFunctionToGreaterOrEqual=function(){this._depthCullingState.depthFunc=this._gl.GEQUAL},s.prototype.setDepthFunctionToLess=function(){this._depthCullingState.depthFunc=this._gl.LESS},s.prototype.setDepthFunctionToLessOrEqual=function(){this._depthCullingState.depthFunc=this._gl.LEQUAL},s.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},s.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},s.prototype.getStencilMask=function(){return this._stencilState.stencilMask},s.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},s.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},s.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},s.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},s.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},s.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},s.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},s.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},s.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},s.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},s.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},s.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},s.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},s.prototype.stopRenderLoop=function(e){if(!e)return void(this._activeRenderLoops=[]);var t=this._activeRenderLoops.indexOf(e);t>=0&&this._activeRenderLoops.splice(t,1)},s.prototype._renderLoop=function(){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i<this._activeRenderLoops.length;i++){var r=this._activeRenderLoops[i];r()}this.endFrame()}this._activeRenderLoops.length>0?e.Tools.QueueNewFrame(this._bindedRenderFunction,this._vrDisplayEnabled):this._renderingQueueLaunched=!1},s.prototype.runRenderLoop=function(t){this._activeRenderLoops.indexOf(t)===-1&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),e.Tools.QueueNewFrame(this._bindedRenderFunction)))},s.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,e.Tools.RequestFullscreen(this._renderingCanvas))},s.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},s.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),s===!0?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},s.prototype.setViewport=function(e,t,i){var r=t||(navigator.isCocoonJS?window.innerWidth:this._renderingCanvas.width),n=i||(navigator.isCocoonJS?window.innerHeight:this._renderingCanvas.height),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._gl.viewport(o*r,s*n,r*e.width,n*e.height)},s.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._gl.viewport(e,t,i,r),n},s.prototype.beginFrame=function(){this._measureFps()},s.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplayEnabled&&this._vrDisplayEnabled.isPresenting&&this._vrDisplayEnabled.submitFrame()},s.prototype.resize=function(){var t=navigator.isCocoonJS?window.innerWidth:this._renderingCanvas.clientWidth,i=navigator.isCocoonJS?window.innerHeight:this._renderingCanvas.clientHeight;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel);for(var r=0;r<this.scenes.length;r++){var n=this.scenes[r];e.DebugLayer&&n.debugLayer.isVisible()&&n.debugLayer._syncPositions()}},s.prototype.setSize=function(e,t){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i<this.scenes.length;i++)for(var r=this.scenes[i],n=0;n<r.cameras.length;n++){var o=r.cameras[n];o._currentRenderId=0}},s.prototype.initWebVR=function(){this.vrDisplaysPromise||this._getVRDisplays()},s.prototype.enableVR=function(e){this._vrDisplayEnabled=e,this._vrDisplayEnabled.requestPresent([{source:this.getRenderingCanvas()}]).then(this._onVRFullScreenTriggered)},s.prototype.disableVR=function(){this._vrDisplayEnabled&&this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered)},s.prototype._getVRDisplays=function(){var e=this,t=function(t){var i=(t.length,0);return e._vrDisplays=t.filter((function(e){return t[i]instanceof VRDisplay})),e._vrDisplays};navigator.getVRDisplays&&(this.vrDisplaysPromise=navigator.getVRDisplays().then(t))},s.prototype.bindFramebuffer=function(e,t,i,r){this._currentRenderTarget=e,this.bindUnboundFramebuffer(e._framebuffer);var n=this._gl;e.isCube&&n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0),n.viewport(0,0,i||e._width,r||e._height),this.wipeCaches()},s.prototype.bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)},s.prototype.unBindFramebuffer=function(e,t){if(void 0===t&&(t=!1),this._currentRenderTarget=null,e.generateMipMaps&&!t){var i=this._gl;this._bindTextureDirectly(i.TEXTURE_2D,e),i.generateMipmap(i.TEXTURE_2D),this._bindTextureDirectly(i.TEXTURE_2D,null)}this.bindUnboundFramebuffer(null)},s.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){var t=this._gl;this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,e),t.generateMipmap(t.TEXTURE_CUBE_MAP),this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)}},s.prototype.flushFramebuffer=function(){this._gl.flush()},s.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget=null,this.bindUnboundFramebuffer(null),this.setViewport(this._cachedViewport),this.wipeCaches()},s.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},s.prototype.createVertexBuffer=function(e){var t=this._gl.createBuffer();return this.bindArrayBuffer(t),e instanceof Float32Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this._resetVertexBufferBinding(),t.references=1,t},s.prototype.createDynamicVertexBuffer=function(e){var t=this._gl.createBuffer();return this.bindArrayBuffer(t),e instanceof Float32Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this._resetVertexBufferBinding(),t.references=1,t},s.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this._resetVertexBufferBinding()},s.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},s.prototype.createIndexBuffer=function(e){var t=this._gl.createBuffer();this.bindIndexBuffer(t);var i,r=!1;if(this._caps.uintIndices){for(var n=0;n<e.length;n++)if(e[n]>65535){r=!0;break}i=r?new Uint32Array(e):new Uint16Array(e)}else i=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),t.references=1,t.is32Bits=r,t},s.prototype.bindArrayBuffer=function(e){this.bindBuffer(e,this._gl.ARRAY_BUFFER)},s.prototype.bindIndexBuffer=function(e){this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},s.prototype.bindBuffer=function(e,t){this._currentBoundBuffer[t]!==e&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},s.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},s.prototype.vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],h=!1;a?(a.buffer!==e&&(a.buffer=e,h=!0),a.size!==i&&(a.size=i,h=!0),a.type!==r&&(a.type=r,h=!0),a.normalized!==n&&(a.normalized=n,h=!0),a.stride!==o&&(a.stride=o,h=!0),a.offset!==s&&(a.offset=s,h=!0)):(h=!0,this._currentBufferPointers[t]={indx:t,size:i,type:r,normalized:n,stride:o,offset:s,buffer:e}),h&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},s.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;for(var o=n.getAttributesCount(),s=0,a=0;a<o;a++)if(a<i.length){var h=n.getAttributeLocation(a);h>=0&&(this._vertexAttribArraysEnabled[h]||(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0),this.vertexAttribPointer(e,h,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}else{var h=n.getAttributeLocation(a);this._vertexAttribArraysEnabled[h]&&(this._gl.disableVertexAttribArray(h),
this._vertexAttribArraysEnabled[h]=!1)}}this._cachedIndexBuffer!==t&&(this._cachedIndexBuffer=t,this.bindIndexBuffer(t),this._uintIndicesCurrentlySet=t.is32Bits)},s.prototype.bindBuffers=function(e,t,i){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i;for(var r=i.getAttributesNames(),n=0;n<r.length;n++){var o=i.getAttributeLocation(n);if(o>=0){var s=e[r[n]];if(!s){this._vertexAttribArraysEnabled[o]&&(this._gl.disableVertexAttribArray(o),this._vertexAttribArraysEnabled[o]=!1);continue}this._vertexAttribArraysEnabled[o]||(this._gl.enableVertexAttribArray(o),this._vertexAttribArraysEnabled[o]=!0);var a=s.getBuffer();this.vertexAttribPointer(a,o,s.getSize(),this._gl.FLOAT,!1,4*s.getStrideSize(),4*s.getOffset()),s.getIsInstanced()&&(this._caps.instancedArrays.vertexAttribDivisorANGLE(o,1),this._currentInstanceLocations.push(o),this._currentInstanceBuffers.push(a))}}}null!=t&&this._cachedIndexBuffer!==t&&(this._cachedIndexBuffer=t,this.bindIndexBuffer(t),this._uintIndicesCurrentlySet=t.is32Bits)},s.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t<i;t++){var r=this._currentInstanceBuffers[t];e!=r&&(e=r,this.bindArrayBuffer(r));var n=this._currentInstanceLocations[t];this._caps.instancedArrays.vertexAttribDivisorANGLE(n,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0},s.prototype._releaseBuffer=function(e){return e.references--,0===e.references&&(this._gl.deleteBuffer(e),!0)},s.prototype.createInstancesBuffer=function(e){var t=this._gl.createBuffer();return t.capacity=e,this.bindArrayBuffer(t),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),t},s.prototype.deleteInstancesBuffer=function(e){this._gl.deleteBuffer(e)},s.prototype.updateAndBindInstancesBuffer=function(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index){for(var r=0,n=0;n<i.length;n++){var o=i[n];r+=4*o.attributeSize}for(var n=0;n<i.length;n++){var o=i[n];this._vertexAttribArraysEnabled[o.index]||(this._gl.enableVertexAttribArray(o.index),this._vertexAttribArraysEnabled[o.index]=!0),this.vertexAttribPointer(e,o.index,o.attributeSize,o.attribyteType||this._gl.FLOAT,o.normalized||!1,r,o.offset),this._caps.instancedArrays.vertexAttribDivisorANGLE(o.index,1),this._currentInstanceLocations.push(o.index),this._currentInstanceBuffers.push(e)}}else for(var s=0;s<4;s++){var a=i[s];this._vertexAttribArraysEnabled[a]||(this._gl.enableVertexAttribArray(a),this._vertexAttribArraysEnabled[a]=!0),this.vertexAttribPointer(e,a,4,this._gl.FLOAT,!1,64,16*s),this._caps.instancedArrays.vertexAttribDivisorANGLE(a,1),this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(e)}},s.prototype.applyStates=function(){this._depthCullingState.apply(this._gl),this._stencilState.apply(this._gl),this._alphaState.apply(this._gl)},s.prototype.draw=function(e,t,i,r){this.applyStates(),this._drawCalls.addCount(1,!1);var n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,o=this._uintIndicesCurrentlySet?4:2;return r?void this._caps.instancedArrays.drawElementsInstancedANGLE(e?this._gl.TRIANGLES:this._gl.LINES,i,n,t*o,r):void this._gl.drawElements(e?this._gl.TRIANGLES:this._gl.LINES,i,n,t*o)},s.prototype.drawPointClouds=function(e,t,i){return this.applyStates(),this._drawCalls.addCount(1,!1),i?void this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS,e,t,i):void this._gl.drawArrays(this._gl.POINTS,e,t)},s.prototype.drawUnIndexed=function(e,t,i,r){return this.applyStates(),this._drawCalls.addCount(1,!1),r?void this._caps.instancedArrays.drawArraysInstancedANGLE(e?this._gl.TRIANGLES:this._gl.LINES,t,i,r):void this._gl.drawArrays(e?this._gl.TRIANGLES:this._gl.LINES,t,i)},s.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],e.getProgram()&&this._gl.deleteProgram(e.getProgram()))},s.prototype.createEffect=function(t,i,r,n,o,s,a,h,c){var l=t.vertexElement||t.vertex||t,u=t.fragmentElement||t.fragment||t,d=l+"+"+u+"@"+o;if(this._compiledEffects[d])return this._compiledEffects[d];var f=new e.Effect(t,i,r,n,this,o,s,a,h,c);return f._key=d,this._compiledEffects[d]=f,f},s.prototype.createEffectForParticles=function(e,t,i,r,n,o,s){return void 0===t&&(t=[]),void 0===i&&(i=[]),void 0===r&&(r=""),this.createEffect({vertex:"particles",fragmentElement:e},["position","color","options"],["view","projection"].concat(t),["diffuseSampler"].concat(i),r,n,o,s)},s.prototype.createShaderProgram=function(e,i,r,n){n=n||this._gl;var o=t(n,e,"vertex",r),s=t(n,i,"fragment",r),a=n.createProgram();n.attachShader(a,o),n.attachShader(a,s),n.linkProgram(a);var h=n.getProgramParameter(a,n.LINK_STATUS);if(!h){var c=n.getProgramInfoLog(a);if(c)throw new Error(c)}return n.deleteShader(o),n.deleteShader(s),a},s.prototype.getUniforms=function(e,t){for(var i=[],r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(e,t[r]));return i},s.prototype.getAttributes=function(e,t){for(var i=[],r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(e,t[r]))}catch(n){i.push(-1)}return i},s.prototype.enableEffect=function(e){this.setProgram(e.getProgram()),this._currentEffect=e,e.onBind&&e.onBind(e)},s.prototype.setIntArray=function(e,t){e&&this._gl.uniform1iv(e,t)},s.prototype.setIntArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2iv(e,t)},s.prototype.setIntArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3iv(e,t)},s.prototype.setIntArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4iv(e,t)},s.prototype.setFloatArray=function(e,t){e&&this._gl.uniform1fv(e,t)},s.prototype.setFloatArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2fv(e,t)},s.prototype.setFloatArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3fv(e,t)},s.prototype.setFloatArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4fv(e,t)},s.prototype.setArray=function(e,t){e&&this._gl.uniform1fv(e,t)},s.prototype.setArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2fv(e,t)},s.prototype.setArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3fv(e,t)},s.prototype.setArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4fv(e,t)},s.prototype.setMatrices=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t)},s.prototype.setMatrix=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t.toArray())},s.prototype.setMatrix3x3=function(e,t){e&&this._gl.uniformMatrix3fv(e,!1,t)},s.prototype.setMatrix2x2=function(e,t){e&&this._gl.uniformMatrix2fv(e,!1,t)},s.prototype.setFloat=function(e,t){e&&this._gl.uniform1f(e,t)},s.prototype.setFloat2=function(e,t,i){e&&this._gl.uniform2f(e,t,i)},s.prototype.setFloat3=function(e,t,i,r){e&&this._gl.uniform3f(e,t,i,r)},s.prototype.setBool=function(e,t){e&&this._gl.uniform1i(e,t)},s.prototype.setFloat4=function(e,t,i,r,n){e&&this._gl.uniform4f(e,t,i,r,n)},s.prototype.setColor3=function(e,t){e&&this._gl.uniform3f(e,t.r,t.g,t.b)},s.prototype.setColor4=function(e,t,i){e&&this._gl.uniform4f(e,t.r,t.g,t.b,i)},s.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1);var n=r?this._gl.FRONT:this._gl.BACK,o=r?this._gl.BACK:this._gl.FRONT,s=this.cullBackFaces?n:o;(this._depthCullingState.cull!==e||i||this._depthCullingState.cullFace!==s)&&(e?(this._depthCullingState.cullFace=s,this._depthCullingState.cull=!0):this._depthCullingState.cull=!1),this._depthCullingState.zOffset=t},s.prototype.setDepthBuffer=function(e){this._depthCullingState.depthTest=e},s.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},s.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},s.prototype.setColorWrite=function(e){this._gl.colorMask(e,e,e,e)},s.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode!==e){switch(e){case s.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case s.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0}t||this.setDepthWrite(e===s.ALPHA_DISABLE),this._alphaMode=e}},s.prototype.getAlphaMode=function(){return this._alphaMode},s.prototype.setAlphaTesting=function(e){this._alphaTest=e},s.prototype.getAlphaTesting=function(){return this._alphaTest},s.prototype.wipeCaches=function(){this.resetTextureCache(),this._currentEffect=null,this._stencilState.reset(),this._depthCullingState.reset(),this.setDepthFunctionToLessOrEqual(),this._alphaState.reset(),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null},s.prototype.setSamplingMode=function(t,i){var r=this._gl;this._bindTextureDirectly(r.TEXTURE_2D,t);var n=r.NEAREST,o=r.NEAREST;i===e.Texture.BILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=r.LINEAR):i===e.Texture.TRILINEAR_SAMPLINGMODE&&(n=r.LINEAR,o=r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,o),this._bindTextureDirectly(r.TEXTURE_2D,null),t.samplingMode=i},s.prototype.setTextureFormatToUse=function(e){for(var t=0,i=this.texturesSupported.length;t<i;t++)if(".astc"!==this._texturesSupported[t]&&".pvr"!==this._texturesSupported[t]&&".etc1"!==this._texturesSupported[t]&&".etc2"!==this._texturesSupported[t])for(var r=0,n=e.length;r<n;r++)if(this._texturesSupported[t]===e[r].toLowerCase())return this._textureFormatInUse=this._texturesSupported[t];return this._textureFormatInUse=null},s.prototype.createTexture=function(t,i,r,n,s,a,h,c){var l=this;void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===h&&(h=null),void 0===c&&(c=null);var u,d=this._gl.createTexture(),f=!1;if("data:"===t.substr(0,5)&&(f=!0),f){var p=t;f=p.split(":"),t=p,u=f[1].substr(f[1].length-4,4).toLowerCase()}else{var m=t.lastIndexOf(".");u=t.substring(m).toLowerCase(),!this._textureFormatInUse||f||n.database||(u=this._textureFormatInUse,t=t.substring(0,m)+this._textureFormatInUse)}var _=".dds"===u,g=".tga"===u;n._addPendingData(d),d.url=t,d.noMipmap=i,d.references=1,d.samplingMode=s,d.onLoadedCallbacks=[a],this._loadedTexturesCache.push(d);var v,y=function(){n._removePendingData(d),h&&h()};if(g)v=function(t){var a=new Uint8Array(t),h=e.Internals.TGATools.GetTGAHeader(a);o(d,l._gl,n,h.width,h.height,r,i,!1,(function(){e.Internals.TGATools.UploadContent(l._gl,a)}),s)},f instanceof Array?v(c):e.Tools.LoadFile(t,(function(e){v(e)}),null,n.database,!0,y);else if(_)v=function(t){var a=e.Internals.DDSTools.GetDDSInfo(t),h=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&!i&&a.width>>a.mipmapCount-1===1;o(d,l._gl,n,a.width,a.height,r,!h,a.isFourCC,(function(){e.Internals.DDSTools.UploadDDSLevels(l._gl,l.getCaps().s3tc,t,a,h,1)}),s)},f instanceof Array?v(c):e.Tools.LoadFile(t,(function(e){v(e)}),null,n.database,!0,y);else{var x=function(t){o(d,l._gl,n,t.width,t.height,r,i,!1,(function(i,r){var n=t.width===i&&t.height===r;n||(l._prepareWorkingCanvas(),l._workingCanvas.width=i,l._workingCanvas.height=r,s===e.Texture.NEAREST_SAMPLINGMODE&&(l._workingContext.imageSmoothingEnabled=!1,l._workingContext.mozImageSmoothingEnabled=!1,l._workingContext.oImageSmoothingEnabled=!1,l._workingContext.webkitImageSmoothingEnabled=!1,l._workingContext.msImageSmoothingEnabled=!1),l._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s===e.Texture.NEAREST_SAMPLINGMODE&&(l._workingContext.imageSmoothingEnabled=!0,l._workingContext.mozImageSmoothingEnabled=!0,l._workingContext.oImageSmoothingEnabled=!0,l._workingContext.webkitImageSmoothingEnabled=!0,l._workingContext.msImageSmoothingEnabled=!0)),l._gl.texImage2D(l._gl.TEXTURE_2D,0,l._gl.RGBA,l._gl.RGBA,l._gl.UNSIGNED_BYTE,n?t:l._workingCanvas)}),s)};f instanceof Array?e.Tools.LoadImage(c,x,y,n.database):e.Tools.LoadImage(t,x,y,n.database)}return d},s.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case s.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case s.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case s.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case s.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case s.TEXTUREFORMAT_RGBA:t=this._gl.RGBA}return t},s.prototype.updateRawTexture=function(e,t,i,r,n){void 0===n&&(n=null);var o=this._getInternalFormat(i);this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,void 0===r?1:r?1:0),e._width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[n],e._width,e._height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e._width,e._height,0,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this.resetTextureCache(),e.isReady=!0},s.prototype.createRawTexture=function(e,t,i,r,o,s,a,h){void 0===h&&(h=null);var c=this._gl.createTexture();c._baseWidth=t,c._baseHeight=i,c._width=t,c._height=i,c.references=1,this.updateRawTexture(c,e,r,s,h),this._bindTextureDirectly(this._gl.TEXTURE_2D,c);var l=n(a,o,this._gl);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,l.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,l.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),c.samplingMode=a,this._loadedTexturesCache.push(c),c},s.prototype.createDynamicTexture=function(t,i,r,n){var o=this._gl.createTexture();return o._baseWidth=t,o._baseHeight=i,r&&(t=e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize),i=e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize)),this.resetTextureCache(),o._width=t,o._height=i,o.isReady=!1,o.generateMipMaps=r,o.references=1,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._loadedTexturesCache.push(o),o},s.prototype.updateTextureSamplingMode=function(e,t){var i=n(e,t.generateMipMaps,this._gl);t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null))},s.prototype.updateDynamicTexture=function(e,t,i,r){void 0===r&&(r=!1),this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?1:0),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this.resetTextureCache(),e.isReady=!0},s.prototype.updateVideoTexture=function(e,t,i){if(!e._isDisabled){this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?0:1);try{void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported?this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t):(e._workingCanvas||(e._workingCanvas=document.createElement("canvas"),e._workingContext=e._workingCanvas.getContext("2d"),e._workingCanvas.width=e._width,e._workingCanvas.height=e._height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e._width,e._height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this.resetTextureCache(),e.isReady=!0}catch(r){e._isDisabled=!0}}},s.prototype.createRenderTargetTexture=function(t,i){var o=!1,a=!0,h=!1,c=s.TEXTURETYPE_UNSIGNED_INT,l=e.Texture.TRILINEAR_SAMPLINGMODE;void 0!==i&&(o=void 0===i.generateMipMaps?i:i.generateMipMaps,a=void 0===i.generateDepthBuffer||i.generateDepthBuffer,h=a&&i.generateStencilBuffer,c=void 0===i.type?c:i.type,void 0!==i.samplingMode&&(l=i.samplingMode),c!==s.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?c!==s.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(l=e.Texture.NEAREST_SAMPLINGMODE):l=e.Texture.NEAREST_SAMPLINGMODE);var u=this._gl,d=u.createTexture();this._bindTextureDirectly(u.TEXTURE_2D,d);var f=t.width||t,p=t.height||t,m=n(l,o,u);c!==s.TEXTURETYPE_FLOAT||this._caps.textureFloat||(c=s.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,m.mag),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,m.min),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,f,p,0,u.RGBA,r(u,c),null);var _;h?(_=u.createRenderbuffer(),u.bindRenderbuffer(u.RENDERBUFFER,_),u.renderbufferStorage(u.RENDERBUFFER,u.DEPTH_STENCIL,f,p)):a&&(_=u.createRenderbuffer(),u.bindRenderbuffer(u.RENDERBUFFER,_),u.renderbufferStorage(u.RENDERBUFFER,u.DEPTH_COMPONENT16,f,p));var g=u.createFramebuffer();return this.bindUnboundFramebuffer(g),h?u.framebufferRenderbuffer(u.FRAMEBUFFER,u.DEPTH_STENCIL_ATTACHMENT,u.RENDERBUFFER,_):a&&u.framebufferRenderbuffer(u.FRAMEBUFFER,u.DEPTH_ATTACHMENT,u.RENDERBUFFER,_),u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,d,0),o&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(u.TEXTURE_2D,null),u.bindRenderbuffer(u.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),d._framebuffer=g,a&&(d._depthBuffer=_),d._baseWidth=f,d._baseHeight=p,d._width=f,d._height=p,d.isReady=!0,d.generateMipMaps=o,d.references=1,d.samplingMode=l,d.type=c,this.resetTextureCache(),this._loadedTexturesCache.push(d),d},s.prototype.createRenderTargetCubeTexture=function(t,i){var r=this._gl,o=r.createTexture(),s=!0,a=!0,h=!1,c=e.Texture.TRILINEAR_SAMPLINGMODE;void 0!==i&&(s=void 0===i.generateMipMaps?i:i.generateMipMaps,a=void 0===i.generateDepthBuffer||i.generateDepthBuffer,h=a&&i.generateStencilBuffer,void 0!==i.samplingMode&&(c=i.samplingMode)),o.isCube=!0,o.references=1,o.generateMipMaps=s,o.references=1,o.samplingMode=c;var l=n(c,s,r);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,o);for(var u=0;u<6;u++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+u,0,r.RGBA,t,t,0,r.RGBA,r.UNSIGNED_BYTE,null);r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,l.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,l.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);var d;h?(d=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,d),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,t)):a&&(d=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,d),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT16,t,t));var f=r.createFramebuffer();return this.bindUnboundFramebuffer(f),h?r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,d):a&&r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,d),o.generateMipMaps&&(this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,o),r.generateMipmap(r.TEXTURE_CUBE_MAP)),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),r.bindRenderbuffer(r.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),o._framebuffer=f,a&&(o._depthBuffer=d),o._width=t,o._height=t,o.isReady=!0,this.resetTextureCache(),this._loadedTexturesCache.push(o),o},s.prototype.createCubeTexture=function(t,i,r,n,o,s){var h=this;void 0===o&&(o=null),void 0===s&&(s=null);var c=this._gl,l=c.createTexture();l.isCube=!0,l.url=t,l.references=1,l.onLoadedCallbacks=[];var u=t.substr(t.length-4,4).toLowerCase(),d=this.getCaps().s3tc&&".dds"===u;return d?e.Tools.LoadFile(t,(function(t){var i=e.Internals.DDSTools.GetDDSInfo(t),r=(i.isRGB||i.isLuminance||i.mipmapCount>1)&&!n;h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l),c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,1),e.Internals.DDSTools.UploadDDSLevels(h._gl,h.getCaps().s3tc,t,i,r,6),n||i.isFourCC||1!==i.mipmapCount||c.generateMipmap(c.TEXTURE_CUBE_MAP),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,r?c.LINEAR_MIPMAP_LINEAR:c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),h.resetTextureCache(),l._width=i.width,l._height=i.height,l.isReady=!0}),null,null,!0,s):a(t,i,(function(t){var i=e.Tools.GetExponentOfTwo(t[0].width,h._caps.maxCubemapTextureSize),r=i;h._prepareWorkingCanvas(),h._workingCanvas.width=i,h._workingCanvas.height=r;var s=[c.TEXTURE_CUBE_MAP_POSITIVE_X,c.TEXTURE_CUBE_MAP_POSITIVE_Y,c.TEXTURE_CUBE_MAP_POSITIVE_Z,c.TEXTURE_CUBE_MAP_NEGATIVE_X,c.TEXTURE_CUBE_MAP_NEGATIVE_Y,c.TEXTURE_CUBE_MAP_NEGATIVE_Z];h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l),c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,0);for(var a=0;a<s.length;a++)h._workingContext.drawImage(t[a],0,0,t[a].width,t[a].height,0,0,i,r),c.texImage2D(s[a],0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,h._workingCanvas);n||c.generateMipmap(c.TEXTURE_CUBE_MAP),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,n?c.LINEAR:c.LINEAR_MIPMAP_LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),h.resetTextureCache(),l._width=i,l._height=r,l.isReady=!0,l.onLoadedCallbacks.forEach((function(e){e()})),o&&o()}),r,s),this._loadedTexturesCache.push(l),l},s.prototype.updateTextureSize=function(e,t,i){e._width=t,e._height=i,e._size=t*i,e._baseWidth=t,e._baseHeight=i},s.prototype.createRawCubeTexture=function(t,r,n,o,a,h,c,l){var u=this,d=this._gl,f=d.createTexture();r._addPendingData(f),f.isCube=!0,f.references=1,f.url=t;var p=this._getInternalFormat(o),m=d.UNSIGNED_BYTE;a===s.TEXTURETYPE_FLOAT&&(m=d.FLOAT);var _=n,g=_,v=e.Tools.IsExponentOfTwo(_)&&e.Tools.IsExponentOfTwo(g);f._width=_,f._height=g;var y=function(){r._removePendingData(f)},x=function(t){var n=c(t),o=[d.TEXTURE_CUBE_MAP_POSITIVE_X,d.TEXTURE_CUBE_MAP_POSITIVE_Y,d.TEXTURE_CUBE_MAP_POSITIVE_Z,d.TEXTURE_CUBE_MAP_NEGATIVE_X,d.TEXTURE_CUBE_MAP_NEGATIVE_Y,d.TEXTURE_CUBE_MAP_NEGATIVE_Z];if(_=f._width,g=f._height,v=e.Tools.IsExponentOfTwo(_)&&e.Tools.IsExponentOfTwo(g),u._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f),d.pixelStorei(d.UNPACK_FLIP_Y_WEBGL,0),!h&&v)if(l){var s=[];s.push(n[0]),s.push(n[3]),s.push(n[1]),s.push(n[4]),s.push(n[2]),s.push(n[5]);for(var a=l(s),y=0;y<a.length;y++){var x=_>>y;d.texImage2D(o[0],y,p,x,x,0,p,m,a[y][0]),d.texImage2D(o[1],y,p,x,x,0,p,m,a[y][2]),d.texImage2D(o[2],y,p,x,x,0,p,m,a[y][4]),d.texImage2D(o[3],y,p,x,x,0,p,m,a[y][1]),d.texImage2D(o[4],y,p,x,x,0,p,m,a[y][3]),d.texImage2D(o[5],y,p,x,x,0,p,m,a[y][5])}}else{for(var b=0;b<o.length;b++){var T=n[b];d.texImage2D(o[b],0,p,_,g,0,p,m,T)}if(d.generateMipmap(d.TEXTURE_CUBE_MAP),m===d.FLOAT&&p===d.RGB&&1282===d.getError()){e.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");for(var b=0;b<o.length;b++){for(var T=n[b],A=new Float32Array(_*g*4),E=0;E<_;E++)for(var P=0;P<g;P++){var M=3*(P*_+E),S=4*(P*_+E);A[S+0]=T[M+0],A[S+1]=T[M+1],A[S+2]=T[M+2],A[S+3]=1}d.texImage2D(o[b],0,d.RGBA,_,g,0,d.RGBA,m,A)}d.generateMipmap(d.TEXTURE_CUBE_MAP)}}else h=!0;(m!==d.FLOAT||u._caps.textureFloatLinearFiltering)&&(m!==i||u._caps.textureHalfFloatLinearFiltering)?(d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MAG_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MIN_FILTER,h?d.LINEAR:d.LINEAR_MIPMAP_LINEAR)):(d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MIN_FILTER,d.NEAREST)),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),u._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null),f.isReady=!0,u.resetTextureCache(),r._removePendingData(f)};return e.Tools.LoadFile(t,(function(e){x(e)}),y,r.database,!0),f},s.prototype._releaseTexture=function(e){var t=this._gl;e._framebuffer&&t.deleteFramebuffer(e._framebuffer),e._depthBuffer&&t.deleteRenderbuffer(e._depthBuffer),t.deleteTexture(e),this.unbindAllTextures();var i=this._loadedTexturesCache.indexOf(e);i!==-1&&this._loadedTexturesCache.splice(i,1)},s.prototype.setProgram=function(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)},s.prototype.bindSamplers=function(e){this.setProgram(e.getProgram());for(var t=e.getSamplers(),i=0;i<t.length;i++){var r=e.getUniform(t[i]);this._gl.uniform1i(r,i)}this._currentEffect=null},s.prototype.activateTexture=function(e){this._activeTexture!==e&&(this._gl.activeTexture(e),this._activeTexture=e)},s.prototype._bindTextureDirectly=function(e,t){this._activeTexturesCache[this._activeTexture]!==t&&(this._gl.bindTexture(e,t),this._activeTexturesCache[this._activeTexture]=t)},s.prototype._bindTexture=function(e,t){e<0||(this.activateTexture(this._gl["TEXTURE"+e]),this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},s.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t._textures.data[t._currentRenderTextureInd])},s.prototype.unbindAllTextures=function(){for(var e=0;e<this._caps.maxTexturesImageUnits;e++)this.activateTexture(this._gl["TEXTURE"+e]),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)},s.prototype.setTexture=function(e,t,i){e<0||(this._gl.uniform1i(t,e),this._setTexture(e,i))},s.prototype._setTexture=function(t,i){if(!i||!i.isReady())return void(null!=this._activeTexturesCache[t]&&(this.activateTexture(this._gl["TEXTURE"+t]),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)));var r=!1;if(i instanceof e.VideoTexture)this.activateTexture(this._gl["TEXTURE"+t]),r=!0,i.update();else if(i.delayLoadState===s.DELAYLOADSTATE_NOTLOADED)return void i.delayLoad();var n=i.getInternalTexture();if(this._activeTexturesCache[t]!==n)if(r||this.activateTexture(this._gl["TEXTURE"+t]),n.isCube){if(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,n),n._cachedCoordinatesMode!==i.coordinatesMode){n._cachedCoordinatesMode=i.coordinatesMode;var o=i.coordinatesMode!==e.Texture.CUBIC_MODE&&i.coordinatesMode!==e.Texture.SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,o),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,o)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,i)}else{if(this._bindTextureDirectly(this._gl.TEXTURE_2D,n),n._cachedWrapU!==i.wrapU)switch(n._cachedWrapU=i.wrapU,i.wrapU){case e.Texture.WRAP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.REPEAT);break;case e.Texture.CLAMP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE);break;case e.Texture.MIRROR_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.MIRRORED_REPEAT)}if(n._cachedWrapV!==i.wrapV)switch(n._cachedWrapV=i.wrapV,i.wrapV){case e.Texture.WRAP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.REPEAT);break;case e.Texture.CLAMP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);break;case e.Texture.MIRROR_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.MIRRORED_REPEAT)}this._setAnisotropicLevel(this._gl.TEXTURE_2D,i)}},s.prototype.setTextureArray=function(e,t,i){if(!(e<0)){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r<i.length;r++)this._textureUnits[r]=e+r;this._gl.uniform1iv(t,this._textureUnits);for(var n=0;n<i.length;n++)this._setTexture(e+n,i[n])}},s.prototype._setAnisotropicLevel=function(t,i){var r=this._caps.textureAnisotropicFilterExtension,n=i.anisotropicFilteringLevel;i.getInternalTexture().samplingMode===e.Texture.NEAREST_SAMPLINGMODE&&(n=1),r&&i._cachedAnisotropicFilteringLevel!==n&&(this._gl.texParameterf(t,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n,this._caps.maxAnisotropy)),i._cachedAnisotropicFilteringLevel=n)},s.prototype.readPixels=function(e,t,i,r){var n=new Uint8Array(r*i*4);return this._gl.readPixels(e,t,i,r,this._gl.RGBA,this._gl.UNSIGNED_BYTE,n),n},s.prototype.addExternalData=function(e,t){return this._externalData.add(e,t)},s.prototype.getExternalData=function(e){return this._externalData.get(e)},s.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData.getOrAddWithFactory(e,t)},s.prototype.removeExternalData=function(e){return this._externalData.remove(e)},s.prototype.releaseInternalTexture=function(e){if(e&&(e.references--,0===e.references)){var t=this.getLoadedTexturesCache(),i=t.indexOf(e);i>-1&&t.splice(i,1),this._releaseTexture(e)}},s.prototype.unbindAllAttributes=function(){for(var e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1)},s.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.scenes.length;)this.scenes[0].dispose();s.audioEngine.dispose();for(var e in this._compiledEffects)this._gl.deleteProgram(this._compiledEffects[e]._program);this.unbindAllAttributes(),this._gl=null,this.disableVR(),window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)},s.prototype.displayLoadingUI=function(){this._loadingScreen.displayLoadingUI()},s.prototype.hideLoadingUI=function(){this._loadingScreen.hideLoadingUI()},Object.defineProperty(s.prototype,"loadingScreen",{get:function(){return this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"loadingUIText",{set:function(e){this._loadingScreen.loadingUIText=e;
},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"loadingUIBackgroundColor",{set:function(e){this._loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),s.prototype.attachContextLostEvent=function(e){this._renderingCanvas.addEventListener("webglcontextlost",e,!1)},s.prototype.attachContextRestoredEvent=function(e){this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)},s.prototype.getVertexShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return this._gl.getShaderSource(t[0])},s.prototype.getFragmentShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return this._gl.getShaderSource(t[1])},s.prototype.getFps=function(){return this.fps},s.prototype.getDeltaTime=function(){return this.deltaTime},s.prototype._measureFps=function(){this.previousFramesDuration.push(e.Tools.Now);var t=this.previousFramesDuration.length;if(t>=2&&(this.deltaTime=this.previousFramesDuration[t-1]-this.previousFramesDuration[t-2]),t>=this.fpsRange){t>this.fpsRange&&(this.previousFramesDuration.splice(0,1),t=this.previousFramesDuration.length);for(var i=0,r=0;r<t-1;r++)i+=this.previousFramesDuration[r+1]-this.previousFramesDuration[r];this.fps=1e3/(i/(t-1))}},s.prototype._canRenderToFloatTexture=function(){return this._canRenderToTextureOfType(e.Engine.TEXTURETYPE_FLOAT,"OES_texture_float")},s.prototype._canRenderToHalfFloatTexture=function(){return this._canRenderToTextureOfType(e.Engine.TEXTURETYPE_HALF_FLOAT,"OES_texture_half_float")},s.prototype._canRenderToTextureOfType=function(t,i){var n=document.createElement("canvas");n.height=16,n.width=16;var o=n.getContext("webgl")||n.getContext("experimental-webgl"),s=o.getExtension(i);if(!s)return!1;var a="attribute vec4 a_position;\n                void main() {\n                    gl_Position = a_position;\n                }",h="precision mediump float;\n                uniform vec4 u_color;\n                uniform sampler2D u_texture;\n\n                void main() {\n                    gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n                }",c=this.createShaderProgram(a,h,null,o);o.useProgram(c);var l=o.getAttribLocation(c,"a_position"),u=o.getUniformLocation(c,"u_color"),d=o.createBuffer();o.bindBuffer(o.ARRAY_BUFFER,d),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),o.STATIC_DRAW),o.enableVertexAttribArray(l),o.vertexAttribPointer(l,2,o.FLOAT,!1,0,0);var f=o.createTexture();o.bindTexture(o.TEXTURE_2D,f),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));var p=o.createTexture();o.bindTexture(o.TEXTURE_2D,p),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,r(o,t),null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST);var m=o.createFramebuffer();o.bindFramebuffer(o.FRAMEBUFFER,m),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,p,0);var _=function(){o.deleteProgram(c),o.disableVertexAttribArray(l),o.deleteBuffer(d),o.deleteFramebuffer(m),o.deleteTexture(f),o.deleteTexture(p)},g=o.checkFramebufferStatus(o.FRAMEBUFFER);if(g!==o.FRAMEBUFFER_COMPLETE)return e.Tools.Log("GL Support: can **NOT** render to "+t+" texture"),_(),!1;o.bindTexture(o.TEXTURE_2D,f),o.uniform4fv(u,[0,10,20,1]),o.drawArrays(o.TRIANGLES,0,6),o.bindTexture(o.TEXTURE_2D,p),o.bindFramebuffer(o.FRAMEBUFFER,null),o.clearColor(1,0,0,1),o.clear(o.COLOR_BUFFER_BIT),o.uniform4fv(u,[0,.1,.05,1]),o.drawArrays(o.TRIANGLES,0,6);var v=new Uint8Array(4);return o.readPixels(0,0,1,1,o.RGBA,o.UNSIGNED_BYTE,v),0!==v[0]||v[1]<248||v[2]<248||v[3]<254?(e.Tools.Log("GL Support: Was not able to actually render to "+t+" texture"),_(),!1):(_(),!0)},s.isSupported=function(){try{if(navigator.isCocoonJS)return!0;var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");return null!=t&&!!window.WebGLRenderingContext}catch(i){return!1}},s._ALPHA_DISABLE=0,s._ALPHA_ADD=1,s._ALPHA_COMBINE=2,s._ALPHA_SUBTRACT=3,s._ALPHA_MULTIPLY=4,s._ALPHA_MAXIMIZED=5,s._ALPHA_ONEONE=6,s._DELAYLOADSTATE_NONE=0,s._DELAYLOADSTATE_LOADED=1,s._DELAYLOADSTATE_LOADING=2,s._DELAYLOADSTATE_NOTLOADED=4,s._TEXTUREFORMAT_ALPHA=0,s._TEXTUREFORMAT_LUMINANCE=1,s._TEXTUREFORMAT_LUMINANCE_ALPHA=2,s._TEXTUREFORMAT_RGB=4,s._TEXTUREFORMAT_RGBA=5,s._TEXTURETYPE_UNSIGNED_INT=0,s._TEXTURETYPE_FLOAT=1,s._TEXTURETYPE_HALF_FLOAT=2,s._NEVER=512,s._ALWAYS=519,s._LESS=513,s._EQUAL=514,s._LEQUAL=515,s._GREATER=516,s._GEQUAL=518,s._NOTEQUAL=517,s._KEEP=7680,s._REPLACE=7681,s._INCR=7682,s._DECR=7683,s._INVERT=5386,s._INCR_WRAP=34055,s._DECR_WRAP=34056,s.CollisionsEpsilon=.001,s.CodeRepository="src/",s.ShadersRepository="src/Shaders/",s})();e.Engine=l})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.state="",this.metadata=null,this.doNotSerialize=!1,this.animations=new Array,this._ranges={},this._childrenFlag=-1,this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this.onDisposeObservable=new e.Observable,this.name=t,this.id=t,this._scene=i,this._initCache()}return Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode){var t=this._parentNode._children.indexOf(this);t!==-1&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.getWorldMatrix=function(){return e.Matrix.Identity()},t.prototype._initCache=function(){this._cache={},this._cache.parent=void 0},t.prototype.updateCache=function(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())},t.prototype._updateCache=function(e){},t.prototype._isSynchronized=function(){return!0},t.prototype._markSyncedWithParent=function(){this._parentRenderId=this.parent._currentRenderId},t.prototype.isSynchronizedWithParent=function(){return!this.parent||this._parentRenderId===this.parent._currentRenderId&&this.parent.isSynchronized()},t.prototype.isSynchronized=function(e){var t=this.hasNewParent();return t=t||!this.isSynchronizedWithParent(),t=t||!this._isSynchronized(),e&&this.updateCache(!0),!t},t.prototype.hasNewParent=function(e){return this._cache.parent!==this.parent&&(e&&(this._cache.parent=this.parent),!0)},t.prototype.isReady=function(){return this._isReady},t.prototype.isEnabled=function(){return!!this._isEnabled&&(!this.parent||this.parent.isEnabled())},t.prototype.setEnabled=function(e){this._isEnabled=e},t.prototype.isDescendantOf=function(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))},t.prototype._getDescendants=function(e,t,i){if(void 0===t&&(t=!1),this._children)for(var r=0;r<this._children.length;r++){var n=this._children[r];i&&!i(n)||e.push(n),t||n._getDescendants(e,!1,i)}},t.prototype.getDescendants=function(e,t){var i=[];return this._getDescendants(i,e,t),i},t.prototype.getChildren=function(e){return this.getDescendants(!0,e)},t.prototype.getChildMeshes=function(t,i){var r=[];return this._getDescendants(r,t,(function(t){return(!i||i(t))&&t instanceof e.AbstractMesh})),r},t.prototype._setReady=function(e){if(e!==this._isReady){if(!e)return void(this._isReady=!1);this._isReady=!0,this.onReady&&this.onReady(this)}},t.prototype.getAnimationByName=function(e){for(var t=0;t<this.animations.length;t++){var i=this.animations[t];if(i.name===e)return i}return null},t.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=new e.AnimationRange(t,i,r);for(var n=0,o=this.animations.length;n<o;n++)this.animations[n]&&this.animations[n].createRange(t,i,r)}},t.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=void 0},t.prototype.getAnimationRange=function(e){return this._ranges[e]},t.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?void this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},t.prototype.serializeAnimationRanges=function(){var e=[];for(var t in this._ranges){var i={};i.name=t,i.from=this._ranges[t].from,i.to=this._ranges[t].to,e.push(i)}return e},t.prototype.dispose=function(){this.parent=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.ParseAnimationRanges=function(e,t,i){if(t.ranges)for(var r=0;r<t.ranges.length;r++){var n=t.ranges[r];e.createAnimationRange(n.name,n.from,n.to)}},__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"id",void 0),__decorate([e.serialize()],t.prototype,"uniqueId",void 0),__decorate([e.serialize()],t.prototype,"state",void 0),__decorate([e.serialize()],t.prototype,"metadata",void 0),t})();e.Node=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o,s,a){this._engine=e,this._canvas=i,this._currentScene=t,this._sceneLoadedCallback=r,this._progressCallback=n,this._additionnalRenderLoopLogicCallback=o,this._textureLoadingCallback=s,this._startingProcessingFilesCallback=a}return t.prototype.monitorElementForDragNDrop=function(e){var t=this;e&&(this._elementToMonitor=e,this._elementToMonitor.addEventListener("dragenter",(function(e){t.drag(e)}),!1),this._elementToMonitor.addEventListener("dragover",(function(e){t.drag(e)}),!1),this._elementToMonitor.addEventListener("drop",(function(e){t.drop(e)}),!1))},t.prototype.renderFunction=function(){if(this._additionnalRenderLoopLogicCallback&&this._additionnalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){var e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype.loadFiles=function(e){if(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(),e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&this._filesToLoad.length>0){for(var i=0;i<this._filesToLoad.length;i++)switch(this._filesToLoad[i].type){case"image/jpeg":case"image/png":case"image/bmp":t.FilesTextures[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i];break;case"image/targa":case"image/vnd.ms-dds":case"audio/wav":case"audio/x-wav":case"audio/mp3":case"audio/mpeg":case"audio/mpeg3":case"audio/x-mpeg-3":case"audio/ogg":t.FilesToLoad[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i];break;default:this._filesToLoad[i].name.indexOf(".mtl")!==-1?t.FilesToLoad[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i]:this._filesToLoad[i].name.indexOf(".babylon")===-1&&this._filesToLoad[i].name.indexOf(".stl")===-1&&this._filesToLoad[i].name.indexOf(".obj")===-1||this._filesToLoad[i].name.indexOf(".manifest")!==-1||this._filesToLoad[i].name.indexOf(".incremental")!==-1||this._filesToLoad[i].name.indexOf(".babylonmeshdata")!==-1||this._filesToLoad[i].name.indexOf(".babylongeometrydata")!==-1||this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata")!==-1||this._filesToLoad[i].name.indexOf(".binary.babylon")!==-1||(this._sceneFileToLoad=this._filesToLoad[i])}this.reload()}},t.prototype.reload=function(){var t=this,i=this;this._sceneFileToLoad?(this._currentScene&&(e.Tools.errorsCount>0&&(e.Tools.ClearLogCache(),e.Tools.Log("Babylon.js engine (v"+e.Engine.Version+") launched")),this._engine.stopRenderLoop(),this._currentScene.dispose()),e.SceneLoader.Load("file:",this._sceneFileToLoad,this._engine,(function(e){i._currentScene=e,i._currentScene.executeWhenReady((function(){i._currentScene.activeCamera&&0!==i._currentScene.lights.length||i._currentScene.createDefaultCameraOrLight(),i._currentScene.activeCamera.attachControl(i._canvas),i._sceneLoadedCallback&&i._sceneLoadedCallback(t._sceneFileToLoad,i._currentScene),i._engine.runRenderLoop((function(){i.renderFunction()}))}))}),(function(e){t._progressCallback&&t._progressCallback(e)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesTextures=new Array,t.FilesToLoad=new Array,t})();e.FilesInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}return e})();e.IntersectionInfo=t;var i=(function(){function t(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshId=0,this.pickedSprite=null}return t.prototype.getNormal=function(t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!0),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e.VertexBuffer.NormalKind))return null;var r,n=this.pickedMesh.getIndices();if(i){var o=this.pickedMesh.getVerticesData(e.VertexBuffer.NormalKind),s=e.Vector3.FromArray(o,3*n[3*this.faceId]),a=e.Vector3.FromArray(o,3*n[3*this.faceId+1]),h=e.Vector3.FromArray(o,3*n[3*this.faceId+2]);s=s.scale(this.bu),a=a.scale(this.bv),h=h.scale(1-this.bu-this.bv),r=new e.Vector3(s.x+a.x+h.x,s.y+a.y+h.y,s.z+a.z+h.z)}else{var c=this.pickedMesh.getVerticesData(e.VertexBuffer.PositionKind),l=e.Vector3.FromArray(c,3*n[3*this.faceId]),u=e.Vector3.FromArray(c,3*n[3*this.faceId+1]),d=e.Vector3.FromArray(c,3*n[3*this.faceId+2]),f=l.subtract(u),p=d.subtract(u);r=e.Vector3.Cross(f,p)}return t&&(r=e.Vector3.TransformNormal(r,this.pickedMesh.getWorldMatrix())),e.Vector3.Normalize(r)},t.prototype.getTextureCoordinates=function(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e.VertexBuffer.UVKind))return null;var t=this.pickedMesh.getIndices(),i=this.pickedMesh.getVerticesData(e.VertexBuffer.UVKind),r=e.Vector2.FromArray(i,2*t[3*this.faceId]),n=e.Vector2.FromArray(i,2*t[3*this.faceId+1]),o=e.Vector2.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(1-this.bu-this.bv),n=n.scale(this.bu),o=o.scale(this.bv),new e.Vector2(r.x+n.x+o.x,r.y+n.y+o.y)},t})();e.PickingInfo=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._tempRadiusVector=e.Vector3.Zero();var r=e.Vector3.Distance(t,i);this.center=e.Vector3.Lerp(t,i,.5),this.radius=.5*r,this.centerWorld=e.Vector3.Zero(),this._update(e.Matrix.Identity())}return t.prototype._update=function(t){e.Vector3.TransformCoordinatesToRef(this.center,t,this.centerWorld),e.Vector3.TransformNormalFromFloatsToRef(1,1,1,t,this._tempRadiusVector),this.radiusWorld=Math.max(Math.abs(this._tempRadiusVector.x),Math.abs(this._tempRadiusVector.y),Math.abs(this._tempRadiusVector.z))*this.radius},t.prototype.isInFrustum=function(e){for(var t=0;t<6;t++)if(e[t].dotCoordinate(this.centerWorld)<=-this.radiusWorld)return!1;return!0},t.prototype.intersectsPoint=function(t){var i=this.centerWorld.x-t.x,r=this.centerWorld.y-t.y,n=this.centerWorld.z-t.z,o=Math.sqrt(i*i+r*r+n*n);return!(Math.abs(this.radiusWorld-o)<e.Epsilon)},t.Intersects=function(e,t){var i=e.centerWorld.x-t.centerWorld.x,r=e.centerWorld.y-t.centerWorld.y,n=e.centerWorld.z-t.centerWorld.z,o=Math.sqrt(i*i+r*r+n*n);return!(e.radiusWorld+t.radiusWorld<o)},t})();e.BoundingSphere=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.minimum=t,this.maximum=i,this.vectors=new Array,this.vectorsWorld=new Array,this.vectors.push(this.minimum.clone()),this.vectors.push(this.maximum.clone()),this.vectors.push(this.minimum.clone()),this.vectors[2].x=this.maximum.x,this.vectors.push(this.minimum.clone()),this.vectors[3].y=this.maximum.y,this.vectors.push(this.minimum.clone()),this.vectors[4].z=this.maximum.z,this.vectors.push(this.maximum.clone()),this.vectors[5].z=this.minimum.z,this.vectors.push(this.maximum.clone()),this.vectors[6].x=this.minimum.x,this.vectors.push(this.maximum.clone()),this.vectors[7].y=this.minimum.y,this.center=this.maximum.add(this.minimum).scale(.5),this.extendSize=this.maximum.subtract(this.minimum).scale(.5),this.directions=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()];for(var r=0;r<this.vectors.length;r++)this.vectorsWorld[r]=e.Vector3.Zero();this.minimumWorld=e.Vector3.Zero(),this.maximumWorld=e.Vector3.Zero(),this._update(e.Matrix.Identity())}return t.prototype.getWorldMatrix=function(){return this._worldMatrix},t.prototype.setWorldMatrix=function(e){return this._worldMatrix.copyFrom(e),this},t.prototype._update=function(t){e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this.minimumWorld),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this.maximumWorld);for(var i=0;i<this.vectors.length;i++){var r=this.vectorsWorld[i];e.Vector3.TransformCoordinatesToRef(this.vectors[i],t,r),r.x<this.minimumWorld.x&&(this.minimumWorld.x=r.x),r.y<this.minimumWorld.y&&(this.minimumWorld.y=r.y),r.z<this.minimumWorld.z&&(this.minimumWorld.z=r.z),r.x>this.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.addToRef(this.minimumWorld,this.center),this.center.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.x<i||i>t.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.y<i||i>t.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.z<i||i>t.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)},t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.x<e.x||this.minimumWorld.x>t.x)&&(!(this.maximumWorld.y<e.y||this.minimumWorld.y>t.y)&&!(this.maximumWorld.z<e.z||this.minimumWorld.z>t.z))},t.Intersects=function(e,t){return!(e.maximumWorld.x<t.minimumWorld.x||e.minimumWorld.x>t.maximumWorld.x)&&(!(e.maximumWorld.y<t.minimumWorld.y||e.minimumWorld.y>t.maximumWorld.y)&&!(e.maximumWorld.z<t.minimumWorld.z||e.minimumWorld.z>t.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i),s=e.Vector3.DistanceSquared(r,o);return s<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.center,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i){void 0===i&&(i=Number.MAX_VALUE),this.origin=e,this.direction=t,this.length=i,this._show=!1}return t.prototype.intersectsBoxMinMax=function(e,t){var i,r,n,o,s=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<e.x||this.origin.x>t.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<e.y||this.origin.y>t.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<e.z||this.origin.z>t.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;if(s<0)return!1;var a=n-s*s;return a<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var h=e.Vector3.Dot(this._edge2,this._qvec)*o;return h>this.length?null:new e.IntersectionInfo(s,a,h)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.show=function(t,i){this._show||(this._renderFunction=this._render.bind(this),this._show=!0,this._scene=t,this._renderPoints=[this.origin,this.origin.add(this.direction.scale(this.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._scene.registerBeforeRender(this._renderFunction)),i&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._show&&(this._show=!1,this._scene.unregisterBeforeRender(this._renderFunction)),this._renderLine&&(this._renderLine.dispose(),this._renderLine=null,this._renderPoints=null)},t.prototype._render=function(){var t=this._renderPoints[1];t.copyFrom(this.direction),t.scaleInPlace(this.length),t.addInPlace(this.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,h,c=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),l=r.subtract(i),u=c.subtract(this.origin),d=i.subtract(this.origin),f=e.Vector3.Dot(l,l),p=e.Vector3.Dot(l,u),m=e.Vector3.Dot(u,u),_=e.Vector3.Dot(l,d),g=e.Vector3.Dot(u,d),v=f*m-p*p,y=v,x=v;v<t.smallnum?(s=0,y=1,h=g,x=m):(s=p*g-m*_,h=f*g-p*_,s<0?(s=0,h=g,x=m):s>y&&(s=y,h=g+p,x=m)),h<0?(h=0,-_<0?s=0:-_>f?s=y:(s=-_,y=f)):h>x&&(h=x,-_+p<0?s=0:-_+p>f?s=y:(s=-_+p,y=f)),o=Math.abs(s)<t.smallnum?0:s/y,a=Math.abs(h)<t.smallnum?0:h/x;var b=u.multiplyByFloats(a,a,a),T=d.add(l.multiplyByFloats(o,o,o)).subtract(b),A=a>0&&a<=this.length&&T.lengthSquared()<n*n;return A?b.length():-1},t.CreateNew=function(i,r,n,o,s,a,h){var c=e.Vector3.Unproject(new e.Vector3(i,r,0),n,o,s,a,h),l=e.Vector3.Unproject(new e.Vector3(i,r,1),n,o,s,a,h),u=l.subtract(c);return u.normalize(),new t(c,u)},t.CreateNewFromTo=function(i,r,n){void 0===n&&(n=e.Matrix.Identity());var o=r.subtract(i),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),t.Transform(new t(i,o,s),n)},t.Transform=function(i,r){var n=e.Vector3.TransformCoordinates(i.origin,r),o=e.Vector3.TransformNormal(i.direction,r);return o.normalize(),new t(n,o,i.length)},t.TransformToRef=function(t,i,r){e.Vector3.TransformCoordinatesToRef(t.origin,i,r.origin),e.Vector3.TransformNormalToRef(t.direction,i,r.direction),t.direction.normalize()},t.smallnum=1e-8,t.rayl=1e9,t})();e.Ray=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n){var o=this;t.call(this,r,n),this.onCollideObservable=new e.Observable,this.onCollisionPositionChangeObservable=new e.Observable,this.onAfterWorldMatrixUpdateObservable=new e.Observable,this.definedFacingForward=!0,this.position=new e.Vector3(0,0,0),this._rotation=new e.Vector3(0,0,0),this._scaling=new e.Vector3(1,1,1),this.billboardMode=i.BILLBOARDMODE_NONE,this.visibility=1,this.alphaIndex=Number.MAX_VALUE,this.infiniteDistance=!1,this.isVisible=!0,this.isPickable=!0,this.showBoundingBox=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.renderingGroupId=0,this.receiveShadows=!1,this.renderOutline=!1,this.outlineColor=e.Color3.Red(),this.outlineWidth=.02,this.renderOverlay=!1,this.overlayColor=e.Color3.Red(),this.overlayAlpha=.5,this.hasVertexAlpha=!1,this.useVertexColors=!0,this.applyFog=!0,this.computeBonesUsingShaders=!0,this.scalingDeterminant=1,this.numBoneInfluencers=4,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.layerMask=268435455,this.alwaysSelectAsActiveMesh=!1,this._checkCollisions=!1,this.ellipsoid=new e.Vector3(.5,1,.5),this.ellipsoidOffset=new e.Vector3(0,0,0),this._collider=new e.Collider,this._oldPositionForCollisions=new e.Vector3(0,0,0),this._diffPositionForCollisions=new e.Vector3(0,0,0),this._newPositionForCollisions=new e.Vector3(0,0,0),this.edgesWidth=1,this.edgesColor=new e.Color4(1,0,0,1),this._localWorld=e.Matrix.Zero(),this._worldMatrix=e.Matrix.Zero(),this._rotateYByPI=e.Matrix.RotationY(Math.PI),this._absolutePosition=e.Vector3.Zero(),this._collisionsTransformMatrix=e.Matrix.Zero(),this._collisionsScalingMatrix=e.Matrix.Zero(),this._isDirty=!1,this._pivotMatrix=e.Matrix.Identity(),this._isDisposed=!1,this._renderId=0,this._intersectionsInProgress=new Array,this._isWorldMatrixFrozen=!1,this._unIndexed=!1,this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),o.getScene().workerCollisions&&i.multiplyInPlace(o._collider.radius),i.subtractToRef(o._oldPositionForCollisions,o._diffPositionForCollisions),o._diffPositionForCollisions.length()>e.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},n.addMesh(this)}return __extends(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return i._BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return i._BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return i._BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return i._BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return i._BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null)},enumerable:!0,configurable:!0}),i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this.physicsImpostor&&this.physicsImpostor.forceUpdate()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){this._poseMatrix.copyFrom(e)},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype.disableEdgesRendering=function(){void 0!==this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=void 0)},i.prototype.enableEdgesRendering=function(t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.disableEdgesRendering(),this._edgesRenderer=new e.EdgesRenderer(this,t,i)},Object.defineProperty(i.prototype,"isBlocked",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.getLOD=function(e){
return this},i.prototype.getTotalVertices=function(){return 0},i.prototype.getIndices=function(){return null},i.prototype.getVerticesData=function(e){return null},i.prototype.isVerticesDataPresent=function(e){return!1},i.prototype.getBoundingInfo=function(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfo||this._updateBoundingInfo(),this._boundingInfo)},i.prototype.setBoundingInfo=function(e){this._boundingInfo=e},Object.defineProperty(i.prototype,"useBones",{get:function(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)},enumerable:!0,configurable:!0}),i.prototype._preActivate=function(){},i.prototype._preActivateForIntermediateRendering=function(e){},i.prototype._activate=function(e){this._renderId=e},i.prototype.getWorldMatrix=function(){return this._masterMesh?this._masterMesh.getWorldMatrix():(this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix)},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.freezeWorldMatrix=function(){this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0},i.prototype.unfreezeWorldMatrix=function(){this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion)},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}},i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(t){var i,r,n;if(void 0===t.x){if(arguments.length<3)return;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n}},i.prototype.movePOV=function(e,t,i){this.position.addInPlace(this.calcMovePOV(e,t,i))},i.prototype.calcMovePOV=function(t,i,r){var n=new e.Matrix,o=this.rotationQuaternion?this.rotationQuaternion:e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);o.toRotationMatrix(n);var s=e.Vector3.Zero(),a=this.definedFacingForward?-1:1;return e.Vector3.TransformCoordinatesFromFloatsToRef(t*a,i,r*a,n,s),s},i.prototype.rotatePOV=function(e,t,i){this.rotation.addInPlace(this.calcRotatePOV(e,t,i))},i.prototype.calcRotatePOV=function(t,i,r){var n=this.definedFacingForward?1:-1;return new e.Vector3(t*n,i,r*n)},i.prototype.setPivotMatrix=function(e){this._pivotMatrix=e,this._cache.pivotMatrixUpdated=!0},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0},i.prototype._updateBoundingInfo=function(){this._boundingInfo=this._boundingInfo||new e.BoundingInfo(this.absolutePosition,this.absolutePosition),this._boundingInfo.update(this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)},i.prototype._updateSubMeshesBoundingInfo=function(e){if(this.subMeshes)for(var t=0;t<this.subMeshes.length;t++){var i=this.subMeshes[t];i.IsGlobal||i.updateBoundingInfo(e)}},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&(this._currentRenderId===this.getScene().getRenderId()||this.isSynchronized(!0)))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){var r=this.rotation.length();r&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}if(this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation)),this.infiniteDistance&&!this.parent){var n=this.getScene().activeCamera;if(n){var o=n.getWorldMatrix(),s=new e.Vector3(o.m[12],o.m[13],o.m[14]);e.Matrix.TranslationToRef(this.position.x+s.x,this.position.y+s.y,this.position.z+s.z,e.Tmp.Matrix[2])}}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&this.getScene().activeCamera){e.Tmp.Vector3[0].copyFrom(this.position);var a=e.Tmp.Vector3[0];if(this.parent&&this.parent.getWorldMatrix){this._markSyncedWithParent();var h;this._meshToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),h=e.Tmp.Matrix[6]):h=this.parent.getWorldMatrix(),e.Vector3.TransformNormalToRef(a,h,e.Tmp.Vector3[1]),a=e.Tmp.Vector3[1]}var c=this.getScene().activeCamera.globalPosition.clone();this.parent&&this.parent.position&&(a.addInPlace(this.parent.position),e.Matrix.TranslationToRef(a.x,a.y,a.z,e.Tmp.Matrix[2])),(this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL&&(this.billboardMode&i.BILLBOARDMODE_X&&(c.x=a.x+e.Epsilon),this.billboardMode&i.BILLBOARDMODE_Y&&(c.y=a.y+e.Epsilon),this.billboardMode&i.BILLBOARDMODE_Z&&(c.z=a.z+e.Epsilon)),e.Matrix.LookAtLHToRef(a,c,e.Vector3.Up(),e.Tmp.Matrix[3]),e.Tmp.Matrix[3].m[12]=e.Tmp.Matrix[3].m[13]=e.Tmp.Matrix[3].m[14]=0,e.Tmp.Matrix[3].invert(),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[3],this._localWorld),this._rotateYByPI.multiplyToRef(this._localWorld,e.Tmp.Matrix[5])}return e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix&&this.billboardMode===i.BILLBOARDMODE_NONE?(this._markSyncedWithParent(),this._meshToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix)):this._worldMatrix.copyFrom(this._localWorld),this._updateBoundingInfo(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrix},i.prototype.registerAfterWorldMatrixUpdate=function(e){this.onAfterWorldMatrixUpdateObservable.add(e)},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){this.onAfterWorldMatrixUpdateObservable.removeCallback(e)},i.prototype.setPositionWithLocalVector=function(t){this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld)},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld)},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,h=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(h,a);var c=-Math.atan2(a.z,a.x)-Math.PI/2,l=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,l);this.rotationQuaternion=this.rotationQuaternion||new e.Quaternion,e.Quaternion.RotationYawPitchRollToRef(c+r,u+n,o,this.rotationQuaternion)},i.prototype.attachToBone=function(e,t){this._meshToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1)},i.prototype.detachFromBone=function(){this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._meshToBoneReferal=null,this.parent=null},i.prototype.isInFrustum=function(e){return this._boundingInfo.isInFrustum(e)},i.prototype.isCompletelyInFrustum=function(e){return this._boundingInfo.isCompletelyInFrustum(e)},i.prototype.intersectsMesh=function(e,t){return!(!this._boundingInfo||!e._boundingInfo)&&this._boundingInfo.intersects(e._boundingInfo,t)},i.prototype.intersectsPoint=function(e){return!!this._boundingInfo&&this._boundingInfo.intersectsPoint(e)},i.prototype.setPhysicsState=function(t,i){return t.impostor&&(i=t,t=t.impostor),this.physicsImpostor=new e.PhysicsImpostor(this,t,i,this.getScene()),this.physicsImpostor.physicsBody},i.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},i.prototype.getPhysicsMass=function(){return this.physicsImpostor.getParam("mass")},i.prototype.getPhysicsFriction=function(){return this.physicsImpostor.getParam("friction")},i.prototype.getPhysicsRestitution=function(){return this.physicsImpostor.getParam("restitution")},i.prototype.getPositionInCameraSpace=function(t){return t||(t=this.getScene().activeCamera),e.Vector3.TransformCoordinates(this.absolutePosition,t.getViewMatrix())},i.prototype.getDistanceToCamera=function(e){return e||(e=this.getScene().activeCamera),this.absolutePosition.subtract(e.position).length()},i.prototype.applyImpulse=function(e,t){this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t)},i.prototype.setPhysicsLinkWith=function(t,i,r,n){this.physicsImpostor&&t.physicsImpostor&&this.physicsImpostor.createJoint(t.physicsImpostor,e.PhysicsJoint.HingeJoint,{mainPivot:i,connectedPivot:r,nativeParams:n})},i.prototype.updatePhysicsBodyPosition=function(){e.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()"),this.updatePhysicsBody()},i.prototype.updatePhysicsBody=function(){},Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return this._checkCollisions},set:function(e){this._checkCollisions=e,this.getScene().workerCollisions&&this.getScene().collisionCoordinator.onMeshUpdated(this)},enumerable:!0,configurable:!0}),i.prototype.moveWithCollisions=function(e){var t=this.getAbsolutePosition();t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPositionForCollisions),this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset),this._collider.radius=this.ellipsoid,this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions,e,this._collider,3,this,this._onCollisionPositionChange,this.uniqueId)},i.prototype.createOrUpdateSubmeshesOctree=function(t,i){void 0===t&&(t=64),void 0===i&&(i=2),this._submeshesOctree||(this._submeshesOctree=new e.Octree(e.Octree.CreationFuncForSubMeshes,t,i)),this.computeWorldMatrix(!0);var r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree},i.prototype._collideForSubMesh=function(t,i,r){if(this._generatePointsArray(),!t._lastColliderWorldVertices||!t._lastColliderTransformMatrix.equals(i)){t._lastColliderTransformMatrix=i.clone(),t._lastColliderWorldVertices=[],t._trianglePlanes=[];for(var n=t.verticesStart,o=t.verticesStart+t.verticesCount,s=n;s<o;s++)t._lastColliderWorldVertices.push(e.Vector3.TransformCoordinates(this._positions[s],i))}r._collide(t._trianglePlanes,t._lastColliderWorldVertices,this.getIndices(),t.indexStart,t.indexStart+t.indexCount,t.verticesStart,!!t.getMaterial()),r.collisionFound&&(r.collidedMesh=this)},i.prototype._processCollisionsForSubMeshes=function(e,t){var i,r;if(this._submeshesOctree&&this.useOctreeForCollisions){var n=e.velocityWorldLength+Math.max(e.radius.x,e.radius.y,e.radius.z),o=this._submeshesOctree.intersects(e.basePointWorld,n);r=o.length,i=o.data}else i=this.subMeshes,r=i.length;for(var s=0;s<r;s++){var a=i[s];r>1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}},i.prototype._checkCollision=function(t){this._boundingInfo._checkCollision(t)&&(e.Matrix.ScalingToRef(1/t.radius.x,1/t.radius.y,1/t.radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix))},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),h=this._submeshesOctree.intersectsRay(a);o=h.length,n=h.data}else n=this.subMeshes,o=n.length;for(var c=0;c<o;c++){var l=n[c];if(!(o>1)||l.canIntersects(t)){var u=l.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance<s.distance)&&(s=u,s.subMeshId=c,i))break}}if(s){var d=this.getWorldMatrix(),f=e.Vector3.TransformCoordinates(t.origin,d),p=t.direction.clone();p=p.scale(s.distance);var m=e.Vector3.TransformNormal(p,d),_=f.add(m);return r.hit=!0,r.distance=e.Vector3.Distance(f,_),r.pickedPoint=_,r.pickedMesh=this,r.bu=s.bu,r.bv=s.bv,r.faceId=s.faceId,r.subMeshId=s.subMeshId,r}return r},i.prototype.clone=function(e,t,i){return null},i.prototype.releaseSubMeshes=function(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array},i.prototype.dispose=function(e){var i,r=this;for(this.actionManager&&(this.actionManager.dispose(),this.actionManager=null),this.skeleton=null,this.getScene().stopAnimation(this),this.physicsImpostor&&this.physicsImpostor.dispose(),i=0;i<this._intersectionsInProgress.length;i++){var n=this._intersectionsInProgress[i],o=n._intersectionsInProgress.indexOf(this);n._intersectionsInProgress.splice(o,1)}this._intersectionsInProgress=[];var s=this.getScene().lights;if(s.forEach((function(e){var t=e.includedOnlyMeshes.indexOf(r);t!==-1&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(r),t!==-1&&e.excludedMeshes.splice(t,1);var i=e.getShadowGenerator();i&&(t=i.getShadowMap().renderList.indexOf(r),t!==-1&&i.getShadowMap().renderList.splice(t,1))})),this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this.releaseSubMeshes(),this.getScene().getEngine().unbindAllAttributes(),this.getScene().removeMesh(this),e){var a=this.getChildMeshes(!0);for(i=0;i<a.length;i++){var h=a[i];h.parent=null,h.computeWorldMatrix(!0)}}else{for(i=0;i<this.getScene().particleSystems.length;i++)this.getScene().particleSystems[i].emitter===this&&(this.getScene().particleSystems[i].dispose(),i--);var c=this.getDescendants(!0);for(i=0;i<c.length;i++)c[i].dispose()}this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this._isDisposed=!0,t.prototype.dispose.call(this)},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i)},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}e.Vector3.TransformCoordinatesToRef(t,r,this.position),this._pivotMatrix.m[12]=-t.x,this._pivotMatrix.m[13]=-t.y,this._pivotMatrix.m[14]=-t.z,this._cache.pivotMatrixUpdated=!0},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14]},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t)},i._BILLBOARDMODE_NONE=0,i._BILLBOARDMODE_X=1,i._BILLBOARDMODE_Y=2,i._BILLBOARDMODE_Z=4,i._BILLBOARDMODE_ALL=7,i._rotationAxisCache=new e.Quaternion,i._lookAtVectorCache=new e.Vector3(0,0,0),i})(e.Node);e.AbstractMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,i,r),this.diffuse=new e.Color3(1,1,1),this.specular=new e.Color3(1,1,1),this.intensity=1,this.range=Number.MAX_VALUE,this.includeOnlyWithLayerMask=0,this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this.excludeWithLayerMask=0,this.lightmapMode=0,this.radius=1e-5,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,r.addLight(this)}return __extends(i,t),Object.defineProperty(i,"LIGHTMAP_DEFAULT",{get:function(){return i._LIGHTMAP_DEFAULT},enumerable:!0,configurable:!0}),Object.defineProperty(i,"LIGHTMAP_SPECULAR",{get:function(){return i._LIGHTMAP_SPECULAR},enumerable:!0,configurable:!0}),Object.defineProperty(i,"LIGHTMAP_SHADOWSONLY",{get:function(){return i._LIGHTMAP_SHADOWSONLY},enumerable:!0,configurable:!0}),i.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},i.prototype.getShadowGenerator=function(){return this._shadowGenerator},i.prototype.getAbsolutePosition=function(){return e.Vector3.Zero()},i.prototype.transferToEffect=function(e,t,i){},i.prototype._getWorldMatrix=function(){return e.Matrix.Identity()},i.prototype.canAffectMesh=function(e){return!e||!(this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1)&&(!(this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1)&&((0===this.includeOnlyWithLayerMask||0!==(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId();var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.prototype.dispose=function(){this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this),this.getScene().removeLight(this),t.prototype.dispose.call(this)},i.prototype.getTypeID=function(){return 0},i.prototype.clone=function(t){return e.SerializationHelper.Clone(i.GetConstructorFromName(this.getTypeID(),t,this.getScene()),this)},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.type=this.getTypeID(),this.parent&&(t.parentId=this.parent.id),this.excludedMeshes.length>0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){switch(t){case 0:return function(){return new e.PointLight(i,e.Vector3.Zero(),r)};case 1:return function(){return new e.DirectionalLight(i,e.Vector3.Zero(),r)};case 2:return function(){return new e.SpotLight(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)};case 3:return function(){return new e.HemisphericLight(i,e.Vector3.Zero(),r)}}},i.Parse=function(t,r){var n=e.SerializationHelper.Parse(i.GetConstructorFromName(t.type,t.name,r),t,r);if(t.excludedMeshesIds&&(n._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(n._waitingParentId=t.parentId),t.animations){for(var o=0;o<t.animations.length;o++){var s=t.animations[o];n.animations.push(e.Animation.Parse(s))}e.Node.ParseAnimationRanges(n,t,r)}return t.autoAnimate&&r.beginAnimation(n,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),n},i._LIGHTMAP_DEFAULT=0,i._LIGHTMAP_SPECULAR=1,i._LIGHTMAP_SHADOWSONLY=2,__decorate([e.serializeAsColor3()],i.prototype,"diffuse",void 0),__decorate([e.serializeAsColor3()],i.prototype,"specular",void 0),__decorate([e.serialize()],i.prototype,"intensity",void 0),__decorate([e.serialize()],i.prototype,"range",void 0),__decorate([e.serialize()],i.prototype,"includeOnlyWithLayerMask",void 0),__decorate([e.serialize()],i.prototype,"excludeWithLayerMask",void 0),__decorate([e.serialize()],i.prototype,"lightmapMode",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),i})(e.Node);e.Light=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r){t.call(this,e,r),this.position=i}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(e,t){return this.parent&&this.parent.getWorldMatrix?(this.computeTransformedPosition(),void e.setFloat4(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0)):void e.setFloat4(t,this.position.x,this.position.y,this.position.z,0)},i.prototype.needCube=function(){return!0},i.prototype.supportsVSM=function(){return!1},i.prototype.needRefreshPerFrame=function(){return!1},i.prototype.getShadowDirection=function(t){switch(t){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3((-1),0,0);case 2:return new e.Vector3(0,(-1),0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,(-1))}return e.Vector3.Zero()},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;e.Matrix.PerspectiveFovLHToRef(Math.PI/2,1,n.minZ,n.maxZ,t)},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 0},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),i})(e.Light);e.PointLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){t.call(this,e,s),this.position=i,this.direction=r,this.angle=n,this.exponent=o}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;e.Matrix.PerspectiveFovLHToRef(this.angle,1,n.minZ,n.maxZ,t)},i.prototype.needCube=function(){return!1},i.prototype.supportsVSM=function(){return!0},i.prototype.needRefreshPerFrame=function(){return!1},i.prototype.getShadowDirection=function(e){return this.direction},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(t,i,r){var n;this.parent&&this.parent.getWorldMatrix?(this._transformedDirection||(this._transformedDirection=e.Vector3.Zero()),this.computeTransformedPosition(),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection),t.setFloat4(i,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent),n=e.Vector3.Normalize(this._transformedDirection)):(t.setFloat4(i,this.position.x,this.position.y,this.position.z,this.exponent),n=e.Vector3.Normalize(this.direction)),t.setFloat4(r,n.x,n.y,n.z,Math.cos(.5*this.angle))},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 2},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),__decorate([e.serialize()],i.prototype,"angle",void 0),__decorate([e.serialize()],i.prototype,"exponent",void 0),i})(e.Light);e.SpotLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,n),this.groundColor=new e.Color3(0,0,0),this.direction=r}return __extends(i,t),i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i,r){var n=e.Vector3.Normalize(this.direction);t.setFloat4(i,n.x,n.y,n.z,0),t.setColor3(r,this.groundColor.scale(this.intensity))},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return 3},__decorate([e.serializeAsColor3()],i.prototype,"groundColor",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r){t.call(this,e,r),this.shadowOrthoScale=.5,this.autoUpdateExtends=!0,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=i.scale(-1),this.direction=i}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;s<r.length;s++){var a=r[s];if(a){var h=a.getBoundingInfo();if(h)for(var c=h.boundingBox,l=0;l<c.vectorsWorld.length;l++)e.Vector3.TransformCoordinatesToRef(c.vectorsWorld[l],i,o),o.x<this._orthoLeft&&(this._orthoLeft=o.x),o.y<this._orthoBottom&&(this._orthoBottom=o.y),o.x>this._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}}var u=this._orthoRight-this._orthoLeft,d=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-d*this.shadowOrthoScale,this._orthoTop+d*this.shadowOrthoScale,-n.maxZ,n.maxZ,t)},i.prototype.supportsVSM=function(){return!0},i.prototype.needRefreshPerFrame=function(){return!0},i.prototype.needCube=function(){return!1},i.prototype.getShadowDirection=function(e){return this.direction},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(t,i){return this.parent&&this.parent.getWorldMatrix?(this._transformedDirection||(this._transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection),void t.setFloat4(i,this._transformedDirection.x,this._transformedDirection.y,this._transformedDirection.z,1)):void t.setFloat4(i,this.direction.x,this.direction.y,this.direction.z,1)},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 1},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),__decorate([e.serialize()],i.prototype,"shadowOrthoScale",void 0),__decorate([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.Light);e.DirectionalLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(i,r){var n=this;this._filter=t.FILTER_NONE,this.blurScale=2,this._blurBoxOffset=0,this._bias=5e-5,this._lightDirection=e.Vector3.Zero(),this.forceBackFacesOnly=!1,this._darkness=0,this._transparencyShadow=!1,this._viewMatrix=e.Matrix.Zero(),this._projectionMatrix=e.Matrix.Zero(),this._transformMatrix=e.Matrix.Zero(),this._worldViewProjection=e.Matrix.Zero(),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._useFullFloat=!0,this._light=r,this._scene=r.getScene(),this._mapSize=i,r._shadowGenerator=this;var o,s=this._scene.getEngine().getCaps();s.textureFloat&&s.textureFloatLinearFiltering&&s.textureFloatRender?(this._useFullFloat=!0,o=e.Engine.TEXTURETYPE_FLOAT):(this._useFullFloat=!1,o=e.Engine.TEXTURETYPE_UNSIGNED_INT),this._shadowMap=new e.RenderTargetTexture(r.name+"_shadowMap",i,this._scene,(!1),(!0),o,r.needCube()),
this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.NEAREST_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.onBeforeRenderObservable.add((function(e){n._currentFaceIndex=e})),this._shadowMap.onAfterUnbindObservable.add((function(){n.useBlurVarianceShadowMap&&(n._shadowMap2||(n._shadowMap2=new e.RenderTargetTexture(r.name+"_shadowMap",i,n._scene,(!1),(!0),o),n._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,n._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,n._shadowMap2.updateSamplingMode(e.Texture.TRILINEAR_SAMPLINGMODE),n._downSamplePostprocess=new e.PassPostProcess("downScale",1/n.blurScale,null,e.Texture.BILINEAR_SAMPLINGMODE,n._scene.getEngine()),n._downSamplePostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",n._shadowMap)})),n.blurBoxOffset=1),n._scene.postProcessManager.directRender([n._downSamplePostprocess,n._boxBlurPostprocess],n._shadowMap2.getInternalTexture()))}));var a=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id]&&void 0!==s.visibleInstances[t._id];if(n.isReady(t,a)){o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode);var h=t.getMaterial();if(n._effect.setMatrix("viewProjection",n.getTransformMatrix()),n._effect.setVector3("lightPosition",n.getLight().position),n.getLight().needCube()&&n._effect.setFloat2("depthValues",r.activeCamera.minZ,r.activeCamera.maxZ),h&&h.needAlphaTesting()){var c=h.getAlphaTestTexture();n._effect.setTexture("diffuseSampler",c),n._effect.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),n.forceBackFacesOnly&&o.setState(!0,0,!1,!0),i._processRendering(t,n._effect,e.Material.TriangleFillMode,s,a,(function(e,t){return n._effect.setMatrix("world",t)})),n.forceBackFacesOnly&&o.setState(!0,0,!1,!1)}else n._shadowMap.resetRefreshCounter()}};this._shadowMap.customRenderFunction=function(e,t,i){var r;for(r=0;r<e.length;r++)a(e.data[r]);for(r=0;r<t.length;r++)a(t.data[r]);if(n._transparencyShadow)for(r=0;r<i.length;r++)a(i.data[r])},this._shadowMap.onClearObservable.add((function(t){n.useBlurVarianceShadowMap||n.useVarianceShadowMap?t.clear(new e.Color4(0,0,0,0),!0,!0,!0):t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}))}return Object.defineProperty(t,"FILTER_NONE",{get:function(){return t._FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_VARIANCESHADOWMAP",{get:function(){return t._FILTER_VARIANCESHADOWMAP},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_POISSONSAMPLING",{get:function(){return t._FILTER_POISSONSAMPLING},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_BLURVARIANCESHADOWMAP",{get:function(){return t._FILTER_BLURVARIANCESHADOWMAP},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bias",{get:function(){return this._bias},set:function(e){this._bias=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(t){var i=this;this._blurBoxOffset!==t&&(this._blurBoxOffset=t,this._boxBlurPostprocess&&this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=new e.PostProcess("DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1/this.blurScale,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define OFFSET "+t),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",i._mapSize/i.blurScale,i._mapSize/i.blurScale)})))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"filter",{get:function(){return this._filter},set:function(t){this._filter!==t&&(this._filter=t,this.useVarianceShadowMap||this.useBlurVarianceShadowMap||this.usePoissonSampling?(this._shadowMap.anisotropicFilteringLevel=16,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)):(this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.NEAREST_SAMPLINGMODE)))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useVarianceShadowMap",{get:function(){return this.filter===t.FILTER_VARIANCESHADOWMAP&&this._light.supportsVSM()},set:function(e){this.filter=e?t.FILTER_VARIANCESHADOWMAP:t.FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"usePoissonSampling",{get:function(){return this.filter===t.FILTER_POISSONSAMPLING||!this._light.supportsVSM()&&(this.filter===t.FILTER_VARIANCESHADOWMAP||this.filter===t.FILTER_BLURVARIANCESHADOWMAP)},set:function(e){this.filter=e?t.FILTER_POISSONSAMPLING:t.FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBlurVarianceShadowMap",{get:function(){return this.filter===t.FILTER_BLURVARIANCESHADOWMAP&&this._light.supportsVSM()},set:function(e){this.filter=e?t.FILTER_BLURVARIANCESHADOWMAP:t.FILTER_NONE},enumerable:!0,configurable:!0}),t.prototype.isReady=function(t,i){var r=[];this._useFullFloat&&r.push("#define FULLFLOAT"),(this.useVarianceShadowMap||this.useBlurVarianceShadowMap)&&r.push("#define VSM"),this.getLight().needCube()&&r.push("#define CUBEMAP");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(s&&s.needAlphaTesting()&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind))){var a=s.getAlphaTestTexture();1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2"))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var h=r.join("\n");return this._cachedDefines!==h&&(this._cachedDefines=h,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightPosition","depthValues"],["diffuseSampler"],h)),this._effect.isReady()},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.getLight=function(){return this._light},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;return e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.computeTransformedPosition()&&(i=this._light.transformedPosition),!this._light.needRefreshPerFrame()&&this._cachedPosition&&this._cachedDirection&&i.equals(this._cachedPosition)&&this._lightDirection.equals(this._cachedDirection)||(this._cachedPosition=i.clone(),this._cachedDirection=this._lightDirection.clone(),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix),this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,this.getShadowMap().renderList),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)),this._transformMatrix},t.prototype.getDarkness=function(){return this._darkness},t.prototype.setDarkness=function(e){e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e},t.prototype.setTransparencyShadow=function(e){this._transparencyShadow=e},t.prototype._packHalf=function(t){var i=255*t,r=i-Math.floor(i);return new e.Vector2(t-r/255,r)},t.prototype.dispose=function(){this._shadowMap.dispose(),this._shadowMap2&&this._shadowMap2.dispose(),this._downSamplePostprocess&&this._downSamplePostprocess.dispose(),this._boxBlurPostprocess&&this._boxBlurPostprocess.dispose()},t.prototype.serialize=function(){var e={};e.lightId=this._light.id,e.mapSize=this.getShadowMap().getRenderSize(),e.useVarianceShadowMap=this.useVarianceShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.renderList=[];for(var t=0;t<this.getShadowMap().renderList.length;t++){var i=this.getShadowMap().renderList[t];e.renderList.push(i.id)}return e},t.Parse=function(e,i){for(var r=i.getLightByID(e.lightId),n=new t(e.mapSize,r),o=0;o<e.renderList.length;o++){var s=i.getMeshesByID(e.renderList[o]);s.forEach((function(e){n.getShadowMap().renderList.push(e)}))}return e.usePoissonSampling?n.usePoissonSampling=!0:e.useVarianceShadowMap?n.useVarianceShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurVarianceShadowMap=!0,e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset)),void 0!==e.bias&&(n.bias=e.bias),n.forceBackFacesOnly=e.forceBackFacesOnly,n},t._FILTER_NONE=0,t._FILTER_VARIANCESHADOWMAP=1,t._FILTER_POISSONSAMPLING=2,t._FILTER_BLURVARIANCESHADOWMAP=3,t})();e.ShadowGenerator=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t,i,r){return!(e.x>i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),h=(-i+s)/(2*t);if(a>h){var c=h;h=a,a=c}return a>0&&a<n?(e.root=a,e.found=!0,e):h>0&&h<n?(e.root=h,e.found=!0,e):e}})(),r=(function(){function r(){this.radius=new e.Vector3(1,1,1),this.retry=0,this.basePointWorld=e.Vector3.Zero(),this.velocityWorld=e.Vector3.Zero(),this.normalizedVelocity=e.Vector3.Zero(),this._collisionPoint=e.Vector3.Zero(),this._planeIntersectionPoint=e.Vector3.Zero(),this._tempVector=e.Vector3.Zero(),this._tempVector2=e.Vector3.Zero(),this._tempVector3=e.Vector3.Zero(),this._tempVector4=e.Vector3.Zero(),this._edge=e.Vector3.Zero(),this._baseToVertex=e.Vector3.Zero(),this._destinationPoint=e.Vector3.Zero(),this._slidePlaneNormal=e.Vector3.Zero(),this._displacementVector=e.Vector3.Zero()}return r.prototype._initialize=function(t,i,r){this.velocity=i,e.Vector3.NormalizeToRef(i,this.normalizedVelocity),this.basePoint=t,t.multiplyToRef(this.radius,this.basePointWorld),i.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=r,this.collisionFound=!1},r.prototype._checkPointInTriangle=function(t,i,r,n,o){i.subtractToRef(t,this._tempVector),r.subtractToRef(t,this._tempVector2),e.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var s=e.Vector3.Dot(this._tempVector4,o);return!(s<0)&&(n.subtractToRef(t,this._tempVector3),e.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),s=e.Vector3.Dot(this._tempVector4,o),!(s<0)&&(e.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),s=e.Vector3.Dot(this._tempVector4,o),s>=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this.basePointWorld,i),a=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(s>this.velocityWorldLength+a+r)&&!!t(n,o,this.basePointWorld,this.velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var h,c=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var l=r[t];if(a||l.isFrontFacingTo(this.normalizedVelocity,0)){var u=l.signedDistanceTo(this.basePoint),d=e.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(u)>=1)return;c=!0,h=0}else{h=(-1-u)/d;var f=(1-u)/d;if(h>f){var p=f;f=h,h=p}if(h>1||f<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var m=!1,_=1;if(c||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,l.normal)&&(m=!0,_=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!m){var g=this.velocity.lengthSquared(),v=g;this.basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,_);b.found&&(_=b.root,m=!0,this._collisionPoint.copyFrom(n)),this.basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,_),b.found&&(_=b.root,m=!0,this._collisionPoint.copyFrom(o)),this.basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,_),b.found&&(_=b.root,m=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex);var T=this._edge.lengthSquared(),A=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=T*-g+A*A,y=T*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*A*E,x=T*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,_),b.found){var P=(A*b.root-E)/T;P>=0&&P<=1&&(_=b.root,m=!0,this._edge.scaleInPlace(P),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this.basePoint,this._baseToVertex),T=this._edge.lengthSquared(),A=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+A*A,y=T*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*A*E,x=T*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,_),b.found&&(P=(A*b.root-E)/T,P>=0&&P<=1&&(_=b.root,m=!0,this._edge.scaleInPlace(P),o.addToRef(this._edge,this._collisionPoint))),n.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex),T=this._edge.lengthSquared(),A=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex),v=T*-g+A*A,y=T*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*A*E,x=T*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,_),b.found&&(P=(A*b.root-E)/T,P>=0&&P<=1&&(_=b.root,m=!0,this._edge.scaleInPlace(P),s.addToRef(this._edge,this._collisionPoint)))}if(m){var M=_*this.velocity.length();(!this.collisionFound||M<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=M,this.collisionFound=!0)}}},r.prototype._collide=function(e,t,i,r,n,o,s){for(var a=r;a<n;a+=3){var h=t[i[a]-o],c=t[i[a+1]-o],l=t[i[a+2]-o];this._testTriangle(a,e,l,c,h,s)}},r.prototype._getResponse=function(t,i){t.addToRef(i,this._destinationPoint),i.scaleInPlace(this.nearestDistance/i.length()),this.basePoint.addToRef(i,t),t.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),t.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(e.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,i)},r})();e.Collider=r})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){e.CollisionWorker="",(function(e){e[e.INIT=0]="INIT",e[e.UPDATE=1]="UPDATE",e[e.COLLIDE=2]="COLLIDE"})(e.WorkerTaskType||(e.WorkerTaskType={}));var t=e.WorkerTaskType;!(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.UNKNOWN_ERROR=1]="UNKNOWN_ERROR"})(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,r=(function(){function r(){var n=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){n._addUpdateMeshesList[e.uniqueId]=r.SerializeMesh(e)},this.onGeometryUpdated=function(e){n._addUpdateGeometriesList[e.id]=r.SerializeGeometry(e)},this._afterRender=function(){if(n._init&&!(0==n._toRemoveGeometryArray.length&&0==n._toRemoveMeshesArray.length&&0==Object.keys(n._addUpdateGeometriesList).length&&0==Object.keys(n._addUpdateMeshesList).length||n._runningUpdated>4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList,removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:n._runningCollisionTask=!1;var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;n._collisionsCallbackArray[s.collisionId](s.collisionId,e.Vector3.FromArray(s.newPosition),n._scene.getMeshByUniqueID(s.collidedMeshUniqueId)),n._collisionsCallbackArray[s.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r.radius,this._scaledPosition),i.divideToRef(r.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var h={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r.radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},c={payload:h,taskType:t.COLLIDE};this._worker.postMessage(c)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}})));var r=null;return t instanceof e.Mesh?r=t.geometry?t.geometry.id:null:t instanceof e.InstancedMesh&&(r=t.sourceMesh&&t.sourceMesh.geometry?t.sourceMesh.geometry.id:null),{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:t.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:t.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:t.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:t.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i.radius,this._scaledPosition),t.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i.radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r.retry>=n)return void o.copyFrom(t);r._initialize(t,i,a);for(var h=0;h<this._scene.meshes.length;h++){var c=this._scene.meshes[h];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==s&&c._checkCollision(r)}return r.collisionFound?(0===i.x&&0===i.y&&0===i.z||r._getResponse(t,i),i.length()<=a?void o.copyFrom(t):(r.retry++,void this._collideWithWorld(t,i,r,n,o,s))):void t.addToRef(i,o)},t})();e.CollisionCoordinatorLegacy=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o){t.call(this,r,o),this.upVector=e.Vector3.Up(),this.orthoLeft=null,this.orthoRight=null,this.orthoBottom=null,this.orthoTop=null,this.fov=.8,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this.mode=i.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new e.Viewport(0,0,1,1),this.layerMask=268435455,this.fovMode=i.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=i.RIG_MODE_NONE,this._rigCameras=new Array,this._computedViewMatrix=e.Matrix.Identity(),this._projectionMatrix=new e.Matrix,this._doNotComputeProjectionMatrix=!1,this._postProcesses=new Array,this._transformMatrix=e.Matrix.Zero(),this._webvrViewMatrix=e.Matrix.Identity(),this._activeMeshes=new e.SmartArray(256),this._globalPosition=e.Vector3.Zero(),this._refreshFrustumPlanes=!0,o.addCamera(this),o.activeCamera||(o.activeCamera=this),this.position=n}return __extends(i,t),Object.defineProperty(i,"PERSPECTIVE_CAMERA",{get:function(){return i._PERSPECTIVE_CAMERA},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ORTHOGRAPHIC_CAMERA",{get:function(){return i._ORTHOGRAPHIC_CAMERA},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOVMODE_VERTICAL_FIXED",{get:function(){return i._FOVMODE_VERTICAL_FIXED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOVMODE_HORIZONTAL_FIXED",{get:function(){return i._FOVMODE_HORIZONTAL_FIXED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_NONE",{get:function(){return i._RIG_MODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_ANAGLYPH",{get:function(){return i._RIG_MODE_STEREOSCOPIC_ANAGLYPH},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL",{get:function(){return i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED",{get:function(){return i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_OVERUNDER",{get:function(){return i._RIG_MODE_STEREOSCOPIC_OVERUNDER},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_VR",{get:function(){return i._RIG_MODE_VR},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_WEBVR",{get:function(){return i._RIG_MODE_WEBVR},enumerable:!0,configurable:!0}),i.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+this.getTypeName(),this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},Object.defineProperty(i.prototype,"globalPosition",{get:function(){return this._globalPosition},enumerable:!0,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.position=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this.getEngine();this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector),this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()},i.prototype._updateFromScene=function(){this.updateCache(),this.update()},i.prototype._isSynchronized=function(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronized.call(this)&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())},i.prototype._isSynchronizedProjectionMatrix=function(){var e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;var t=this.getEngine();return e=this.mode===i.PERSPECTIVE_CAMERA?this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this):this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight()},i.prototype.attachControl=function(e,t){},i.prototype.detachControl=function(e){},i.prototype.update=function(){this.cameraRigMode!==i.RIG_MODE_NONE&&this._updateRigCameras(),this._checkInputs()},i.prototype._checkInputs=function(){},i.prototype._cascadePostProcessesToRigCams=function(){this._postProcesses.length>0&&this._postProcesses[0].markTextureDirty();for(var t=0,i=this._rigCameras.length;t<i;t++){var r=this._rigCameras[t],n=r._rigPostProcess;if(n){var o=n instanceof e.PassPostProcess;o&&(r.isIntermediate=0===this._postProcesses.length),r._postProcesses=this._postProcesses.slice(0).concat(n),n.markTextureDirty()}else r._postProcesses=this._postProcesses.slice(0)}},i.prototype.attachPostProcess=function(t,i){return void 0===i&&(i=null),!t.isReusable()&&this._postProcesses.indexOf(t)>-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e,t){void 0===t&&(t=null);var i,r,n=[];if(t)for(t=t instanceof Array?t:[t],i=t.length-1;i>=0;i--)this._postProcesses[t[i]]===e?this._postProcesses.splice(r,1):n.push(i);else{var o=this._postProcesses.indexOf(e);o!==-1&&this._postProcesses.splice(o,1)}return this._cascadePostProcessesToRigCams(),n},i.prototype.getWorldMatrix=function(){this._worldMatrix||(this._worldMatrix=e.Matrix.Identity());var t=this.getViewMatrix();return t.invertToRef(this._worldMatrix),this._worldMatrix},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(t){return this._computedViewMatrix=this._computeViewMatrix(t),!t&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._refreshFrustumPlanes=!0,this.parent&&this.parent.getWorldMatrix?(this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._computedViewMatrix),this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12],this._computedViewMatrix.m[13],this._computedViewMatrix.m[14]),this._computedViewMatrix.invert(),this._markSyncedWithParent()):this._globalPosition.copyFrom(this.position),this._currentRenderId=this.getScene().getRenderId(),this._computedViewMatrix)},i.prototype._computeViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)return this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED),this._projectionMatrix;var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;return n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._projectionMatrix},i.prototype.getTranformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTranformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.dispose=function(){for(this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;)this._rigCameras.pop().dispose();
for(var e=0;e<this._postProcesses.length;++e)this._postProcesses[e].dispose(this);t.prototype.dispose.call(this)},i.prototype.setCameraRigMode=function(t,r){for(;this._rigCameras.length>0;)this._rigCameras.pop().dispose();switch(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE&&(this._rigCameras.push(this.createRigCamera(this.name+"_L",0)),this._rigCameras.push(this.createRigCamera(this.name+"_R",1))),this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var n=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,n);break;case i.RIG_MODE_VR:var o=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=o,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=o.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=o.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=o,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=o.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=o.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,o.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],(!1),o),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],(!0),o));break;case i.RIG_MODE_WEBVR:r.vrDisplay&&(this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix)}this._cascadePostProcessesToRigCams(),this.update()},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._getWebVRProjectionMatrix=function(){var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return[8,9,10,11].forEach((function(e){t[e]*=-1})),e.Matrix.FromArrayToRef(t,0,this._projectionMatrix),this._projectionMatrix},i.prototype._getWebVRViewMatrix=function(){var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return[8,9,10,11].forEach((function(e){t[e]*=-1})),e.Matrix.FromArrayToRef(t,0,this._webvrViewMatrix),this._webvrViewMatrix},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov;this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)},i.prototype._setupInputs=function(){},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.type=this.getTypeName(),this.parent&&(t.parentId=this.parent.id),this.inputs&&this.inputs.serialize(t),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.prototype.getTypeName=function(){return"Camera"},i.prototype.clone=function(t){return e.SerializationHelper.Clone(i.GetConstructorFromName(this.getTypeName(),t,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this)},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i)},i.GetConstructorFromName=function(t,i,r,n,o){switch(void 0===n&&(n=0),void 0===o&&(o=!0),t){case"ArcRotateCamera":return function(){return new e.ArcRotateCamera(i,0,0,1,e.Vector3.Zero(),r)};case"DeviceOrientationCamera":return function(){return new e.DeviceOrientationCamera(i,e.Vector3.Zero(),r)};case"FollowCamera":return function(){return new e.FollowCamera(i,e.Vector3.Zero(),r)};case"ArcFollowCamera":return function(){return new e.ArcFollowCamera(i,0,0,1,null,r)};case"GamepadCamera":return function(){return new e.GamepadCamera(i,e.Vector3.Zero(),r)};case"TouchCamera":return function(){return new e.TouchCamera(i,e.Vector3.Zero(),r)};case"VirtualJoysticksCamera":return function(){return new e.VirtualJoysticksCamera(i,e.Vector3.Zero(),r)};case"WebVRFreeCamera":return function(){return new e.WebVRFreeCamera(i,e.Vector3.Zero(),r)};case"VRDeviceOrientationFreeCamera":return function(){return new e.VRDeviceOrientationFreeCamera(i,e.Vector3.Zero(),r)};case"AnaglyphArcRotateCamera":return function(){return new e.AnaglyphArcRotateCamera(i,0,0,1,e.Vector3.Zero(),n,r)};case"AnaglyphFreeCamera":return function(){return new e.AnaglyphFreeCamera(i,e.Vector3.Zero(),n,r)};case"AnaglyphGamepadCamera":return function(){return new e.AnaglyphGamepadCamera(i,e.Vector3.Zero(),n,r)};case"AnaglyphUniversalCamera":return function(){return new e.AnaglyphUniversalCamera(i,e.Vector3.Zero(),n,r)};case"StereoscopicArcRotateCamera":return function(){return new e.StereoscopicArcRotateCamera(i,0,0,1,e.Vector3.Zero(),n,o,r)};case"StereoscopicFreeCamera":return function(){return new e.StereoscopicFreeCamera(i,e.Vector3.Zero(),n,o,r)};case"StereoscopicGamepadCamera":return function(){return new e.StereoscopicGamepadCamera(i,e.Vector3.Zero(),n,o,r)};case"StereoscopicUniversalCamera":return function(){return new e.StereoscopicUniversalCamera(i,e.Vector3.Zero(),n,o,r)};case"FreeCamera":return function(){return new e.UniversalCamera(i,e.Vector3.Zero(),r)};default:return function(){return new e.UniversalCamera(i,e.Vector3.Zero(),r)}}},i.Parse=function(t,r){var n=t.type,o=i.GetConstructorFromName(n,t.name,r,t.interaxial_distance,t.isStereoscopicSideBySide),s=e.SerializationHelper.Parse(o,t,r);if(t.parentId&&(s._waitingParentId=t.parentId),s.inputs&&(s.inputs.parse(t),s._setupInputs()),t.target&&s.setTarget&&s.setTarget(e.Vector3.FromArray(t.target)),t.cameraRigMode){var a=t.interaxial_distance?{interaxialDistance:t.interaxial_distance}:{};s.setCameraRigMode(t.cameraRigMode,a)}if(t.animations){for(var h=0;h<t.animations.length;h++){var c=t.animations[h];s.animations.push(e.Animation.Parse(c))}e.Node.ParseAnimationRanges(s,t,r)}return t.autoAnimate&&r.beginAnimation(s,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),s},i._PERSPECTIVE_CAMERA=0,i._ORTHOGRAPHIC_CAMERA=1,i._FOVMODE_VERTICAL_FIXED=0,i._FOVMODE_HORIZONTAL_FIXED=1,i._RIG_MODE_NONE=0,i._RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,i._RIG_MODE_STEREOSCOPIC_OVERUNDER=13,i._RIG_MODE_VR=20,i._RIG_MODE_WEBVR=21,i.ForceAttachControlToAlwaysPreventDefault=!1,__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"upVector",void 0),__decorate([e.serialize()],i.prototype,"orthoLeft",void 0),__decorate([e.serialize()],i.prototype,"orthoRight",void 0),__decorate([e.serialize()],i.prototype,"orthoBottom",void 0),__decorate([e.serialize()],i.prototype,"orthoTop",void 0),__decorate([e.serialize()],i.prototype,"fov",void 0),__decorate([e.serialize()],i.prototype,"minZ",void 0),__decorate([e.serialize()],i.prototype,"maxZ",void 0),__decorate([e.serialize()],i.prototype,"inertia",void 0),__decorate([e.serialize()],i.prototype,"mode",void 0),__decorate([e.serialize()],i.prototype,"layerMask",void 0),__decorate([e.serialize()],i.prototype,"fovMode",void 0),__decorate([e.serialize()],i.prototype,"cameraRigMode",void 0),__decorate([e.serialize()],i.prototype,"interaxialDistance",void 0),__decorate([e.serialize()],i.prototype,"isStereoscopicSideBySide",void 0),i})(e.Node);e.Camera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();return this.attached[i]?void e.Tools.Warn("camera input of type "+i+" already exists on camera"):(this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),void(this.attachedElement&&t.attachControl(this.attachedElement)))},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getTypeName()===e&&(i.detachControl(this.attachedElement),delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached){this.attached[r];this.attached[r].attachControl(t,i)}}},t.prototype.detachElement=function(e){if(this.attachedElement===e){for(var t in this.attached){this.attached[t];this.attached[t].detachControl(e)}this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getTypeName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getTypeName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){void 0===e&&(e=!0),this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getEngine();this._pointerInput||(this._pointerInput=function(o,s){var a=o.event;if((r.touchEnabled||"touch"!==a.pointerType)&&(o.type===e.PointerEventTypes.POINTERMOVE||r.buttons.indexOf(a.button)!==-1))if(o.type===e.PointerEventTypes.POINTERDOWN){try{a.srcElement.setPointerCapture(a.pointerId)}catch(h){}r.previousPosition={x:a.clientX,y:a.clientY},i||(a.preventDefault(),t.focus())}else if(o.type===e.PointerEventTypes.POINTERUP){try{a.srcElement.releasePointerCapture(a.pointerId)}catch(h){}r.previousPosition=null,i||a.preventDefault()}else if(o.type===e.PointerEventTypes.POINTERMOVE){if(!r.previousPosition||n.isPointerLock)return;var c=a.clientX-r.previousPosition.x,l=a.clientY-r.previousPosition.y;r.camera.getScene().useRightHandedSystem?r.camera.cameraRotation.y-=c/r.angularSensibility:r.camera.cameraRotation.y+=c/r.angularSensibility,r.camera.cameraRotation.x+=l/r.angularSensibility,r.previousPosition={x:a.clientX,y:a.clientY},i||a.preventDefault()}}),this._onMouseMove=function(e){if(n.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,o=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;r.camera.getScene().useRightHandedSystem?r.camera.cameraRotation.y-=t/r.angularSensibility:r.camera.cameraRotation.y+=t/r.angularSensibility,r.camera.cameraRotation.x+=o/r.angularSensibility,r.previousPosition=null,i||e.preventDefault()}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),t.addEventListener("mousemove",this._onMouseMove,!1)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),e.removeEventListener("mousemove",this._onMouseMove),this._observer=null,this._onMouseMove=null,this.previousPosition=null)},t.prototype.getTypeName=function(){return"FreeCameraMouseInput"},t.prototype.getSimpleName=function(){return"mouse"},__decorate([e.serialize()],t.prototype,"buttons",void 0),__decorate([e.serialize()],t.prototype,"angularSensibility",void 0),t})();e.FreeCameraMouseInput=t,e.CameraInputTypes.FreeCameraMouseInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._keys=[],this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39]}return t.prototype.attachControl=function(t,i){var r=this;this._onKeyDown||(t.tabIndex=1,this._onKeyDown=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t===-1&&r._keys.push(e.keyCode),i||e.preventDefault()}},this._onKeyUp=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t>=0&&r._keys.splice(t,1),i||e.preventDefault()}},t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]))},t.prototype.detachControl=function(t){this._onKeyDown&&(t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),this._keys=[],this._onKeyDown=null,this._onKeyUp=null)},t.prototype.checkInputs=function(){if(this._onKeyDown)for(var t=this.camera,i=0;i<this._keys.length;i++){var r=this._keys[i],n=t._computeLocalCameraSpeed();this.keysLeft.indexOf(r)!==-1?t._localDirection.copyFromFloats(-n,0,0):this.keysUp.indexOf(r)!==-1?t._localDirection.copyFromFloats(0,0,n):this.keysRight.indexOf(r)!==-1?t._localDirection.copyFromFloats(n,0,0):this.keysDown.indexOf(r)!==-1&&t._localDirection.copyFromFloats(0,0,-n),t.getScene().useRightHandedSystem&&(t._localDirection.z*=-1),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),e.Vector3.TransformNormalToRef(t._localDirection,t._cameraTransformMatrix,t._transformedDirection),t.cameraDirection.addInPlace(t._transformedDirection)}},t.prototype.getTypeName=function(){return"FreeCameraKeyboardMoveInput"},t.prototype._onLostFocus=function(e){this._keys=[]},t.prototype.getSimpleName=function(){return"keyboard"},__decorate([e.serialize()],t.prototype,"keysUp",void 0),__decorate([e.serialize()],t.prototype,"keysDown",void 0),__decorate([e.serialize()],t.prototype,"keysLeft",void 0),__decorate([e.serialize()],t.prototype,"keysRight",void 0),t})();e.FreeCameraKeyboardMoveInput=t,e.CameraInputTypes.FreeCameraKeyboardMoveInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerCount=0,this._pointerPressed=[],this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r,n=this;void 0===this._pointerInput&&(this._onLostFocus=function(e){n._offsetX=null,n._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),n._pointerPressed.push(s.pointerId),1!==n._pointerPressed.length)return;r={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=n._pointerPressed.indexOf(s.pointerId);if(a===-1)return;if(n._pointerPressed.splice(a,1),0!=a)return;r=null,n._offsetX=null,n._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!r)return;var a=n._pointerPressed.indexOf(s.pointerId);if(0!=a)return;n._offsetX=s.clientX-r.x,n._offsetY=-(s.clientY-r.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null,this._pointerPressed=[],this._offsetX=null,this._offsetY=null,this._pointerCount=0)},t.prototype.checkInputs=function(){if(this._offsetX){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getTypeName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},__decorate([e.serialize()],t.prototype,"touchAngularSensibility",void 0),__decorate([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){var t=this;this._screenOrientationAngle=0,this._screenQuaternion=new e.Quaternion,this._alpha=0,this._beta=0,this._gamma=0,this._orientationChanged=function(){t._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,t._screenOrientationAngle=-e.Tools.ToRadians(t._screenOrientationAngle/2),t._screenQuaternion.copyFromFloats(0,Math.sin(t._screenOrientationAngle),0,Math.cos(t._screenOrientationAngle))},this._deviceOrientation=function(e){t._alpha=e.alpha,t._beta=e.beta,t._gamma=e.gamma},this._constantTranform=new e.Quaternion((-Math.sqrt(.5)),0,0,Math.sqrt(.5)),this._orientationChanged()}return Object.defineProperty(t.prototype,"camera",{get:function(){return this._camera},set:function(t){this._camera=t,this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new e.Quaternion)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){window.addEventListener("orientationchange",this._orientationChanged),window.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()},t.prototype.detachControl=function(e){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation)},t.prototype.checkInputs=function(){this._alpha&&(e.Quaternion.RotationYawPitchRollToRef(e.Tools.ToRadians(this._alpha),e.Tools.ToRadians(this._beta),-e.Tools.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)},t.prototype.getTypeName=function(){return"FreeCameraDeviceOrientationInput"},t.prototype.getSimpleName=function(){return"deviceOrientation"},t})();e.FreeCameraDeviceOrientationInput=t,e.CameraInputTypes.FreeCameraDeviceOrientationInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this;this._gamepads=new e.Gamepads(function(e){r._onNewGameConnected(e)})},t.prototype.detachControl=function(e){this._gamepads&&this._gamepads.dispose(),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var t=this.camera,i=this.gamepad.leftStick,r=i.x/this.gamepadMoveSensibility,n=i.y/this.gamepadMoveSensibility;i.x=Math.abs(r)>.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick,s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0;var h=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),c=50*t._computeLocalCameraSpeed(),l=e.Vector3.TransformCoordinates(new e.Vector3(i.x*c,0,-i.y*c),h);t.cameraDirection=t.cameraDirection.add(l),t.cameraRotation=t.cameraRotation.add(new e.Vector2(o.y,o.x))}},t.prototype._onNewGameConnected=function(e){0===e.index&&(this.gamepad=e)},t.prototype.getTypeName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},__decorate([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),__decorate([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._keys=[],this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39]}return t.prototype.attachControl=function(t,i){var r=this;t.tabIndex=1,this._onKeyDown=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t===-1&&r._keys.push(e.keyCode),e.preventDefault&&(i||e.preventDefault())}},this._onKeyUp=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t>=0&&r._keys.splice(t,1),e.preventDefault&&(i||e.preventDefault())}},this._onLostFocus=function(){r._keys=[]},t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){t&&(t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp)),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),this._keys=[],this._onKeyDown=null,this._onKeyUp=null,this._onLostFocus=null},t.prototype.checkInputs=function(){if(this._onKeyDown)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t];this.keysLeft.indexOf(i)!==-1?e.inertialAlphaOffset-=.01:this.keysUp.indexOf(i)!==-1?e.inertialBetaOffset-=.01:this.keysRight.indexOf(i)!==-1?e.inertialAlphaOffset+=.01:this.keysDown.indexOf(i)!==-1&&(e.inertialBetaOffset+=.01)}},t.prototype.getTypeName=function(){return"ArcRotateCameraKeyboardMoveInput"},t.prototype.getSimpleName=function(){return"keyboard"},__decorate([e.serialize()],t.prototype,"keysUp",void 0),__decorate([e.serialize()],t.prototype,"keysDown",void 0),__decorate([e.serialize()],t.prototype,"keysLeft",void 0),__decorate([e.serialize()],t.prototype,"keysRight",void 0),t})();e.ArcRotateCameraKeyboardMoveInput=t,e.CameraInputTypes.ArcRotateCameraKeyboardMoveInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.wheelPrecision=3}return t.prototype.attachControl=function(t,i){var r=this;this._wheel=function(t,n){if(t.type===e.PointerEventTypes.POINTERWHEEL){var o=t.event,s=0;o.wheelDelta?s=o.wheelDelta/(40*r.wheelPrecision):o.detail&&(s=-o.detail/r.wheelPrecision),s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getTypeName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},__decorate([e.serialize()],t.prototype,"wheelPrecision",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(e.Tools.GetPointerPrefix(),(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=6,this.panningSensibility=50,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n,o,s=this,a=this.camera.getEngine(),h=0;this._pointerInput=function(a,c){var l=a.event;if(a.type===e.PointerEventTypes.POINTERMOVE||s.buttons.indexOf(l.button)!==-1)if(a.type===e.PointerEventTypes.POINTERDOWN){try{l.srcElement.setPointerCapture(l.pointerId)}catch(u){}s._isPanClick=l.button===s.camera._panningMouseButton,r={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType},void 0===n?n=r:void 0===o&&(o=r),i||(l.preventDefault(),t.focus())}else if(a.type===e.PointerEventTypes.POINTERUP){try{l.srcElement.releasePointerCapture(l.pointerId)}catch(u){}r=null,h=0,n=o=void 0,i||l.preventDefault()}else if(a.type===e.PointerEventTypes.POINTERMOVE)if(i||l.preventDefault(),n&&void 0===o){if(0!==s.panningSensibility&&(l.ctrlKey&&s.camera._useCtrlForPanning||!s.camera._useCtrlForPanning&&s._isPanClick))s.camera.inertialPanningX+=-(l.clientX-r.x)/s.panningSensibility,s.camera.inertialPanningY+=(l.clientY-r.y)/s.panningSensibility;else{var d=l.clientX-r.x,f=l.clientY-r.y;s.camera.inertialAlphaOffset-=d/s.angularSensibilityX,s.camera.inertialBetaOffset-=f/s.angularSensibilityY}r.x=l.clientX,r.y=l.clientY}else if(n&&o){var p=n.pointerId===l.pointerId?n:o;p.x=l.clientX,p.y=l.clientY;var m=s.pinchInwards?1:-1,_=n.x-o.x,g=n.y-o.y,v=_*_+g*g;if(0===h)return void(h=v);v!==h&&(s.camera.inertialRadiusOffset+=(v-h)/(s.pinchPrecision*((s.angularSensibilityX+s.angularSensibilityY)/2)*m),h=v)}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){n=o=void 0,h=0,r=null},this._onMouseMove=function(e){if(a.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;s.camera.inertialAlphaOffset-=t/s.angularSensibilityX,s.camera.inertialBetaOffset-=r/s.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(s._MSGestureHandler||(s._MSGestureHandler=new MSGesture,s._MSGestureHandler.target=t),s._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){s.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,t.removeEventListener("contextmenu",this._onContextMenu),t.removeEventListener("mousemove",this._onMouseMove),t.removeEventListener("MSPointerDown",this._onGestureStart),t.removeEventListener("MSGestureChange",this._onGesture),t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),this._isPanClick=!1,this.pinchInwards=!0,this._onKeyDown=null,this._onKeyUp=null,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.getTypeName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},__decorate([e.serialize()],t.prototype,"buttons",void 0),__decorate([e.serialize()],t.prototype,"angularSensibilityX",void 0),__decorate([e.serialize()],t.prototype,"angularSensibilityY",void 0),__decorate([e.serialize()],t.prototype,"pinchPrecision",void 0),__decorate([e.serialize()],t.prototype,"panningSensibility",void 0),t})());e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this;this._gamepads=new e.Gamepads(function(e){r._onNewGameConnected(e)})},t.prototype.detachControl=function(e){this._gamepads&&this._gamepads.dispose(),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}var n=this.gamepad.leftStick;if(0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype._onNewGameConnected=function(e){0===e.index&&(this.gamepad=e)},t.prototype.getTypeName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},__decorate([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),__decorate([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.alphaCorrection=1,this.betaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._beta=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}return e.prototype.attachControl=function(e,t){this.camera.attachControl(e,t),window.addEventListener("deviceorientation",this._deviceOrientationHandler);
},e.prototype._onOrientationEvent=function(e){this.camera;this._alpha=0|+e.alpha,this._beta=0|+e.beta,this._gamma=0|+e.gamma,this._dirty=!0},e.prototype.checkInputs=function(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)},e.prototype.detachControl=function(e){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype.getTypeName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"VRDeviceOrientation"},e})();e.ArcRotateCameraVRDeviceOrientationInput=t,e.CameraInputTypes.ArcRotateCameraVRDeviceOrientationInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,r,n),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0),this.rotation=new e.Vector3(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.lockedTarget=null,this._currentTarget=e.Vector3.Zero(),this._viewMatrix=e.Matrix.Zero(),this._camMatrix=e.Matrix.Zero(),this._cameraTransformMatrix=e.Matrix.Zero(),this._cameraRotationMatrix=e.Matrix.Zero(),this._referencePoint=new e.Vector3(0,0,1),this._defaultUpVector=new e.Vector3(0,1,0),this._transformedReferencePoint=e.Vector3.Zero(),this._lookAtTemp=e.Matrix.Zero(),this._tempMatrix=e.Matrix.Zero()}return __extends(i,t),i.prototype.getFrontPosition=function(e){var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this._defaultUpVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r&&(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,!this.noRotationConstraint)){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}i&&(Math.abs(this.cameraDirection.x)<e.Epsilon&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<e.Epsilon&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<e.Epsilon&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),r&&(Math.abs(this.cameraRotation.x)<e.Epsilon&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<e.Epsilon&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),t.prototype._checkInputs.call(this)},i.prototype._updateCameraRotationMatrix=function(){this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix),e.Vector3.TransformNormalToRef(this._defaultUpVector,this._cameraRotationMatrix,this.upVector)):e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)},i.prototype._getViewMatrix=function(){return this.lockedTarget?this._currentTarget.copyFrom(this._getLockedTargetPosition()):(this._updateCameraRotationMatrix(),e.Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget)),this.getScene().useRightHandedSystem?e.Matrix.LookAtRHToRef(this.position,this._currentTarget,this.upVector,this._viewMatrix):e.Matrix.LookAtLHToRef(this.position,this._currentTarget,this.upVector,this._viewMatrix),this._viewMatrix},i.prototype.createRigCamera=function(t,r){if(this.cameraRigMode!==e.Camera.RIG_MODE_NONE){var n=new i(t,this.position.clone(),this.getScene());return this.cameraRigMode!==e.Camera.RIG_MODE_VR&&this.cameraRigMode!==e.Camera.RIG_MODE_WEBVR||(this.rotationQuaternion||(this.rotationQuaternion=new e.Quaternion),n._cameraRigParams={},n.rotationQuaternion=new e.Quaternion),n}return null},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:var n=this.cameraRigMode===e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,o=this.cameraRigMode===e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle*n,i.position),this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle*o,r.position),i.setTarget(this.getTarget()),r.setTarget(this.getTarget());break;case e.Camera.RIG_MODE_VR:case e.Camera.RIG_MODE_WEBVR:i.rotationQuaternion?(i.rotationQuaternion.copyFrom(this.rotationQuaternion),r.rotationQuaternion.copyFrom(this.rotationQuaternion)):(i.rotation.copyFrom(this.rotation),r.rotation.copyFrom(this.rotation)),i.position.copyFrom(this.position),r.position.copyFrom(this.position)}t.prototype._updateRigCameras.call(this)},i.prototype._getRigCamPosition=function(t,i){this._rigCamTransformMatrix||(this._rigCamTransformMatrix=new e.Matrix);var r=this.getTarget();e.Matrix.Translation(-r.x,-r.y,-r.z).multiplyToRef(e.Matrix.RotationY(t),this._rigCamTransformMatrix),this._rigCamTransformMatrix=this._rigCamTransformMatrix.multiply(e.Matrix.Translation(r.x,r.y,r.z)),e.Vector3.TransformCoordinatesToRef(this.position,this._rigCamTransformMatrix,i)},i.prototype.getTypeName=function(){return"TargetCamera"},__decorate([e.serializeAsVector3()],i.prototype,"rotation",void 0),__decorate([e.serialize()],i.prototype,"speed",void 0),__decorate([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.Camera);e.TargetCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){var o=this;t.call(this,i,r,n),this.ellipsoid=new e.Vector3(.5,1,.5),this.checkCollisions=!1,this.applyGravity=!1,this._collider=new e.Collider,this._needMoveForGravity=!1,this._oldPosition=e.Vector3.Zero(),this._diffPosition=e.Vector3.Zero(),this._newPosition=e.Vector3.Zero(),this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),o.getScene().workerCollisions&&i.multiplyInPlace(o._collider.radius);var n=function(t){o._newPosition.copyFrom(t),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition);o.position.clone();o._diffPosition.length()>e.Engine.CollisionsEpsilon&&(o.position.addInPlace(o._diffPosition),o.onCollide&&r&&o.onCollide(r))};n(i)},this.inputs=new e.FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}return __extends(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;if(e)return e.angularSensibility},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysUp},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysDown},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysLeft},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysRight},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._collider.radius=this.ellipsoid;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):this.position.addInPlace(this.cameraDirection)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getTypeName=function(){return"FreeCamera"},__decorate([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),__decorate([e.serialize()],i.prototype,"checkCollisions",void 0),__decorate([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e){t.call(this,e)}return __extends(i,t),i.prototype.addKeyboard=function(){return this.add(new e.FreeCameraKeyboardMoveInput),this},i.prototype.addMouse=function(t){return void 0===t&&(t=!0),this.add(new e.FreeCameraMouseInput(t)),this},i.prototype.addGamepad=function(){return this.add(new e.FreeCameraGamepadInput),this},i.prototype.addDeviceOrientation=function(){return this.add(new e.FreeCameraDeviceOrientationInput),this},i.prototype.addTouch=function(){return this.add(new e.FreeCameraTouchInput),this},i.prototype.addVirtualJoystick=function(){return this.add(new e.FreeCameraVirtualJoystickInput),this},i})(e.CameraInputsManager);e.FreeCameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n){t.call(this,e,i,r),this.radius=12,this.rotationOffset=0,this.heightOffset=4,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=n}return __extends(i,t),i.prototype.getRadians=function(e){return e*Math.PI/180},i.prototype.follow=function(t){if(t){var i;if(t.rotationQuaternion){var r=new e.Matrix;t.rotationQuaternion.toRotationMatrix(r),i=Math.atan2(r.m[8],r.m[10])}else i=t.rotation.y;var n=this.getRadians(this.rotationOffset)+i,o=t.position.x+Math.sin(n)*this.radius,s=t.position.z+Math.cos(n)*this.radius,a=o-this.position.x,h=t.position.y+this.heightOffset-this.position.y,c=s-this.position.z,l=a*this.cameraAcceleration*2,u=h*this.cameraAcceleration,d=c*this.cameraAcceleration*2;(l>this.maxCameraSpeed||l<-this.maxCameraSpeed)&&(l=l<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+l,this.position.y+u,this.position.z+d),this.setTarget(t.position)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow(this.lockedTarget)},i.prototype.getTypeName=function(){return"FollowCamera"},__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serialize()],i.prototype,"rotationOffset",void 0),__decorate([e.serialize()],i.prototype,"heightOffset",void 0),__decorate([e.serialize()],i.prototype,"cameraAcceleration",void 0),__decorate([e.serialize()],i.prototype,"maxCameraSpeed",void 0),__decorate([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){t.call(this,i,e.Vector3.Zero(),a),this.alpha=r,this.beta=n,this.radius=o,this.target=s,this._cartesianCoordinates=e.Vector3.Zero(),this.follow()}return __extends(i,t),i.prototype.follow=function(){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta),this.position=this.target.position.add(this._cartesianCoordinates),this.setTarget(this.target.position)},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getTypeName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addTouch(),this._setupInputs()}return __extends(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;if(e)return e.touchAngularSensibility},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;if(e)return e.touchMoveSensibility},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getTypeName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;t.call(this,i,e.Vector3.Zero(),a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.zoomOnFactor=1,this.targetScreenOffset=e.Vector2.Zero(),this.allowUpsideDown=!0,this._viewMatrix=new e.Matrix,this.panningAxis=new e.Vector3(1,1,0),this.checkCollisions=!1,this.collisionRadius=new e.Vector3(.5,.5,.5),this._collider=new e.Collider,this._previousPosition=e.Vector3.Zero(),this._collisionVelocity=e.Vector3.Zero(),this._newPosition=e.Vector3.Zero(),this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),h.getScene().workerCollisions&&h.checkCollisions&&i.multiplyInPlace(h._collider.radius),r?(h.setPosition(i),h.onCollide&&h.onCollide(r)):h._previousPosition.copyFrom(h.position);var n=Math.cos(h.alpha),o=Math.sin(h.alpha),s=Math.cos(h.beta),a=Math.sin(h.beta);0===a&&(a=1e-4);var c=h._getTargetPosition();c.addToRef(new e.Vector3(h.radius*n*a,h.radius*s,h.radius*o*a),h._newPosition),h.position.copyFrom(h._newPosition);var l=h.upVector;h.allowUpsideDown&&h.beta<0&&(l=l.clone(),l=l.negate()),e.Matrix.LookAtLHToRef(h.position,c,l,h._viewMatrix),h._viewMatrix.m[12]+=h.targetScreenOffset.x,h._viewMatrix.m[13]+=h.targetScreenOffset.y,h._collisionTriggered=!1},s?this.target=s:this.target=e.Vector3.Zero(),this.alpha=r,this.beta=n,this.radius=o,this.getViewMatrix(),this.inputs=new e.ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad()}return __extends(i,t),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.angularSensibilityX},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.angularSensibilityY},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.pinchPrecision},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.panningSensibility},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysUp},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysDown},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysLeft},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysRight},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;if(e)return e.wheelPrecision},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache.target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this.target.getAbsolutePosition){var e=this.target.getAbsolutePosition();return this._targetBoundingCenter?e.add(this._targetBoundingCenter):e}return this.target},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache.target.equals(this.target)&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){this._collisionTriggered||(this.inputs.checkInputs(),0===this.inertialAlphaOffset&&0===this.inertialBetaOffset&&0===this.inertialRadiusOffset||(this.getScene().useRightHandedSystem?this.alpha-=this.beta<=0?-this.inertialAlphaOffset:this.inertialAlphaOffset:this.alpha+=this.beta<=0?-this.inertialAlphaOffset:this.inertialAlphaOffset,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<e.Epsilon&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<e.Epsilon&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<e.Epsilon&&(this.inertialRadiusOffset=0)),0===this.inertialPanningX&&0===this.inertialPanningY||(this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inertialPanningX*=this.inertia,this.inertialPanningY*=this.inertia,Math.abs(this.inertialPanningX)<e.Epsilon&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<e.Epsilon&&(this.inertialPanningY=0),this._localDirection.copyFromFloats(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY),this._localDirection.multiplyInPlace(this.panningAxis),this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.Vector3.TransformNormalToRef(this._localDirection,this._cameraTransformMatrix,this._transformedDirection),this.panningAxis.y||(this._transformedDirection.y=0),this.target.getAbsolutePosition||this.target.addInPlace(this._transformedDirection)),this._checkLimits(),t.prototype._checkInputs.call(this))},i.prototype._checkLimits=function(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){var e=this.position.subtract(this._getTargetPosition());this.radius=e.length(),this.alpha=Math.acos(e.x/Math.sqrt(Math.pow(e.x,2)+Math.pow(e.z,2))),e.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(e.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t){void 0===t&&(t=!1),this._getTargetPosition().equals(e)||(t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.center.clone():this._targetBoundingCenter=null,this.target=e,this.rebuildAnglesAndRadius())},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(o.addToRef(new e.Vector3(this.radius*t*n,this.radius*r,this.radius*i*n),this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider.radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0,this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&this.beta<0&&(s=s.clone(),s=s.negate()),this.getScene().useRightHandedSystem?e.Matrix.LookAtRHToRef(this.position,o,s,this._viewMatrix):e.Matrix.LookAtLHToRef(this.position,o,s,this._viewMatrix),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;void 0===t.min?(r=t||this.getScene().meshes,r=e.Mesh.MinMax(r),n=e.Vector3.Distance(r.min,r.max)):(r=t,n=t.distance),this.target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this.target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getTypeName=function(){return"ArcRotateCamera"},__decorate([e.serialize()],i.prototype,"alpha",void 0),__decorate([e.serialize()],i.prototype,"beta",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serializeAsVector3()],i.prototype,"target",void 0),__decorate([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),__decorate([e.serialize()],i.prototype,"inertialBetaOffset",void 0),__decorate([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),__decorate([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),__decorate([e.serialize()],i.prototype,"upperAlphaLimit",void 0),__decorate([e.serialize()],i.prototype,"lowerBetaLimit",void 0),__decorate([e.serialize()],i.prototype,"upperBetaLimit",void 0),__decorate([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),__decorate([e.serialize()],i.prototype,"upperRadiusLimit",void 0),__decorate([e.serialize()],i.prototype,"inertialPanningX",void 0),__decorate([e.serialize()],i.prototype,"inertialPanningY",void 0),__decorate([e.serialize()],i.prototype,"zoomOnFactor",void 0),__decorate([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e){t.call(this,e)}return __extends(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addGamepad=function(){return this.add(new e.ArcRotateCameraGamepadInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderinGroupInfo=null,this._scene=e;for(var i=t.MIN_RENDERINGGROUPS;i<t.MAX_RENDERINGGROUPS;i++)this._autoClearDepthStencil[i]=!0}return t.prototype._renderParticles=function(e,t){if(0!==this._scene._activeParticleSystems.length){var i=this._scene.activeCamera;this._scene._particlesDuration.beginMonitoring();for(var r=0;r<this._scene._activeParticleSystems.length;r++){var n=this._scene._activeParticleSystems.data[r];n.renderingGroupId===e&&0!==(i.layerMask&n.layerMask)&&(this._clearDepthStencilBuffer(),n.emitter.position&&t&&t.indexOf(n.emitter)===-1||this._scene._activeParticles.addCount(n.render(),!1))}this._scene._particlesDuration.endMonitoring(!1)}},t.prototype._renderSprites=function(e){if(this._scene.spritesEnabled&&0!==this._scene.spriteManagers.length){var t=this._scene.activeCamera;this._scene._spritesDuration.beginMonitoring();for(var i=0;i<this._scene.spriteManagers.length;i++){var r=this._scene.spriteManagers[i];r.renderingGroupId===e&&0!==(t.layerMask&r.layerMask)&&(this._clearDepthStencilBuffer(),r.render())}this._scene._spritesDuration.endMonitoring(!1)}},t.prototype._clearDepthStencilBuffer=function(){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(0,!1,!0,!0),this._depthStencilBufferAlreadyCleaned=!0)},t.prototype._renderSpritesAndParticles=function(){this._currentRenderSprites&&this._renderSprites(this._currentIndex),this._currentRenderParticles&&this._renderParticles(this._currentIndex,this._currentActiveMeshes)},t.prototype.render=function(i,r,n,o){var s=this._scene.onRenderingGroupObservable.hasObservers()?this._scene.onRenderingGroupObservable:null,a=null;s&&(this._renderinGroupInfo||(this._renderinGroupInfo=new e.RenderingGroupInfo),a=this._renderinGroupInfo,a.scene=this._scene,a.camera=this._scene.activeCamera),this._currentActiveMeshes=r,this._currentRenderParticles=n,this._currentRenderSprites=o;for(var h=t.MIN_RENDERINGGROUPS;h<t.MAX_RENDERINGGROUPS;h++){this._depthStencilBufferAlreadyCleaned=h===t.MIN_RENDERINGGROUPS;var c=this._renderingGroups[h],l=!1;if(this._currentIndex=h,c){var u=0;s&&(u=Math.pow(2,h),a.renderStage=e.RenderingGroupInfo.STAGE_PRECLEAR,a.renderingGroupId=h,s.notifyObservers(a,u)),this._autoClearDepthStencil[h]&&this._clearDepthStencilBuffer(),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_PREOPAQUE,s.notifyObservers(a,u)),c.onBeforeTransparentRendering||(c.onBeforeTransparentRendering=this._renderSpritesAndParticles.bind(this)),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_PRETRANSPARENT,s.notifyObservers(a,u)),c.render(i)||(this._renderingGroups.splice(h,1),l=!0,this._renderSpritesAndParticles()),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_POSTTRANSPARENT,s.notifyObservers(a,u))}else if(this._renderSpritesAndParticles(),s){var u=Math.pow(2,h);a.renderStage=e.RenderingGroupInfo.STAGE_PRECLEAR,
a.renderingGroupId=h,s.notifyObservers(a,u),a.renderStage=e.RenderingGroupInfo.STAGE_POSTTRANSPARENT,s.notifyObservers(a,u)}l&&h--}},t.prototype.reset=function(){for(var e=t.MIN_RENDERINGGROUPS;e<t.MAX_RENDERINGGROUPS;e++){var i=this._renderingGroups[e];i&&i.prepare()}},t.prototype.dispatch=function(t){var i=t.getMesh(),r=i.renderingGroupId||0;this._renderingGroups[r]||(this._renderingGroups[r]=new e.RenderingGroup(r,this._scene,this._customOpaqueSortCompareFn[r],this._customAlphaTestSortCompareFn[r],this._customTransparentSortCompareFn[r])),this._renderingGroups[r].dispatch(t)},t.prototype.setRenderingOrder=function(e,t,i,r){if(void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){var n=this._renderingGroups[e];n.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],n.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],n.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}},t.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._autoClearDepthStencil[e]=t},t.MAX_RENDERINGGROUPS=4,t.MIN_RENDERINGGROUPS=0,t})();e.RenderingManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=null),this.index=t,this._opaqueSubMeshes=new e.SmartArray(256),this._transparentSubMeshes=new e.SmartArray(256),this._alphaTestSubMeshes=new e.SmartArray(256),this._scene=i,this.opaqueSortCompareFn=r,this.alphaTestSortCompareFn=n,this.transparentSortCompareFn=o}return Object.defineProperty(t.prototype,"opaqueSortCompareFn",{set:function(e){this._opaqueSortCompareFn=e,e?this._renderOpaque=this.renderOpaqueSorted:this._renderOpaque=t.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"alphaTestSortCompareFn",{set:function(e){this._alphaTestSortCompareFn=e,e?this._renderAlphaTest=this.renderAlphaTestSorted:this._renderAlphaTest=t.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transparentSortCompareFn",{set:function(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=t.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!0,configurable:!0}),t.prototype.render=function(t){if(t)return t(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes),!0;if(0===this._opaqueSubMeshes.length&&0===this._alphaTestSubMeshes.length&&0===this._transparentSubMeshes.length)return this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),!1;var i=this._scene.getEngine();return this._renderOpaque(this._opaqueSubMeshes),i.setAlphaTesting(!0),this._renderAlphaTest(this._alphaTestSubMeshes),i.setAlphaTesting(!1),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),this._renderTransparent(this._transparentSubMeshes),i.setAlphaMode(e.Engine.ALPHA_DISABLE),!0},t.prototype.renderOpaqueSorted=function(e){return t.renderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera.globalPosition,!1)},t.prototype.renderAlphaTestSorted=function(e){return t.renderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera.globalPosition,!1)},t.prototype.renderTransparentSorted=function(e){return t.renderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera.globalPosition,!0)},t.renderSorted=function(e,t,i,r){for(var n,o=0;o<e.length;o++)n=e.data[o],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=n.getBoundingInfo().boundingSphere.centerWorld.subtract(i).length();var s=e.data.slice(0,e.length);for(s.sort(t),o=0;o<s.length;o++)n=s[o],n.render(r)},t.renderUnsorted=function(e){for(var t=0;t<e.length;t++){var i=e.data[t];i.render(!1)}},t.defaultTransparentSortCompare=function(e,i){return e._alphaIndex>i._alphaIndex?1:e._alphaIndex<i._alphaIndex?-1:t.backToFrontSortCompare(e,i)},t.backToFrontSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset()},t.prototype.dispatch=function(e){var t=e.getMaterial(),i=e.getMesh();t.needAlphaBlending()||i.visibility<1||i.hasVertexAlpha?this._transparentSubMeshes.push(e):t.needAlphaTesting()?this._alphaTestSubMeshes.push(e):this._opaqueSubMeshes.push(e)},t})();e.RenderingGroup=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return Object.defineProperty(e,"POINTERDOWN",{get:function(){return e._POINTERDOWN},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERUP",{get:function(){return e._POINTERUP},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERMOVE",{get:function(){return e._POINTERMOVE},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERWHEEL",{get:function(){return e._POINTERWHEEL},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERPICK",{get:function(){return e._POINTERPICK},enumerable:!0,configurable:!0}),e._POINTERDOWN=1,e._POINTERUP=2,e._POINTERMOVE=4,e._POINTERWHEEL=8,e._POINTERPICK=16,e})();e.PointerEventTypes=t;var i=(function(){function e(e,t){this.type=e,this.event=t}return e})();e.PointerInfoBase=i;var r=(function(t){function i(i,r,n,o){t.call(this,i,r),this.skipOnPointerObservable=!1,this.localPosition=new e.Vector2(n,o)}return __extends(i,t),i})(i);e.PointerInfoPre=r;var n=(function(e){function t(t,i,r){e.call(this,t,i),this.pickInfo=r}return __extends(t,e),t})(i);e.PointerInfo=n;var o=(function(){function e(){}return e.STAGE_PRECLEAR=1,e.STAGE_PREOPAQUE=2,e.STAGE_PRETRANSPARENT=3,e.STAGE_POSTTRANSPARENT=4,e})();e.RenderingGroupInfo=o;var s=(function(){function i(t){this.autoClear=!0,this.clearColor=new e.Color3(.2,.2,.3),this.ambientColor=new e.Color3(0,0,0),this.forceWireframe=!1,this.forcePointsCloud=!1,this.forceShowBoundingBoxes=!1,this.animationsEnabled=!0,this.constantlyUpdateMeshUnderPointer=!1,this.useRightHandedSystem=!1,this.hoverCursor="pointer",this.metadata=null,this.onDisposeObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onReadyObservable=new e.Observable,this.onBeforeCameraRenderObservable=new e.Observable,this.onAfterCameraRenderObservable=new e.Observable,this.onNewCameraAddedObservable=new e.Observable,this.onCameraRemovedObservable=new e.Observable,this.onNewLightAddedObservable=new e.Observable,this.onLightRemovedObservable=new e.Observable,this.onNewGeometryAddedObservable=new e.Observable,this.onGeometryRemovedObservable=new e.Observable,this.onNewMeshAddedObservable=new e.Observable,this.onMeshRemovedObservable=new e.Observable,this.onRenderingGroupObservable=new e.Observable,this.animations=[],this.onPrePointerObservable=new e.Observable,this.onPointerObservable=new e.Observable,this.cameraToUseForPointers=null,this._startingPointerPosition=new e.Vector2(0,0),this._startingPointerTime=0,this.fogEnabled=!0,this.fogMode=i.FOGMODE_NONE,this.fogColor=new e.Color3(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.shadowsEnabled=!0,this.lightsEnabled=!0,this.lights=new Array,this.cameras=new Array,this.activeCameras=new Array,this.meshes=new Array,this._geometries=new Array,this.materials=new Array,this.multiMaterials=new Array,this.texturesEnabled=!0,this.textures=new Array,this.particlesEnabled=!0,this.particleSystems=new Array,this.spritesEnabled=!0,this.spriteManagers=new Array,this.layers=new Array,this.highlightLayers=new Array,this.skeletonsEnabled=!0,this.skeletons=new Array,this.lensFlaresEnabled=!0,this.lensFlareSystems=new Array,this.collisionsEnabled=!0,this.gravity=new e.Vector3(0,(-9.807),0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this.reflectionProbes=new Array,this._actionManagers=new Array,this._meshesForIntersections=new e.SmartArray(256),this.proceduralTexturesEnabled=!0,this._proceduralTextures=new Array,this.soundTracks=new Array,this._audioEnabled=!0,this._headphone=!1,this._totalMeshesCounter=new e.PerfCounter,this._totalLightsCounter=new e.PerfCounter,this._totalMaterialsCounter=new e.PerfCounter,this._totalTexturesCounter=new e.PerfCounter,this._totalVertices=new e.PerfCounter,this._activeIndices=new e.PerfCounter,this._activeParticles=new e.PerfCounter,this._lastFrameDuration=new e.PerfCounter,this._evaluateActiveMeshesDuration=new e.PerfCounter,this._renderTargetsDuration=new e.PerfCounter,this._particlesDuration=new e.PerfCounter,this._renderDuration=new e.PerfCounter,this._spritesDuration=new e.PerfCounter,this._activeBones=new e.PerfCounter,this._renderId=0,this._executeWhenReadyTimeoutId=-1,this._intermediateRendering=!1,this._toBeDisposed=new e.SmartArray(256),this._pendingData=[],this._activeMeshes=new e.SmartArray(256),this._processedMaterials=new e.SmartArray(256),this._renderTargets=new e.SmartArray(256),this._activeParticleSystems=new e.SmartArray(256),this._activeSkeletons=new e.SmartArray(32),this._softwareSkinnedMeshes=new e.SmartArray(32),this._activeAnimatables=new Array,this._transformMatrix=e.Matrix.Zero(),this._edgesRenderers=new e.SmartArray(16),this._uniqueIdCounter=0,this._engine=t,t.scenes.push(this),this._externalData=new e.StringDictionary,this._uid=null,this._renderingManager=new e.RenderingManager(this),this.postProcessManager=new e.PostProcessManager(this),this.postProcessRenderPipelineManager=new e.PostProcessRenderPipelineManager,this._boundingBoxRenderer=new e.BoundingBoxRenderer(this),e.OutlineRenderer&&(this._outlineRenderer=new e.OutlineRenderer(this)),this.attachControl(),e.SoundTrack&&(this.mainSoundTrack=new e.SoundTrack(this,{mainTrack:!0})),e.SimplificationQueue&&(this.simplificationQueue=new e.SimplificationQueue),this.workerCollisions=!1}return Object.defineProperty(i,"FOGMODE_NONE",{get:function(){return i._FOGMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_EXP",{get:function(){return i._FOGMODE_EXP},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_EXP2",{get:function(){return i._FOGMODE_EXP2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_LINEAR",{get:function(){return i._FOGMODE_LINEAR},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"beforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"afterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"beforeCameraRender",{set:function(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"afterCameraRender",{set:function(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"unTranslatedPointer",{get:function(){return new e.Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"defaultMaterial",{get:function(){return this._defaultMaterial||(this._defaultMaterial=new e.StandardMaterial("default material",this)),this._defaultMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new e.DebugLayer(this)),this._debugLayer},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"workerCollisions",{get:function(){return this._workerCollisions},set:function(t){t=t&&!!Worker,this._workerCollisions=t,this.collisionCoordinator&&this.collisionCoordinator.destroy(),this.collisionCoordinator=t?new e.CollisionCoordinatorWorker:new e.CollisionCoordinatorLegacy,this.collisionCoordinator.init(this)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"SelectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"meshUnderPointer",{get:function(){return this._pointerOverMesh},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pointerX",{get:function(){return this._pointerX},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pointerY",{get:function(){return this._pointerY},enumerable:!0,configurable:!0}),i.prototype.getCachedMaterial=function(){return this._cachedMaterial},i.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer},i.prototype.getOutlineRenderer=function(){return this._outlineRenderer},i.prototype.getEngine=function(){return this._engine},i.prototype.getTotalVertices=function(){return this._totalVertices.current},Object.defineProperty(i.prototype,"totalVerticesPerfCounter",{get:function(){return this._totalVertices},enumerable:!0,configurable:!0}),i.prototype.getActiveIndices=function(){return this._activeIndices.current},Object.defineProperty(i.prototype,"totalActiveIndicesPerfCounter",{get:function(){return this._activeIndices},enumerable:!0,configurable:!0}),i.prototype.getActiveParticles=function(){return this._activeParticles.current},Object.defineProperty(i.prototype,"activeParticlesPerfCounter",{get:function(){return this._activeParticles},enumerable:!0,configurable:!0}),i.prototype.getActiveBones=function(){return this._activeBones.current},Object.defineProperty(i.prototype,"activeBonesPerfCounter",{get:function(){return this._activeBones},enumerable:!0,configurable:!0}),i.prototype.getLastFrameDuration=function(){return this._lastFrameDuration.current},Object.defineProperty(i.prototype,"lastFramePerfCounter",{get:function(){return this._lastFrameDuration},enumerable:!0,configurable:!0}),i.prototype.getEvaluateActiveMeshesDuration=function(){return this._evaluateActiveMeshesDuration.current},Object.defineProperty(i.prototype,"evaluateActiveMeshesDurationPerfCounter",{get:function(){return this._evaluateActiveMeshesDuration},enumerable:!0,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.getRenderTargetsDuration=function(){return this._renderTargetsDuration.current},i.prototype.getRenderDuration=function(){return this._renderDuration.current},Object.defineProperty(i.prototype,"renderDurationPerfCounter",{get:function(){return this._renderDuration},enumerable:!0,configurable:!0}),i.prototype.getParticlesDuration=function(){return this._particlesDuration.current},Object.defineProperty(i.prototype,"particlesDurationPerfCounter",{get:function(){return this._particlesDuration},enumerable:!0,configurable:!0}),i.prototype.getSpritesDuration=function(){return this._spritesDuration.current},Object.defineProperty(i.prototype,"spriteDuractionPerfCounter",{get:function(){return this._spritesDuration},enumerable:!0,configurable:!0}),i.prototype.getAnimationRatio=function(){return this._animationRatio},i.prototype.getRenderId=function(){return this._renderId},i.prototype.incrementRenderId=function(){this._renderId++},i.prototype._updatePointerPosition=function(e){var t=this._engine.getRenderingCanvasClientRect();this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY,this.cameraToUseForPointers&&(this._pointerX=this._pointerX-this.cameraToUseForPointers.viewport.x*this._engine.getRenderWidth(),this._pointerY=this._pointerY-this.cameraToUseForPointers.viewport.y*this._engine.getRenderHeight())},i.prototype.attachControl=function(i,o,s){var a=this;void 0===i&&(i=!0),void 0===o&&(o=!0),void 0===s&&(s=!0);var h=function(e){return e.isPickable&&e.actionManager&&e.actionManager.hasPointerTriggers};this._onPointerMove=function(e){if(a._updatePointerPosition(e),a.onPrePointerObservable.hasObservers()){var i="mousewheel"===e.type||"DOMMouseScroll"===e.type?t.POINTERWHEEL:t.POINTERMOVE,o=new r(i,e,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(o,i),o.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){var s=a._engine.getRenderingCanvas();a.pointerMovePredicate||(a.pointerMovePredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&(a.constantlyUpdateMeshUnderPointer||null!==e.actionManager&&void 0!==e.actionManager)});var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerMovePredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh?(a.setPointerOverSprite(null),a.setPointerOverMesh(c.pickedMesh),a._pointerOverMesh.actionManager&&a._pointerOverMesh.actionManager.hasPointerTriggers?a._pointerOverMesh.actionManager.hoverCursor?s.style.cursor=a._pointerOverMesh.actionManager.hoverCursor:s.style.cursor=a.hoverCursor:s.style.cursor=""):(a.setPointerOverMesh(null),c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite?(a.setPointerOverSprite(c.pickedSprite),a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor):(a.setPointerOverSprite(null),s.style.cursor="")),a.onPointerMove&&a.onPointerMove(e,c),a.onPointerObservable.hasObservers()){var i="mousewheel"===e.type||"DOMMouseScroll"===e.type?t.POINTERWHEEL:t.POINTERMOVE,o=new n(i,e,c);a.onPointerObservable.notifyObservers(o,i)}}},this._onPointerDown=function(i){if(a._updatePointerPosition(i),a.onPrePointerObservable.hasObservers()){var o=t.POINTERDOWN,s=new r(o,i,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(s,o),s.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){a._startingPointerPosition.x=a._pointerX,a._startingPointerPosition.y=a._pointerY,a._startingPointerTime=(new Date).getTime(),a.pointerDownPredicate||(a.pointerDownPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()}),a._pickedDownMesh=null;var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerDownPredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh&&c.pickedMesh.actionManager){if(a._pickedDownMesh=c.pickedMesh,c.pickedMesh.actionManager.hasPickTriggers){switch(i.button){case 0:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i));break;case 1:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i));break;case 2:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i))}c.pickedMesh.actionManager&&c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i))}if(c.pickedMesh.actionManager&&c.pickedMesh.actionManager.hasSpecificTrigger(e.ActionManager.OnLongPressTrigger)){var l=a;window.setTimeout((function(){var t=l.pick(l._unTranslatedPointerX,l._unTranslatedPointerY,(function(t){return t.isPickable&&t.isVisible&&t.isReady()&&t.actionManager&&t.actionManager.hasSpecificTrigger(e.ActionManager.OnLongPressTrigger)}),!1,l.cameraToUseForPointers);t.hit&&t.pickedMesh&&t.pickedMesh.actionManager&&0!==l._startingPointerTime&&(new Date).getTime()-l._startingPointerTime>e.ActionManager.LongPressDelay&&Math.abs(l._startingPointerPosition.x-l._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(l._startingPointerPosition.y-l._pointerY)<e.ActionManager.DragMovementThreshold&&(l._startingPointerTime=0,t.pickedMesh.actionManager.processTrigger(e.ActionManager.OnLongPressTrigger,e.ActionEvent.CreateNew(t.pickedMesh,i)))}),e.ActionManager.LongPressDelay)}}if(a.onPointerDown&&a.onPointerDown(i,c),a.onPointerObservable.hasObservers()){var o=t.POINTERDOWN,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}if(a._pickedDownSprite=null,a.spriteManagers.length>0&&(c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite&&c.pickedSprite.actionManager)){switch(a._pickedDownSprite=c.pickedSprite,i.button){case 0:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i));break;case 1:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i));break;case 2:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))}c.pickedSprite.actionManager&&c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))}}},this._onPointerUp=function(i){if(a._updatePointerPosition(i),a.onPrePointerObservable.hasObservers()){var o=t.POINTERUP,s=new r(o,i,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(s,o),s.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){a.pointerUpPredicate||(a.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()});var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerUpPredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh){if(null!=a._pickedDownMesh&&c.pickedMesh==a._pickedDownMesh&&(a.onPointerPick&&a.onPointerPick(i,c),a.onPointerObservable.hasObservers())){var o=t.POINTERPICK,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}c.pickedMesh.actionManager&&(c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i)),c.pickedMesh.actionManager&&Math.abs(a._startingPointerPosition.x-a._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(a._startingPointerPosition.y-a._pointerY)<e.ActionManager.DragMovementThreshold&&c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i)))}if(a._pickedDownMesh&&a._pickedDownMesh.actionManager&&a._pickedDownMesh!==c.pickedMesh&&a._pickedDownMesh.actionManager.processTrigger(e.ActionManager.OnPickOutTrigger,e.ActionEvent.CreateNew(a._pickedDownMesh,i)),a.onPointerUp&&a.onPointerUp(i,c),a.onPointerObservable.hasObservers()){var o=t.POINTERUP,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}a._startingPointerTime=0,a.spriteManagers.length>0&&(c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite&&c.pickedSprite.actionManager&&(c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i)),c.pickedSprite.actionManager&&Math.abs(a._startingPointerPosition.x-a._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(a._startingPointerPosition.y-a._pointerY)<e.ActionManager.DragMovementThreshold&&c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==c.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(e.ActionManager.OnPickOutTrigger,e.ActionEvent.CreateNewFromSprite(a._pickedDownSprite,a,i)))}},this._onKeyDown=function(t){a.actionManager&&a.actionManager.processTrigger(e.ActionManager.OnKeyDownTrigger,e.ActionEvent.CreateNewFromScene(a,t))},this._onKeyUp=function(t){a.actionManager&&a.actionManager.processTrigger(e.ActionManager.OnKeyUpTrigger,e.ActionEvent.CreateNewFromScene(a,t))};var c=e.Tools.GetPointerPrefix(),l=this._engine.getRenderingCanvas();s&&(l.addEventListener(c+"move",this._onPointerMove,!1),l.addEventListener("mousewheel",this._onPointerMove,!1),l.addEventListener("DOMMouseScroll",this._onPointerMove,!1)),o&&l.addEventListener(c+"down",this._onPointerDown,!1),i&&l.addEventListener(c+"up",this._onPointerUp,!1),l.tabIndex=1,l.addEventListener("keydown",this._onKeyDown,!1),l.addEventListener("keyup",this._onKeyUp,!1)},i.prototype.detachControl=function(){var t=e.Tools.GetPointerPrefix(),i=this._engine.getRenderingCanvas();i.removeEventListener(t+"move",this._onPointerMove),i.removeEventListener(t+"down",this._onPointerDown),i.removeEventListener(t+"up",this._onPointerUp),i.removeEventListener("mousewheel",this._onPointerMove),i.removeEventListener("DOMMouseScroll",this._onPointerMove),i.removeEventListener("keydown",this._onKeyDown),i.removeEventListener("keyup",this._onKeyUp)},i.prototype.isReady=function(){if(this._pendingData.length>0)return!1;var t;for(t=0;t<this._geometries.length;t++){var i=this._geometries[t];if(i.delayLoadState===e.Engine.DELAYLOADSTATE_LOADING)return!1}for(t=0;t<this.meshes.length;t++){var r=this.meshes[t];if(!r.isReady())return!1;var n=r.material;if(n&&!n.isReady(r))return!1}return!0},i.prototype.resetCachedMaterial=function(){this._cachedMaterial=null},i.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},i.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},i.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},i.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},i.prototype._addPendingData=function(e){this._pendingData.push(e)},i.prototype._removePendingData=function(e){var t=this._pendingData.indexOf(e);t!==-1&&this._pendingData.splice(t,1)},i.prototype.getWaitingItemsCount=function(){return this._pendingData.length},i.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),this._executeWhenReadyTimeoutId===-1&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},i.prototype._checkIsReady=function(){var e=this;return this.isReady()?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):void(this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150))},i.prototype.beginAnimation=function(t,i,r,n,o,s,a){if(void 0===o&&(o=1),this.stopAnimation(t),a||(a=new e.Animatable(this,t,i,r,n,o,s)),t.animations&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var h=t.getAnimatables(),c=0;c<h.length;c++)this.beginAnimation(h[c],i,r,n,o,s,a);return a.reset(),a},i.prototype.beginDirectAnimation=function(t,i,r,n,o,s,a){void 0===s&&(s=1);var h=new e.Animatable(this,t,r,n,o,s,a,i);return h},i.prototype.getAnimatableByTarget=function(e){for(var t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},Object.defineProperty(i.prototype,"Animatables",{get:function(){return this._activeAnimatables},enumerable:!0,configurable:!0}),i.prototype.stopAnimation=function(e,t){var i=this.getAnimatableByTarget(e);i&&i.stop(t)},i.prototype._animate=function(){if(this.animationsEnabled&&0!==this._activeAnimatables.length){if(!this._animationStartDate){if(this._pendingData.length>0)return;this._animationStartDate=e.Tools.Now}for(var t=e.Tools.Now,i=t-this._animationStartDate,r=0;r<this._activeAnimatables.length;r++)this._activeAnimatables[r]._animate(i)}},i.prototype.getViewMatrix=function(){return this._viewMatrix},i.prototype.getProjectionMatrix=function(){return this._projectionMatrix},i.prototype.getTransformMatrix=function(){return this._transformMatrix},i.prototype.setTransformMatrix=function(t,i){this._viewMatrix=t,this._projectionMatrix=i,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix)},i.prototype.addMesh=function(e){e.uniqueId=this._uniqueIdCounter++;this.meshes.push(e);this.collisionCoordinator.onMeshAdded(e),this.onNewMeshAddedObservable.notifyObservers(e)},i.prototype.removeMesh=function(e){var t=this.meshes.indexOf(e);return t!==-1&&this.meshes.splice(t,1),this.collisionCoordinator.onMeshRemoved(e),this.onMeshRemovedObservable.notifyObservers(e),t},i.prototype.removeSkeleton=function(e){var t=this.skeletons.indexOf(e);return t!==-1&&this.skeletons.splice(t,1),t},i.prototype.removeLight=function(e){var t=this.lights.indexOf(e);return t!==-1&&this.lights.splice(t,1),this.onLightRemovedObservable.notifyObservers(e),t},i.prototype.removeCamera=function(e){var t=this.cameras.indexOf(e);t!==-1&&this.cameras.splice(t,1);var i=this.activeCameras.indexOf(e);return i!==-1&&this.activeCameras.splice(i,1),this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},i.prototype.addLight=function(e){e.uniqueId=this._uniqueIdCounter++;this.lights.push(e);this.onNewLightAddedObservable.notifyObservers(e)},i.prototype.addCamera=function(e){e.uniqueId=this._uniqueIdCounter++;this.cameras.push(e);this.onNewCameraAddedObservable.notifyObservers(e)},i.prototype.switchActiveCamera=function(e,t){void 0===t&&(t=!0);var i=this._engine.getRenderingCanvas();this.activeCamera.detachControl(i),this.activeCamera=e,t&&e.attachControl(i)},i.prototype.setActiveCameraByID=function(e){var t=this.getCameraByID(e);return t?(this.activeCamera=t,t):null},i.prototype.setActiveCameraByName=function(e){var t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null},i.prototype.getMaterialByID=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].id===e)return this.materials[t];return null},i.prototype.getMaterialByName=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].name===e)return this.materials[t];return null},i.prototype.getLensFlareSystemByName=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},i.prototype.getLensFlareSystemByID=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},i.prototype.getCameraByID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null},i.prototype.getCameraByUniqueID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null},i.prototype.getCameraByName=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null},i.prototype.getBoneByID=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].id===e)return i.bones[r];return null},i.prototype.getBoneByName=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].name===e)return i.bones[r];return null},i.prototype.getLightByName=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null},i.prototype.getLightByID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null},i.prototype.getLightByUniqueID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];
return null},i.prototype.getParticleSystemByID=function(e){for(var t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null},i.prototype.getGeometryByID=function(e){for(var t=0;t<this._geometries.length;t++)if(this._geometries[t].id===e)return this._geometries[t];return null},i.prototype.pushGeometry=function(e,t){return!(!t&&this.getGeometryByID(e.id))&&(this._geometries.push(e),this.collisionCoordinator.onGeometryAdded(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)},i.prototype.removeGeometry=function(e){var t=this._geometries.indexOf(e);return t>-1&&(this._geometries.splice(t,1),this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},i.prototype.getGeometries=function(){return this._geometries},i.prototype.getMeshByID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null},i.prototype.getMeshesByID=function(e){return this.meshes.filter((function(t){return t.id===e}))},i.prototype.getMeshByUniqueID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null},i.prototype.getLastMeshByID=function(e){for(var t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},i.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},i.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);if(r)return r;var n=this.getBoneByID(e);return n},i.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);if(r)return r;var n=this.getBoneByName(e);return n},i.prototype.getMeshByName=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null},i.prototype.getSoundByName=function(t){var i;if(e.AudioEngine){for(i=0;i<this.mainSoundTrack.soundCollection.length;i++)if(this.mainSoundTrack.soundCollection[i].name===t)return this.mainSoundTrack.soundCollection[i];for(var r=0;r<this.soundTracks.length;r++)for(i=0;i<this.soundTracks[r].soundCollection.length;i++)if(this.soundTracks[r].soundCollection[i].name===t)return this.soundTracks[r].soundCollection[i]}return null},i.prototype.getLastSkeletonByID=function(e){for(var t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},i.prototype.getSkeletonById=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null},i.prototype.getSkeletonByName=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},Object.defineProperty(i.prototype,"uid",{get:function(){return this._uid||(this._uid=e.Tools.RandomId()),this._uid},enumerable:!0,configurable:!0}),i.prototype.addExternalData=function(e,t){return this._externalData.add(e,t)},i.prototype.getExternalData=function(e){return this._externalData.get(e)},i.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData.getOrAddWithFactory(e,t)},i.prototype.removeExternalData=function(e){return this._externalData.remove(e)},i.prototype._evaluateSubMesh=function(e,t){if(t.alwaysSelectAsActiveMesh||1===t.subMeshes.length||e.isInFrustum(this._frustumPlanes)){var i=e.getMaterial();t.showSubMeshesBoundingBox&&this._boundingBoxRenderer.renderList.push(e.getBoundingInfo().boundingBox),i&&(i.getRenderTargetTextures&&this._processedMaterials.indexOf(i)===-1&&(this._processedMaterials.push(i),this._renderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._activeIndices.addCount(e.indexCount,!1),this._renderingManager.dispatch(e))}},i.prototype._isInIntermediateRendering=function(){return this._intermediateRendering},i.prototype._evaluateActiveMeshes=function(){this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._boundingBoxRenderer.reset(),this._edgesRenderers.reset();var t,i;if(this._selectionOctree){var r=this._selectionOctree.select(this._frustumPlanes);t=r.data,i=r.length}else i=this.meshes.length,t=this.meshes;for(var n=0;n<i;n++){var o=t[n];if(!o.isBlocked&&(this._totalVertices.addCount(o.getTotalVertices(),!1),o.isReady()&&o.isEnabled())){o.computeWorldMatrix(),o.actionManager&&o.actionManager.hasSpecificTriggers([e.ActionManager.OnIntersectionEnterTrigger,e.ActionManager.OnIntersectionExitTrigger])&&this._meshesForIntersections.pushNoDuplicate(o);var s=o.getLOD(this.activeCamera);s&&(o._preActivate(),(o.alwaysSelectAsActiveMesh||o.isVisible&&o.visibility>0&&0!==(o.layerMask&this.activeCamera.layerMask)&&o.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(o),this.activeCamera._activeMeshes.push(o),o._activate(this._renderId),this._activeMesh(o,s)))}}this._particlesDuration.beginMonitoring();e.Tools.Now;if(this.particlesEnabled){e.Tools.StartPerformanceCounter("Particles",this.particleSystems.length>0);for(var a=0;a<this.particleSystems.length;a++){var h=this.particleSystems[a];h.isStarted()&&(!h.emitter.position||h.emitter&&h.emitter.isEnabled())&&(this._activeParticleSystems.push(h),h.animate())}e.Tools.EndPerformanceCounter("Particles",this.particleSystems.length>0)}this._particlesDuration.endMonitoring(!1)},i.prototype._activeMesh=function(e,t){if(t.skeleton&&this.skeletonsEnabled&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&t.skeleton.prepare(),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t)),(e.showBoundingBox||this.forceShowBoundingBoxes)&&this._boundingBoxRenderer.renderList.push(e.getBoundingInfo().boundingBox),e._edgesRenderer&&this._edgesRenderers.push(e._edgesRenderer),t&&t.subMeshes){var i,r;if(t._submeshesOctree&&t.useOctreeForRenderingSelection){var n=t._submeshesOctree.select(this._frustumPlanes);i=n.length,r=n.data}else r=t.subMeshes,i=r.length;for(var o=0;o<i;o++){var s=r[o];this._evaluateSubMesh(s,t)}}},i.prototype.updateTransformMatrix=function(e){this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))},i.prototype._renderForCamera=function(t){var i=this._engine;e.Tools.Now;if(this.activeCamera=t,!this.activeCamera)throw new Error("Active camera not set");e.Tools.StartPerformanceCounter("Rendering camera "+this.activeCamera.name),i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshesDuration.beginMonitoring(),e.Tools.StartPerformanceCounter("Active meshes evaluation"),this._evaluateActiveMeshes(),this._evaluateActiveMeshesDuration.endMonitoring(!1),e.Tools.EndPerformanceCounter("Active meshes evaluation");for(var r=0;r<this._softwareSkinnedMeshes.length;r++){var n=this._softwareSkinnedMeshes.data[r];n.applySkeleton(n.skeleton)}this._renderTargetsDuration.beginMonitoring();var o=!1;e.Tools.Now;if(this.renderTargetsEnabled&&this._renderTargets.length>0){this._intermediateRendering=!0,e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s<this._renderTargets.length;s++){var a=this._renderTargets.data[s];if(a._shouldRender()){this._renderId++;var h=a.activeCamera&&a.activeCamera!==this.activeCamera;a.render(h,this.dumpNextRenderTargets)}}e.Tools.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._intermediateRendering=!1,this._renderId++,o=!0}var c=this._engine.getStencilBuffer(),l=!1;if(this.renderTargetsEnabled&&this.highlightLayers&&this.highlightLayers.length>0){this._intermediateRendering=!0;for(var u=0;u<this.highlightLayers.length;u++){var d=this.highlightLayers[u];if(d.shouldRender()&&(!d.camera||d.camera.cameraRigMode===e.Camera.RIG_MODE_NONE&&t===d.camera||d.camera.cameraRigMode!==e.Camera.RIG_MODE_NONE&&d.camera._rigCameras.indexOf(t)>-1)){l=!0;var a=d._mainTexture;a._shouldRender()&&(this._renderId++,a.render(!1,!1),o=!0)}}this._intermediateRendering=!1,this._renderId++}o&&i.restoreDefaultFramebuffer(),this._renderTargetsDuration.endMonitoring(!1),this.postProcessManager._prepareFrame(),this._renderDuration.beginMonitoring();var f,p;if(this.layers.length){for(i.setDepthBuffer(!1),f=0;f<this.layers.length;f++)p=this.layers[f],p.isBackground&&p.render();i.setDepthBuffer(!0)}e.Tools.StartPerformanceCounter("Main render"),l&&this._engine.setStencilBuffer(!0),this._renderingManager.render(null,null,!0,!0),l&&this._engine.setStencilBuffer(c),e.Tools.EndPerformanceCounter("Main render"),this._boundingBoxRenderer.render();for(var m=0;m<this._edgesRenderers.length;m++)this._edgesRenderers.data[m].render();if(this.lensFlaresEnabled){e.Tools.StartPerformanceCounter("Lens flares",this.lensFlareSystems.length>0);for(var _=0;_<this.lensFlareSystems.length;_++){var g=this.lensFlareSystems[_];0!==(t.layerMask&g.layerMask)&&g.render()}e.Tools.EndPerformanceCounter("Lens flares",this.lensFlareSystems.length>0)}if(this.layers.length){for(i.setDepthBuffer(!1),f=0;f<this.layers.length;f++)p=this.layers[f],p.isBackground||p.render();i.setDepthBuffer(!0)}if(l){i.setDepthBuffer(!1);for(var u=0;u<this.highlightLayers.length;u++)this.highlightLayers[u].shouldRender()&&this.highlightLayers[u].render();i.setDepthBuffer(!0)}this._renderDuration.endMonitoring(!1),this.postProcessManager._finalizeFrame(t.isIntermediate),this.activeCamera._updateFromScene(),this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera),e.Tools.EndPerformanceCounter("Rendering camera "+this.activeCamera.name)},i.prototype._processSubCameras=function(t){if(t.cameraRigMode===e.Camera.RIG_MODE_NONE)return void this._renderForCamera(t);for(var i=0;i<t._rigCameras.length;i++)this._renderForCamera(t._rigCameras[i]);this.activeCamera=t,this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix()),this.activeCamera._updateFromScene()},i.prototype._checkIntersections=function(){for(var t=0;t<this._meshesForIntersections.length;t++)for(var i=this._meshesForIntersections.data[t],r=0;r<i.actionManager.actions.length;r++){var n=i.actionManager.actions[r];if(n.trigger===e.ActionManager.OnIntersectionEnterTrigger||n.trigger===e.ActionManager.OnIntersectionExitTrigger){var o=n.getTriggerParameter(),s=o instanceof e.AbstractMesh?o:o.mesh,a=s.intersectsMesh(i,o.usePreciseIntersection),h=i._intersectionsInProgress.indexOf(s);a&&h===-1?n.trigger===e.ActionManager.OnIntersectionEnterTrigger?(n._executeCurrent(e.ActionEvent.CreateNew(i,null,s)),i._intersectionsInProgress.push(s)):n.trigger===e.ActionManager.OnIntersectionExitTrigger&&i._intersectionsInProgress.push(s):!a&&h>-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,null,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger)&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(h,1))}}},i.prototype.render=function(){this._lastFrameDuration.beginMonitoring(),this._particlesDuration.fetchNewFrame(),this._spritesDuration.fetchNewFrame(),this._activeParticles.fetchNewFrame(),this._renderDuration.fetchNewFrame(),this._renderTargetsDuration.fetchNewFrame(),this._evaluateActiveMeshesDuration.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this.getEngine().drawCallsPerfCounter.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),e.Tools.StartPerformanceCounter("Scene rendering"),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger,null),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext();var t=Math.max(i.MinDeltaTime,Math.min(this._engine.getDeltaTime(),i.MaxDeltaTime));this._animationRatio=.06*t,this._animate(),this._physicsEngine&&(e.Tools.StartPerformanceCounter("Physics"),this._physicsEngine._step(t/1e3),e.Tools.EndPerformanceCounter("Physics")),this.onBeforeRenderObservable.notifyObservers(this),this._renderTargetsDuration.beginMonitoring();var r=(e.Tools.Now,this.getEngine()),n=this.activeCamera;if(this.renderTargetsEnabled){e.Tools.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0);for(var o=0;o<this.customRenderTargets.length;o++){var s=this.customRenderTargets[o];if(s._shouldRender()){if(this._renderId++,this.activeCamera=s.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");r.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),s.render(n!==this.activeCamera,this.dumpNextRenderTargets)}}e.Tools.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._renderId++}if(this.customRenderTargets.length>0&&r.restoreDefaultFramebuffer(),this._renderTargetsDuration.endMonitoring(),this.activeCamera=n,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this._proceduralTextures.length>0);for(var a=0;a<this._proceduralTextures.length;a++){var h=this._proceduralTextures[a];h._shouldRender()&&h.render()}e.Tools.EndPerformanceCounter("Procedural textures",this._proceduralTextures.length>0)}if(this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,!0,!0),this.shadowsEnabled)for(var c=0;c<this.lights.length;c++){var l=this.lights[c],u=l.getShadowGenerator();l.isEnabled()&&u&&u.getShadowMap().getScene().textures.indexOf(u.getShadowMap())!==-1&&this._renderTargets.push(u.getShadowMap())}if(this._depthRenderer&&this._renderTargets.push(this._depthRenderer.getDepthMap()),this.postProcessRenderPipelineManager.update(),this.activeCameras.length>0)for(var d=0;d<this.activeCameras.length;d++)d>0&&this._engine.clear(0,!1,!0,!0),this._processSubCameras(this.activeCameras[d]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var f=0;f<this._toBeDisposed.length;f++)this._toBeDisposed.data[f].dispose(),this._toBeDisposed[f]=null;this._toBeDisposed.reset(),this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),e.Tools.EndPerformanceCounter("Scene rendering"),this._lastFrameDuration.endMonitoring(),this._totalMeshesCounter.addCount(this.meshes.length,!0),this._totalLightsCounter.addCount(this.lights.length,!0),this._totalMaterialsCounter.addCount(this.materials.length,!0),this._totalTexturesCounter.addCount(this.textures.length,!0),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0)},i.prototype._updateAudioParameters=function(){if(this.audioEnabled&&(0!==this.mainSoundTrack.soundCollection.length||1!==this.soundTracks.length)){var t,i=e.Engine.audioEngine;if(t=this.activeCameras.length>0?this.activeCameras[0]:this.activeCamera,t&&i.canUseWebAudio){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,(-1)),r);n.normalize(),i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o<this.mainSoundTrack.soundCollection.length;o++){var s=this.mainSoundTrack.soundCollection[o];s.useCustomAttenuation&&s.updateDistanceFromListener()}for(o=0;o<this.soundTracks.length;o++)for(var a=0;a<this.soundTracks[o].soundCollection.length;a++)s=this.soundTracks[o].soundCollection[a],s.useCustomAttenuation&&s.updateDistanceFromListener()}}},Object.defineProperty(i.prototype,"audioEnabled",{get:function(){return this._audioEnabled},set:function(t){this._audioEnabled=t,e.AudioEngine&&(this._audioEnabled?this._enableAudio():this._disableAudio())},enumerable:!0,configurable:!0}),i.prototype._disableAudio=function(){var e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)this.mainSoundTrack.soundCollection[e].pause();for(e=0;e<this.soundTracks.length;e++)for(var t=0;t<this.soundTracks[e].soundCollection.length;t++)this.soundTracks[e].soundCollection[t].pause()},i.prototype._enableAudio=function(){var e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)this.mainSoundTrack.soundCollection[e].isPaused&&this.mainSoundTrack.soundCollection[e].play();for(e=0;e<this.soundTracks.length;e++)for(var t=0;t<this.soundTracks[e].soundCollection.length;t++)this.soundTracks[e].soundCollection[t].isPaused&&this.soundTracks[e].soundCollection[t].play()},Object.defineProperty(i.prototype,"headphone",{get:function(){return this._headphone},set:function(t){this._headphone=t,e.AudioEngine&&(this._headphone?this._switchAudioModeForHeadphones():this._switchAudioModeForNormalSpeakers())},enumerable:!0,configurable:!0}),i.prototype._switchAudioModeForHeadphones=function(){this.mainSoundTrack.switchPanningModelToHRTF();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].switchPanningModelToHRTF()},i.prototype._switchAudioModeForNormalSpeakers=function(){this.mainSoundTrack.switchPanningModelToEqualPower();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].switchPanningModelToEqualPower()},i.prototype.enableDepthRenderer=function(){return this._depthRenderer?this._depthRenderer:(this._depthRenderer=new e.DepthRenderer(this),this._depthRenderer)},i.prototype.disableDepthRenderer=function(){this._depthRenderer&&(this._depthRenderer.dispose(),this._depthRenderer=null)},i.prototype.freezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].freeze()},i.prototype.unfreezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].unfreeze()},i.prototype.dispose=function(){this.beforeRender=null,this.afterRender=null,this.skeletons=[],this._boundingBoxRenderer.dispose(),this._depthRenderer&&this._depthRenderer.dispose(),this._debugLayer&&this._debugLayer.hide(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.detachControl(),e.AudioEngine&&this.disposeSounds();var t,i=this._engine.getRenderingCanvas();for(t=0;t<this.cameras.length;t++)this.cameras[t].detachControl(i);for(;this.lights.length;)this.lights[0].dispose();for(;this.meshes.length;)this.meshes[0].dispose(!0);for(;this.cameras.length;)this.cameras[0].dispose();for(;this.materials.length;)this.materials[0].dispose();for(;this.particleSystems.length;)this.particleSystems[0].dispose();for(;this.spriteManagers.length;)this.spriteManagers[0].dispose();for(;this.layers.length;)this.layers[0].dispose();for(;this.highlightLayers.length;)this.highlightLayers[0].dispose();for(;this.textures.length;)this.textures[0].dispose();this.postProcessManager.dispose(),this._physicsEngine&&this.disablePhysicsEngine(),t=this._engine.scenes.indexOf(this),t>-1&&this._engine.scenes.splice(t,1),this._engine.wipeCaches()},i.prototype.disposeSounds=function(){this.mainSoundTrack.dispose();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].dispose()},i.prototype.getWorldExtends=function(){for(var t=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE)),r=0;r<this.meshes.length;r++){var n=this.meshes[r];n.computeWorldMatrix(!0);var o=n.getBoundingInfo().boundingBox.minimumWorld,s=n.getBoundingInfo().boundingBox.maximumWorld;e.Tools.CheckExtends(o,t,i),e.Tools.CheckExtends(s,t,i)}return{min:t,max:i}},i.prototype.createOrUpdateSelectionOctree=function(t,i){void 0===t&&(t=64),void 0===i&&(i=2),this._selectionOctree||(this._selectionOctree=new e.Octree(e.Octree.CreationFuncForMeshes,t,i));var r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},i.prototype.createPickingRay=function(t,i,r,n,o){void 0===o&&(o=!1);var s=this._engine;if(!n){if(!this.activeCamera)throw new Error("Active camera not set");n=this.activeCamera}var a=n.viewport,h=a.toGlobal(s.getRenderWidth(),s.getRenderHeight());return t=t/this._engine.getHardwareScalingLevel()-h.x,i=i/this._engine.getHardwareScalingLevel()-(this._engine.getRenderHeight()-h.y-h.height),e.Ray.CreateNew(t,i,h.width,h.height,r?r:e.Matrix.Identity(),o?e.Matrix.Identity():n.getViewMatrix(),n.getProjectionMatrix())},i.prototype.createPickingRayInCameraSpace=function(t,i,r){var n=this._engine;if(!r){if(!this.activeCamera)throw new Error("Active camera not set");r=this.activeCamera}var o=r.viewport,s=o.toGlobal(n.getRenderWidth(),n.getRenderHeight()),a=e.Matrix.Identity();return t=t/this._engine.getHardwareScalingLevel()-s.x,i=i/this._engine.getHardwareScalingLevel()-(this._engine.getRenderHeight()-s.y-s.height),e.Ray.CreateNew(t,i,s.width,s.height,a,a,r.getProjectionMatrix())},i.prototype._internalPick=function(t,i,r){for(var n=null,o=0;o<this.meshes.length;o++){var s=this.meshes[o];if(i){if(!i(s))continue}else if(!s.isEnabled()||!s.isVisible||!s.isPickable)continue;var a=s.getWorldMatrix(),h=t(a),c=s.intersects(h,r);if(c&&c.hit&&(r||null==n||!(c.distance>=n.distance))&&(n=c,r))break}return n||new e.PickingInfo},i.prototype._internalMultiPick=function(e,t){for(var i=new Array,r=0;r<this.meshes.length;r++){var n=this.meshes[r];if(t){if(!t(n))continue}else if(!n.isEnabled()||!n.isVisible||!n.isPickable)continue;var o=n.getWorldMatrix(),s=e(o),a=n.intersects(s,!1);a&&a.hit&&i.push(a)}return i},i.prototype._internalPickSprites=function(t,i,r,n){var o=null;if(n=n||this.activeCamera,this.spriteManagers.length>0)for(var s=0;s<this.spriteManagers.length;s++){var a=this.spriteManagers[s];if(a.isPickable){var h=a.intersects(t,n,i,r);if(h&&h.hit&&(r||null==o||!(h.distance>=o.distance))&&(o=h,r))break}}return o||new e.PickingInfo},i.prototype.pick=function(e,t,i,r,n){var o=this;return this._internalPick((function(i){return o.createPickingRay(e,t,i,n)}),i,r)},i.prototype.pickSprite=function(e,t,i,r,n){return this._internalPickSprites(this.createPickingRayInCameraSpace(e,t,n),i,r,n)},i.prototype.pickWithRay=function(t,i,r){var n=this;return this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),e.Ray.Transform(t,n._pickWithRayInverseMatrix)}),i,r)},i.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r)}),i)},i.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),e.Ray.Transform(t,r._pickWithRayInverseMatrix)}),i)},i.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},i.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},i.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},i.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},i.prototype.getPhysicsEngine=function(){return this._physicsEngine},i.prototype.enablePhysics=function(t,i){if(this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(r){return e.Tools.Error(r.message),!1}},i.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=void 0)},i.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},i.prototype.setGravity=function(t){e.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'"),this._physicsEngine&&this._physicsEngine.setGravity(t)},i.prototype.createCompoundImpostor=function(t,i){e.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child"),t.parts&&(i=t,t=t.parts);var r=t[0].mesh;r.physicsImpostor=new e.PhysicsImpostor(r,t[0].impostor,i,this);for(var n=1;n<t.length;n++){var o=t[n].mesh;o.parent!==r&&(o.position=o.position.subtract(r.position),o.parent=r),o.physicsImpostor=new e.PhysicsImpostor(o,t[n].impostor,i,this)}r.physicsImpostor.forceUpdate()},i.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor.dispose(),t.physicsImpostor=null},i.prototype.createDefaultCameraOrLight=function(){if(0===this.lights.length&&new e.HemisphericLight("default light",e.Vector3.Up(),this),!this.activeCamera){var t=new e.FreeCamera("default camera",e.Vector3.Zero(),this),i=this.getWorldExtends(),r=i.min.add(i.max.subtract(i.min).scale(.5));t.position=new e.Vector3(r.x,r.y,i.min.z-(i.max.z-i.min.z)),t.setTarget(r),this.activeCamera=t}},i.prototype._getByTags=function(t,i,r){if(void 0===i)return t;var n=[];r=r||function(e){};for(var o in t){var s=t[o];e.Tags.MatchesQuery(s,i)&&(n.push(s),r(s))}return n},i.prototype.getMeshesByTags=function(e,t){return this._getByTags(this.meshes,e,t)},i.prototype.getCamerasByTags=function(e,t){return this._getByTags(this.cameras,e,t)},i.prototype.getLightsByTags=function(e,t){return this._getByTags(this.lights,e,t)},i.prototype.getMaterialByTags=function(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t)},i._FOGMODE_NONE=0,i._FOGMODE_EXP=1,i._FOGMODE_EXP2=2,i._FOGMODE_LINEAR=3,i.MinDeltaTime=1,i.MaxDeltaTime=1e3,i})();e.Scene=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s){t instanceof e.Mesh?this._engine=t.getScene().getEngine():this._engine=t,this._updatable=r,this._data=i,this._strideSize=n,o||this.create(),this._instanced=s}return t.prototype.createVertexBuffer=function(t,i,r,n){return new e.VertexBuffer(this._engine,this,t,this._updatable,(!0),n?n:this._strideSize,this._instanced,i,r)},t.prototype.isUpdatable=function(){return this._updatable},t.prototype.getData=function(){return this._data},t.prototype.getBuffer=function(){return this._buffer},t.prototype.getStrideSize=function(){return this._strideSize},t.prototype.getIsInstanced=function(){return this._instanced},t.prototype.create=function(e){!e&&this._buffer||(e=e||this._data,this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))},t.prototype.update=function(e){this.create(e)},t.prototype.updateDirectly=function(e,t,i){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,t,i?i*this.getStrideSize():void 0),this._data=null)},t.prototype.dispose=function(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)},t})();e.Buffer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(i,r,n,o,s,a,h,c,l){if(!a)switch(n){case t.PositionKind:a=3;break;case t.NormalKind:a=3;break;case t.UVKind:case t.UV2Kind:case t.UV3Kind:case t.UV4Kind:case t.UV5Kind:case t.UV6Kind:a=2;break;case t.ColorKind:a=4;break;case t.MatricesIndicesKind:case t.MatricesIndicesExtraKind:a=4;break;case t.MatricesWeightsKind:case t.MatricesWeightsExtraKind:a=4}r instanceof e.Buffer?(a||(a=r.getStrideSize()),this._buffer=r,this._ownsBuffer=!1):(this._buffer=new e.Buffer(i,r,o,a,s,h),this._ownsBuffer=!0),this._stride=a,this._offset=c?c:0,this._size=l?l:a,this._kind=n}return t.prototype.getKind=function(){return this._kind},t.prototype.isUpdatable=function(){return this._buffer.isUpdatable()},t.prototype.getData=function(){return this._buffer.getData()},t.prototype.getBuffer=function(){return this._buffer.getBuffer()},t.prototype.getStrideSize=function(){return this._stride},t.prototype.getOffset=function(){return this._offset},t.prototype.getSize=function(){return this._size},t.prototype.getIsInstanced=function(){return this._buffer.getIsInstanced()},t.prototype.create=function(e){return this._buffer.create(e)},t.prototype.update=function(e){return this._buffer.update(e)},t.prototype.updateDirectly=function(e,t){return this._buffer.updateDirectly(e,t)},t.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose()},Object.defineProperty(t,"PositionKind",{get:function(){return t._PositionKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"NormalKind",{get:function(){return t._NormalKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UVKind",{get:function(){return t._UVKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV2Kind",{get:function(){return t._UV2Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV3Kind",{get:function(){return t._UV3Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV4Kind",{get:function(){return t._UV4Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV5Kind",{get:function(){return t._UV5Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV6Kind",{get:function(){return t._UV6Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ColorKind",{get:function(){return t._ColorKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesIndicesKind",{get:function(){return t._MatricesIndicesKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesWeightsKind",{get:function(){return t._MatricesWeightsKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesIndicesExtraKind",{get:function(){return t._MatricesIndicesExtraKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesWeightsExtraKind",{get:function(){return t._MatricesWeightsExtraKind},enumerable:!0,configurable:!0}),t._PositionKind="position",t._NormalKind="normal",t._UVKind="uv",t._UV2Kind="uv2",t._UV3Kind="uv3",t._UV4Kind="uv4",t._UV5Kind="uv5",t._UV6Kind="uv6",t._ColorKind="color",t._MatricesIndicesKind="matricesIndices",t._MatricesWeightsKind="matricesWeights",t._MatricesIndicesExtraKind="matricesIndicesExtra",t._MatricesWeightsExtraKind="matricesWeightsExtra",t})();e.VertexBuffer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i){t.call(this,e,i.getScene()),i.instances.push(this),this._sourceMesh=i,this.position.copyFrom(i.position),this.rotation.copyFrom(i.rotation),this.scaling.copyFrom(i.scaling),i.rotationQuaternion&&(this.rotationQuaternion=i.rotationQuaternion.clone()),this.infiniteDistance=i.infiniteDistance,this.setPivotMatrix(i.getPivotMatrix()),
this.refreshBoundingInfo(),this._syncSubMeshes()}return __extends(i,t),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._sourceMesh.receiveShadows},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._sourceMesh.material},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._sourceMesh.visibility},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._sourceMesh.skeleton},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"renderingGroupId",{get:function(){return this._sourceMesh.renderingGroupId},enumerable:!0,configurable:!0}),i.prototype.getTotalVertices=function(){return this._sourceMesh.getTotalVertices()},Object.defineProperty(i.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!0,configurable:!0}),i.prototype.getVerticesData=function(e,t){return this._sourceMesh.getVerticesData(e,t)},i.prototype.isVerticesDataPresent=function(e){return this._sourceMesh.isVerticesDataPresent(e)},i.prototype.getIndices=function(){return this._sourceMesh.getIndices()},Object.defineProperty(i.prototype,"_positions",{get:function(){return this._sourceMesh._positions},enumerable:!0,configurable:!0}),i.prototype.refreshBoundingInfo=function(){var t=this._sourceMesh.getBoundingInfo();this._boundingInfo=new e.BoundingInfo(t.minimum.clone(),t.maximum.clone()),this._updateBoundingInfo()},i.prototype._preActivate=function(){this._currentLOD&&this._currentLOD._preActivate()},i.prototype._activate=function(e){this._currentLOD&&this._currentLOD._registerInstanceForRenderId(this,e)},i.prototype.getLOD=function(e){return this._currentLOD=this.sourceMesh.getLOD(this.getScene().activeCamera,this.getBoundingInfo().boundingSphere),this._currentLOD===this.sourceMesh?this:this._currentLOD},i.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh)},i.prototype._generatePointsArray=function(){return this._sourceMesh._generatePointsArray()},i.prototype.clone=function(t,i,r){var n=this._sourceMesh.createInstance(t);if(e.Tools.DeepCopy(this,n,["name","subMeshes"],[]),this.refreshBoundingInfo(),i&&(n.parent=i),!r)for(var o=0;o<this.getScene().meshes.length;o++){var s=this.getScene().meshes[o];s.parent===this&&s.clone(s.name,n)}return n.computeWorldMatrix(!0),n},i.prototype.dispose=function(e){var i=this._sourceMesh.instances.indexOf(this);this._sourceMesh.instances.splice(i,1),t.prototype.dispose.call(this,e)},i})(e.AbstractMesh);e.InstancedMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array}return e})();e._InstancesBatch=t;var i=(function(i){function r(n,o,s,a,h,c){if(void 0===s&&(s=null),void 0===c&&(c=!0),i.call(this,n,o),this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onBeforeDrawObservable=new e.Observable,this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this.instances=new Array,this._LODLevels=new Array,this._visibleInstances={},this._renderIdForInstances=new Array,this._batchCache=new t,this._instancesBufferSize=2048,this._sideOrientation=r._DEFAULTSIDE,this._areNormalsFrozen=!1,a){a._geometry&&a._geometry.applyToMesh(this),e.Tools.DeepCopy(a,this,["name","material","skeleton","instances","parent"],["_poseMatrix"]),this.parent=a.parent,this.setPivotMatrix(a.getPivotMatrix()),this.id=n+"."+a.id,this.material=a.material;var l;if(!h)for(l=0;l<o.meshes.length;l++){var u=o.meshes[l];if(u.parent===a){u.clone(n+"."+u.name,this,h)}}var d=this.getScene().getPhysicsEngine();if(c&&d){var f=d.getImpostorForPhysicsObject(a);f&&(this.physicsImpostor=f.clone(this))}for(l=0;l<o.particleSystems.length;l++){var p=o.particleSystems[l];p.emitter===a&&p.clone(p.name,this)}this.computeWorldMatrix(!0)}null!==s&&(this.parent=s)}return __extends(r,i),Object.defineProperty(r,"FRONTSIDE",{get:function(){return r._FRONTSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BACKSIDE",{get:function(){return r._BACKSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"DOUBLESIDE",{get:function(){return r._DOUBLESIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"DEFAULTSIDE",{get:function(){return r._DEFAULTSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"NO_CAP",{get:function(){return r._NO_CAP},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_START",{get:function(){return r._CAP_START},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_END",{get:function(){return r._CAP_END},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_ALL",{get:function(){return r._CAP_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"onBeforeDraw",{set:function(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)},enumerable:!0,configurable:!0}),r.prototype.toString=function(t){var r=i.prototype.toString.call(this,t);if(r+=", n vertices: "+this.getTotalVertices(),r+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(var n=0;n<this.animations.length;n++)r+=", animation[0]: "+this.animations[n].toString(t);return t&&(r+=", flat shading: "+(this._geometry?this.getVerticesData(e.VertexBuffer.PositionKind).length/3===this.getIndices().length?"YES":"NO":"UNKNOWN")),r},Object.defineProperty(r.prototype,"hasLODLevels",{get:function(){return this._LODLevels.length>0},enumerable:!0,configurable:!0}),r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distance<t.distance?1:e.distance>t.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.Internals.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;t<this._LODLevels.length;t++){var i=this._LODLevels[t];if(i.distance===e)return i.mesh}return null},r.prototype.removeLODLevel=function(e){for(var t=0;t<this._LODLevels.length;t++)this._LODLevels[t].mesh===e&&(this._LODLevels.splice(t,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this},r.prototype.getLOD=function(e,t){if(!this._LODLevels||0===this._LODLevels.length)return this;var i=(t?t:this.getBoundingInfo().boundingSphere).centerWorld.subtract(e.globalPosition).length();if(this._LODLevels[this._LODLevels.length-1].distance>i)return this.onLODLevelSelection&&this.onLODLevelSelection(i,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var r=0;r<this._LODLevels.length;r++){var n=this._LODLevels[r];if(n.distance<i)return n.mesh&&(n.mesh._preActivate(),n.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)),this.onLODLevelSelection&&this.onLODLevelSelection(i,this,n.mesh),n.mesh}return this.onLODLevelSelection&&this.onLODLevelSelection(i,this,this),this},Object.defineProperty(r.prototype,"geometry",{get:function(){return this._geometry},enumerable:!0,configurable:!0}),r.prototype.getTotalVertices=function(){return this._geometry?this._geometry.getTotalVertices():0},r.prototype.getVerticesData=function(e,t){return this._geometry?this._geometry.getVerticesData(e,t):null},r.prototype.getVertexBuffer=function(e){if(this._geometry)return this._geometry.getVertexBuffer(e)},r.prototype.isVerticesDataPresent=function(e){return this._geometry?this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&this._delayInfo.indexOf(e)!==-1},r.prototype.getVerticesDataKinds=function(){if(!this._geometry){var e=[];return this._delayInfo&&this._delayInfo.forEach((function(t,i,r){e.push(t)})),e}return this._geometry.getVerticesDataKinds()},r.prototype.getTotalIndices=function(){return this._geometry?this._geometry.getTotalIndices():0},r.prototype.getIndices=function(e){return this._geometry?this._geometry.getIndices(e):[]},Object.defineProperty(r.prototype,"isBlocked",{get:function(){return null!==this._masterMesh&&void 0!==this._masterMesh},enumerable:!0,configurable:!0}),r.prototype.isReady=function(){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&i.prototype.isReady.call(this)},r.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(r.prototype,"sideOrientation",{get:function(){return this._sideOrientation},set:function(e){this._sideOrientation=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"areNormalsFrozen",{get:function(){return this._areNormalsFrozen},enumerable:!0,configurable:!0}),r.prototype.freezeNormals=function(){this._areNormalsFrozen=!0},r.prototype.unfreezeNormals=function(){this._areNormalsFrozen=!1},Object.defineProperty(r.prototype,"overridenInstanceCount",{set:function(e){this._overridenInstanceCount=e},enumerable:!0,configurable:!0}),r.prototype._preActivate=function(){var e=this.getScene().getRenderId();this._preActivateId!==e&&(this._preActivateId=e,this._visibleInstances=null)},r.prototype._preActivateForIntermediateRendering=function(e){this._visibleInstances&&(this._visibleInstances.intermediateDefaultRenderId=e)},r.prototype._registerInstanceForRenderId=function(e,t){this._visibleInstances||(this._visibleInstances={},this._visibleInstances.defaultRenderId=t,this._visibleInstances.selfDefaultRenderId=this._renderId),this._visibleInstances[t]||(this._visibleInstances[t]=new Array),this._visibleInstances[t].push(e)},r.prototype.refreshBoundingInfo=function(){if(!this._boundingInfo.isLocked){var t=this.getVerticesData(e.VertexBuffer.PositionKind);if(t){var i=e.Tools.ExtractMinAndMax(t,0,this.getTotalVertices());this._boundingInfo=new e.BoundingInfo(i.minimum,i.maximum)}if(this.subMeshes)for(var r=0;r<this.subMeshes.length;r++)this.subMeshes[r].refreshBoundingInfo();this._updateBoundingInfo()}},r.prototype._createGlobalSubMesh=function(){var t=this.getTotalVertices();return t&&this.getIndices()?(this.releaseSubMeshes(),new e.SubMesh(0,0,t,0,this.getTotalIndices(),this)):null},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!==0;)r++;this.releaseSubMeshes();for(var o=0;o<t&&!(n>=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}},r.prototype.setVerticesBuffer=function(t){if(!this._geometry){var i=this.getScene();new e.Geometry(e.Geometry.RandomId(),i).applyToMesh(this)}this._geometry.setVerticesBuffer(t)},r.prototype.updateVerticesData=function(e,t,i,r){this._geometry&&(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i))},r.prototype.updateVerticesDataDirectly=function(t,i,r,n){e.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3."),this._geometry&&(n?(this.makeGeometryUnique(),this.updateVerticesDataDirectly(t,i,r,!1)):this._geometry.updateVerticesDataDirectly(t,i,r))},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}},r.prototype.makeGeometryUnique=function(){if(this._geometry){var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());t.releaseForMesh(this,!0),i.applyToMesh(this)}},r.prototype.setIndices=function(t,i){if(this._geometry)this._geometry.setIndices(t,i);else{var r=new e.VertexData;r.indices=t;var n=this.getScene();new e.Geometry(e.Geometry.RandomId(),n,r,(!1),this)}},r.prototype.toLeftHanded=function(){this._geometry&&this._geometry.toLeftHanded()},r.prototype._bind=function(t,i,r){var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}o.bindBuffers(this._geometry.getVertexBuffers(),n,i)},r.prototype._draw=function(t,i,r){if(this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){this.onBeforeDrawObservable.notifyObservers(this);var n=this.getScene().getEngine();switch(i){case e.Material.PointFillMode:n.drawPointClouds(t.verticesStart,t.verticesCount,r);break;case e.Material.WireFrameFillMode:this._unIndexed?n.drawUnIndexed(!1,t.verticesStart,t.verticesCount,r):n.draw(!1,0,r>0?t.linesIndexCount/2:t.linesIndexCount,r);break;default:this._unIndexed?n.drawUnIndexed(!0,t.verticesStart,t.verticesCount,r):n.draw(!0,t.indexStart,t.indexCount,r)}}},r.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},r.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},r.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},r.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;if(!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i)),this._batchCache.visibleInstances[e]&&this._batchCache.visibleInstances[e].length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){for(var s=r.visibleInstances[t._id],a=s.length+1,h=16*a*4,c=this._instancesBufferSize,l=this._instancesBuffer;this._instancesBufferSize<h;)this._instancesBufferSize*=2;this._instancesData&&c==this._instancesBufferSize||(this._instancesData=new Float32Array(this._instancesBufferSize/4));var u=0,d=0,f=this.getWorldMatrix();if(r.renderSelf[t._id]&&(f.copyToArray(this._instancesData,u),u+=16,d++),s)for(var p=0;p<s.length;p++){var m=s[p];m.getWorldMatrix().copyToArray(this._instancesData,u),u+=16,d++}l&&c==this._instancesBufferSize?l.updateDirectly(this._instancesData,0,d):(l&&l.dispose(),l=new e.Buffer(o,this._instancesData,(!0),16,(!1),(!0)),this._instancesBuffer=l,this.setVerticesBuffer(l.createVertexBuffer("world0",0,4)),this.setVerticesBuffer(l.createVertexBuffer("world1",4,4)),this.setVerticesBuffer(l.createVertexBuffer("world2",8,4)),this.setVerticesBuffer(l.createVertexBuffer("world3",12,4))),o.bindBuffers(this.geometry.getVertexBuffers(),this.geometry.getIndexBuffer(),n),this._draw(t,i,d),o.unbindInstanceAttributes()},r.prototype._processRendering=function(e,t,i,r,n,o,s){var a=this.getScene(),h=a.getEngine();if(n)this._renderWithInstances(e,i,r,t,h);else if(r.renderSelf[e._id]&&(o&&o(!1,this.getWorldMatrix(),s),this._draw(e,i,this._overridenInstanceCount)),r.visibleInstances[e._id])for(var c=0;c<r.visibleInstances[e._id].length;c++){var l=r.visibleInstances[e._id][c],u=l.getWorldMatrix();o&&o(!0,u,s),this._draw(e,i)}},r.prototype.render=function(t,i){var r=this.getScene(),n=this._getInstancesRenderList(t._id);if(!n.mustReturn&&this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){this.onBeforeRenderObservable.notifyObservers(this);var o=r.getEngine(),s=null!==o.getCaps().instancedArrays&&null!==n.visibleInstances[t._id]&&void 0!==n.visibleInstances[t._id],a=t.getMaterial();if(a&&a.isReady(this,s)){var h=o.getDepthWrite();this.renderOutline&&(o.setDepthWrite(!1),r.getOutlineRenderer().render(t,n),o.setDepthWrite(h)),a._preBind();var c=a.getEffect(),l=r.forcePointsCloud?e.Material.PointFillMode:r.forceWireframe?e.Material.WireFrameFillMode:a.fillMode;this._bind(t,c,l);var u=this.getWorldMatrix();if(a.bind(u,this),i&&o.setAlphaMode(a.alphaMode),this._processRendering(t,c,l,n,s,this._onBeforeDraw,a),a.unbind(),this.renderOutline&&h&&(o.setDepthWrite(!0),o.setColorWrite(!1),r.getOutlineRenderer().render(t,n),o.setColorWrite(!0)),this.renderOverlay){var d=o.getAlphaMode();o.setAlphaMode(e.Engine.ALPHA_COMBINE),r.getOutlineRenderer().render(t,n,!0),o.setAlphaMode(d)}this.onAfterRenderObservable.notifyObservers(this)}}},r.prototype._onBeforeDraw=function(e,t,i){e&&i.bindOnlyWorldMatrix(t)},r.prototype.getEmittedParticleSystems=function(){for(var e=new Array,t=0;t<this.getScene().particleSystems.length;t++){var i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},r.prototype.getHierarchyEmittedParticleSystems=function(){var e=new Array,t=this.getDescendants();t.push(this);for(var i=0;i<this.getScene().particleSystems.length;i++){var r=this.getScene().particleSystems[i];t.indexOf(r.emitter)!==-1&&e.push(r)}return e},r.prototype._checkDelayState=function(){var t=this.getScene();this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(this,t))},r.prototype._queueLoad=function(t,i){var r=this;i._addPendingData(t);var n=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;e.Tools.LoadFile(this.delayLoadingFile,(function(t){t instanceof ArrayBuffer?r._delayLoadingFunction(t,r):r._delayLoadingFunction(JSON.parse(t),r),r.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,i._removePendingData(r)}),(function(){}),i.database,n)},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=0;t<i.length;t++)if(i[t].id===e)return void(this.material=i[t]);var r=this.getScene().multiMaterials;for(t=0;t<r.length;t++)if(r[t].id===e)return void(this.material=r[t])},r.prototype.getAnimatables=function(){var e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(this.isVerticesDataPresent(e.VertexBuffer.PositionKind)){var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=[];for(r=0;r<n.length;r+=3)e.Vector3.TransformCoordinates(e.Vector3.FromArray(n,r),t).toArray(o,r);if(this.setVerticesData(e.VertexBuffer.PositionKind,o,this.getVertexBuffer(e.VertexBuffer.PositionKind).isUpdatable()),this.isVerticesDataPresent(e.VertexBuffer.NormalKind)){for(n=this.getVerticesData(e.VertexBuffer.NormalKind),o=[],r=0;r<n.length;r+=3)e.Vector3.TransformNormal(e.Vector3.FromArray(n,r),t).normalize().toArray(o,r);this.setVerticesData(e.VertexBuffer.NormalKind,o,this.getVertexBuffer(e.VertexBuffer.NormalKind).isUpdatable()),t.m[0]*t.m[5]*t.m[10]<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=i}}},r.prototype.bakeCurrentTransformIntoVertices=function(){this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=e.Quaternion.Identity()),this._worldMatrix=e.Matrix.Identity()},r.prototype._resetPointsArrayCache=function(){this._positions=null},r.prototype._generatePointsArray=function(){if(this._positions)return!0;this._positions=[];var t=this.getVerticesData(e.VertexBuffer.PositionKind);if(!t)return!1;for(var i=0;i<t.length;i+=3)this._positions.push(e.Vector3.FromArray(t,i));return!0},r.prototype.clone=function(e,t,i,n){return void 0===n&&(n=!0),new r(e,this.getScene(),t,this,i,n)},r.prototype.dispose=function(e){for(this._geometry&&this._geometry.releaseForMesh(this,!0),this._instancesBuffer&&(this._instancesBuffer.dispose(),this._instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(var t=this.getScene().highlightLayers,r=0;r<t.length;r++){var n=t[r];n&&(n.removeMesh(this),n.removeExcludedMesh(this))}i.prototype.dispose.call(this,e)},r.prototype.applyDisplacementMap=function(t,i,r,n){var o=this,s=this.getScene(),a=function(e){var t=document.createElement("canvas"),s=t.getContext("2d"),a=e.width,h=e.height;t.width=a,t.height=h,s.drawImage(e,0,0);var c=s.getImageData(0,0,a,h).data;o.applyDisplacementMapFromBuffer(c,a,h,i,r),n&&n(o)};e.Tools.LoadImage(t,a,(function(){}),s.database)},r.prototype.applyDisplacementMapFromBuffer=function(t,i,r,n,o){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind)||!this.isVerticesDataPresent(e.VertexBuffer.NormalKind)||!this.isVerticesDataPresent(e.VertexBuffer.UVKind))return void e.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");for(var s=this.getVerticesData(e.VertexBuffer.PositionKind),a=this.getVerticesData(e.VertexBuffer.NormalKind),h=this.getVerticesData(e.VertexBuffer.UVKind),c=e.Vector3.Zero(),l=e.Vector3.Zero(),u=e.Vector2.Zero(),d=0;d<s.length;d+=3){e.Vector3.FromArrayToRef(s,d,c),e.Vector3.FromArrayToRef(a,d,l),e.Vector2.FromArrayToRef(h,d/3*2,u);var f=Math.abs(u.x)*i%i|0,p=Math.abs(u.y)*r%r|0,m=4*(f+p*i),_=t[m]/255,g=t[m+1]/255,v=t[m+2]/255,y=.3*_+.59*g+.11*v;l.normalize(),l.scaleInPlace(n+(o-n)*y),c=c.add(l),c.toArray(s,d)}e.VertexData.ComputeNormals(s,this.getIndices(),a),this.updateVerticesData(e.VertexBuffer.PositionKind,s),this.updateVerticesData(e.VertexBuffer.NormalKind,a)},r.prototype.convertToFlatShadedMesh=function(){var t,i,r=this.getVerticesDataKinds(),n=[],o=[],s=[],a=!1;for(t=0;t<r.length;t++){i=r[t];var h=this.getVertexBuffer(i);i!==e.VertexBuffer.NormalKind?(n[i]=h,o[i]=n[i].getData(),s[i]=[]):(a=h.isUpdatable(),r.splice(t,1),t--)}var c,l=this.subMeshes.slice(0),u=this.getIndices(),d=this.getTotalIndices();for(c=0;c<d;c++){var f=u[c];for(t=0;t<r.length;t++){i=r[t];for(var p=n[i].getStrideSize(),m=0;m<p;m++)s[i].push(o[i][f*p+m])}}var _=[],g=s[e.VertexBuffer.PositionKind];for(c=0;c<d;c+=3){u[c]=c,u[c+1]=c+1,u[c+2]=c+2;for(var v=e.Vector3.FromArray(g,3*c),y=e.Vector3.FromArray(g,3*(c+1)),x=e.Vector3.FromArray(g,3*(c+2)),b=v.subtract(y),T=x.subtract(y),A=e.Vector3.Normalize(e.Vector3.Cross(b,T)),E=0;E<3;E++)_.push(A.x),_.push(A.y),_.push(A.z)}for(this.setIndices(u),this.setVerticesData(e.VertexBuffer.NormalKind,_,a),t=0;t<r.length;t++)i=r[t],this.setVerticesData(i,s[i],n[i].isUpdatable());this.releaseSubMeshes();for(var P=0;P<l.length;P++){var M=l[P];new e.SubMesh(M.materialIndex,M.indexStart,M.indexCount,M.indexStart,M.indexCount,this)}this.synchronizeInstances()},r.prototype.convertToUnIndexedMesh=function(){var t,i,r=this.getVerticesDataKinds(),n=[],o=[],s=[];for(t=0;t<r.length;t++){i=r[t];var a=this.getVertexBuffer(i);n[i]=a,o[i]=n[i].getData(),s[i]=[]}var h,c=this.subMeshes.slice(0),l=this.getIndices(),u=this.getTotalIndices();for(h=0;h<u;h++){var d=l[h];for(t=0;t<r.length;t++){i=r[t];for(var f=n[i].getStrideSize(),p=0;p<f;p++)s[i].push(o[i][d*f+p])}}for(h=0;h<u;h+=3)l[h]=h,l[h+1]=h+1,l[h+2]=h+2;for(this.setIndices(l),t=0;t<r.length;t++)i=r[t],this.setVerticesData(i,s[i],n[i].isUpdatable());this.releaseSubMeshes();for(var m=0;m<c.length;m++){var _=c[m];new e.SubMesh(_.materialIndex,_.indexStart,_.indexCount,_.indexStart,_.indexCount,this)}this._unIndexed=!0,this.synchronizeInstances()},r.prototype.flipFaces=function(t){void 0===t&&(t=!1);var i,r=e.VertexData.ExtractFromMesh(this);if(t&&this.isVerticesDataPresent(e.VertexBuffer.NormalKind))for(i=0;i<r.normals.length;i++)r.normals[i]*=-1;var n;for(i=0;i<r.indices.length;i+=3)n=r.indices[i+1],r.indices[i+1]=r.indices[i+2],r.indices[i+2]=n;r.applyToMesh(this)},r.prototype.createInstance=function(t){return new e.InstancedMesh(t,this)},r.prototype.synchronizeInstances=function(){for(var e=0;e<this.instances.length;e++){var t=this.instances[e];t._syncSubMeshes()}},r.prototype.simplify=function(t,i,r,n){void 0===i&&(i=!0),void 0===r&&(r=e.SimplificationType.QUADRATIC),this.getScene().simplificationQueue.addTask({settings:t,parallelProcessing:i,mesh:this,simplificationType:r,successCallback:n})},r.prototype.optimizeIndices=function(t){for(var i=this,r=this.getIndices(),n=this.getVerticesData(e.VertexBuffer.PositionKind),o=[],s=0;s<n.length;s+=3)o.push(e.Vector3.FromArray(n,s));var a=[];e.AsyncLoop.SyncAsyncForLoop(o.length,40,(function(e){for(var t=o.length-1-e,i=o[t],r=0;r<t;++r){var n=o[r];if(i.equals(n)){a[t]=r;break}}}),(function(){for(var e=0;e<r.length;++e)r[e]=a[r[e]]||r[e];var n=i.subMeshes.slice(0);i.setIndices(r),i.subMeshes=n,t&&t(i)}))},r.Parse=function(t,i,n){var o=new r(t.name,i);if(o.id=t.id,e.Tags.AddTagsTo(o,t.tags),o.position=e.Vector3.FromArray(t.position),void 0!==t.metadata&&(o.metadata=t.metadata),t.rotationQuaternion?o.rotationQuaternion=e.Quaternion.FromArray(t.rotationQuaternion):t.rotation&&(o.rotation=e.Vector3.FromArray(t.rotation)),o.scaling=e.Vector3.FromArray(t.scaling),t.localMatrix?o.setPivotMatrix(e.Matrix.FromArray(t.localMatrix)):t.pivotMatrix&&o.setPivotMatrix(e.Matrix.FromArray(t.pivotMatrix)),o.setEnabled(t.isEnabled),o.isVisible=t.isVisible,o.infiniteDistance=t.infiniteDistance,o.showBoundingBox=t.showBoundingBox,o.showSubMeshesBoundingBox=t.showSubMeshesBoundingBox,void 0!==t.applyFog&&(o.applyFog=t.applyFog),void 0!==t.pickable&&(o.isPickable=t.pickable),void 0!==t.alphaIndex&&(o.alphaIndex=t.alphaIndex),o.receiveShadows=t.receiveShadows,o.billboardMode=t.billboardMode,void 0!==t.visibility&&(o.visibility=t.visibility),o.checkCollisions=t.checkCollisions,void 0!==t.isBlocker&&(o.isBlocker=t.isBlocker),o._shouldGenerateFlatShading=t.useFlatShading,t.freezeWorldMatrix&&(o._waitingFreezeWorldMatrix=t.freezeWorldMatrix),t.parentId&&(o._waitingParentId=t.parentId),void 0!==t.actions&&(o._waitingActions=t.actions),void 0!==t.overlayAlpha&&(o.overlayAlpha=t.overlayAlpha),void 0!==t.overlayColor&&(o.overlayColor=e.Color3.FromArray(t.overlayColor)),void 0!==t.renderOverlay&&(o.renderOverlay=t.renderOverlay),o.hasVertexAlpha=t.hasVertexAlpha,t.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+t.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(t.boundingBoxMinimum),e.Vector3.FromArray(t.boundingBoxMaximum)),t._binaryInfo&&(o._binaryInfo=t._binaryInfo),o._delayInfo=[],t.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),t.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),t.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),t.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),t.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),t.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),t.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),t.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),t.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.Geometry.ImportGeometry,e.SceneLoader.ForceFullSceneLoadingForIncremental&&o._checkDelayState()):e.Geometry.ImportGeometry(t,o),t.materialId?o.setMaterialByID(t.materialId):o.material=null,t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s<t.animations.length;s++){var a=t.animations[s];o.animations.push(e.Animation.Parse(a))}e.Node.ParseAnimationRanges(o,t,i)}if(t.autoAnimate&&i.beginAnimation(o,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),t.layerMask&&!isNaN(t.layerMask)?o.layerMask=Math.abs(parseInt(t.layerMask)):o.layerMask=268435455,t.physicsImpostor&&(o.physicsImpostor=new e.PhysicsImpostor(o,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},i)),t.instances)for(var h=0;h<t.instances.length;h++){var c=t.instances[h],l=o.createInstance(c.name);if(e.Tags.AddTagsTo(l,c.tags),l.position=e.Vector3.FromArray(c.position),c.parentId&&(l._waitingParentId=c.parentId),c.rotationQuaternion?l.rotationQuaternion=e.Quaternion.FromArray(c.rotationQuaternion):c.rotation&&(l.rotation=e.Vector3.FromArray(c.rotation)),l.scaling=e.Vector3.FromArray(c.scaling),l.checkCollisions=o.checkCollisions,t.animations){for(s=0;s<t.animations.length;s++)a=t.animations[s],l.animations.push(e.Animation.Parse(a));e.Node.ParseAnimationRanges(l,t,i)}}return o},r.CreateRibbon=function(t,i,r,n,o,s,a,h,c){return e.MeshBuilder.CreateRibbon(t,{pathArray:i,closeArray:r,closePath:n,offset:o,updatable:a,sideOrientation:h,instance:c},s)},r.CreateDisc=function(t,i,r,n,o,s){var a={radius:i,tessellation:r,sideOrientation:s,updatable:o};return e.MeshBuilder.CreateDisc(t,a,n)},r.CreateBox=function(t,i,r,n,o){var s={size:i,sideOrientation:o,updatable:n};return e.MeshBuilder.CreateBox(t,s,r)},r.CreateSphere=function(t,i,r,n,o,s){var a={segments:i,diameterX:r,diameterY:r,diameterZ:r,sideOrientation:s,updatable:o};return e.MeshBuilder.CreateSphere(t,a,n)},r.CreateCylinder=function(t,i,n,o,s,a,h,c,l){void 0!==h&&h instanceof e.Scene||(void 0!==h&&(l=c||r.DEFAULTSIDE,c=h),h=a,a=1);var u={height:i,diameterTop:n,diameterBottom:o,tessellation:s,subdivisions:a,sideOrientation:l,updatable:c};return e.MeshBuilder.CreateCylinder(t,u,h)},r.CreateTorus=function(t,i,r,n,o,s,a){var h={diameter:i,thickness:r,tessellation:n,sideOrientation:a,updatable:s};return e.MeshBuilder.CreateTorus(t,h,o)},r.CreateTorusKnot=function(t,i,r,n,o,s,a,h,c,l){var u={radius:i,tube:r,radialSegments:n,tubularSegments:o,p:s,q:a,sideOrientation:l,updatable:c};return e.MeshBuilder.CreateTorusKnot(t,u,h)},r.CreateLines=function(t,i,r,n,o){var s={points:i,updatable:n,instance:o};return e.MeshBuilder.CreateLines(t,s,r)},r.CreateDashedLines=function(t,i,r,n,o,s,a,h){var c={points:i,dashSize:r,gapSize:n,dashNb:o,updatable:a,instance:h};return e.MeshBuilder.CreateDashedLines(t,c,s)},r.ExtrudeShape=function(t,i,n,o,s,a,h,c,l,u){var d={shape:i,path:n,scale:o,rotation:s,cap:0===a?0:a||r.NO_CAP,sideOrientation:l,instance:u,updatable:c};return e.MeshBuilder.ExtrudeShape(t,d,h)},r.ExtrudeShapeCustom=function(t,i,n,o,s,a,h,c,l,u,d,f){var p={shape:i,path:n,scaleFunction:o,rotationFunction:s,ribbonCloseArray:a,ribbonClosePath:h,cap:0===c?0:c||r.NO_CAP,sideOrientation:d,instance:f,updatable:u};return e.MeshBuilder.ExtrudeShapeCustom(t,p,l)},r.CreateLathe=function(t,i,r,n,o,s,a){var h={shape:i,radius:r,tessellation:n,sideOrientation:a,updatable:s};return e.MeshBuilder.CreateLathe(t,h,o)},r.CreatePlane=function(t,i,r,n,o){var s={size:i,width:i,height:i,sideOrientation:o,updatable:n};return e.MeshBuilder.CreatePlane(t,s,r)},r.CreateGround=function(t,i,r,n,o,s){var a={width:i,height:r,subdivisions:n,updatable:s};return e.MeshBuilder.CreateGround(t,a,o)},r.CreateTiledGround=function(t,i,r,n,o,s,a,h,c){var l={xmin:i,zmin:r,xmax:n,zmax:o,subdivisions:s,precision:a,updatable:c};return e.MeshBuilder.CreateTiledGround(t,l,h)},r.CreateGroundFromHeightMap=function(t,i,r,n,o,s,a,h,c,l){var u={width:r,height:n,subdivisions:o,minHeight:s,maxHeight:a,updatable:c,onReady:l};return e.MeshBuilder.CreateGroundFromHeightMap(t,i,u,h)},r.CreateTube=function(t,i,r,n,o,s,a,h,c,l){var u={path:i,radius:r,tessellation:n,radiusFunction:o,arc:1,cap:s,updatable:h,sideOrientation:c,instance:l};return e.MeshBuilder.CreateTube(t,u,a)},r.CreatePolyhedron=function(t,i,r){return e.MeshBuilder.CreatePolyhedron(t,i,r)},r.CreateIcoSphere=function(t,i,r){
return e.MeshBuilder.CreateIcoSphere(t,i,r)},r.CreateDecal=function(t,i,r,n,o,s){var a={position:r,normal:n,size:o,angle:s};return e.MeshBuilder.CreateDecal(t,i,a)},r.prototype.setPositionsForCPUSkinning=function(){var t;return this._sourcePositions||(t=this.getVerticesData(e.VertexBuffer.PositionKind),this._sourcePositions=new Float32Array(t),this.getVertexBuffer(e.VertexBuffer.PositionKind).isUpdatable()||this.setVerticesData(e.VertexBuffer.PositionKind,t,!0)),this._sourcePositions},r.prototype.setNormalsForCPUSkinning=function(){var t;return this._sourceNormals||(t=this.getVerticesData(e.VertexBuffer.NormalKind),this._sourceNormals=new Float32Array(t),this.getVertexBuffer(e.VertexBuffer.NormalKind).isUpdatable()||this.setVerticesData(e.VertexBuffer.NormalKind,t,!0)),this._sourceNormals},r.prototype.applySkeleton=function(t){if(this.geometry&&this.geometry._softwareSkinningRenderId!=this.getScene().getRenderId()){if(this.geometry._softwareSkinningRenderId=this.getScene().getRenderId(),!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.NormalKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind))return this;if(!this._sourcePositions){var i=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=i}this._sourceNormals||this.setNormalsForCPUSkinning();var r=this.getVerticesData(e.VertexBuffer.PositionKind);r instanceof Float32Array||(r=new Float32Array(r));var n=this.getVerticesData(e.VertexBuffer.NormalKind);n instanceof Float32Array||(n=new Float32Array(n));for(var o,s=this.getVerticesData(e.VertexBuffer.MatricesIndicesKind),a=this.getVerticesData(e.VertexBuffer.MatricesWeightsKind),h=this.numBoneInfluencers>4,c=h?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,l=h?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),d=e.Vector3.Zero(),f=new e.Matrix,p=new e.Matrix,m=0,_=0;_<r.length;_+=3,m+=4){var g;for(o=0;o<4&&(g=a[m+o],g>0);o++)e.Matrix.FromFloat32ArrayToRefScaled(u,16*s[m+o],g,p),f.addToSelf(p);if(h)for(o=0;o<4&&(g=l[m+o],g>0);o++)e.Matrix.FromFloat32ArrayToRefScaled(u,16*c[m+o],g,p),f.addToSelf(p);e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[_],this._sourcePositions[_+1],this._sourcePositions[_+2],f,d),d.toArray(r,_),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[_],this._sourceNormals[_+1],this._sourceNormals[_+2],f,d),d.toArray(n,_),f.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this}},r.MinMax=function(e){var t=null,i=null;return e.forEach((function(e,r,n){var o=e.getBoundingInfo().boundingBox;t?(t.MinimizeInPlace(o.minimumWorld),i.MaximizeInPlace(o.maximumWorld)):(t=o.minimumWorld,i=o.maximumWorld)})),{min:t,max:i}},r.Center=function(t){var i=t instanceof Array?e.Mesh.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o){void 0===i&&(i=!0);var s;if(!n){var a=0;for(s=0;s<t.length;s++)if(t[s]&&(a+=t[s].getTotalVertices(),a>65536))return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var h,c,l;for(s=0;s<t.length;s++)t[s]&&(t[s].computeWorldMatrix(!0),c=e.VertexData.ExtractFromMesh(t[s],!0),c.transform(t[s].getWorldMatrix()),h?h.merge(c):(h=c,l=t[s]));if(o||(o=new r(l.name+"_merged",l.getScene())),h.applyToMesh(o),o.material=l.material,o.checkCollisions=l.checkCollisions,i)for(s=0;s<t.length;s++)t[s]&&t[s].dispose();return o},r._FRONTSIDE=0,r._BACKSIDE=1,r._DOUBLESIDE=2,r._DEFAULTSIDE=0,r._NO_CAP=0,r._CAP_START=1,r._CAP_END=2,r._CAP_ALL=3,r})(e.AbstractMesh);e.Mesh=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o,s,a){void 0===a&&(a=!0),this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=n,this._renderId=0,this._mesh=o,this._renderingMesh=s||o,o.subMeshes.push(this),this._trianglePlanes=[],this._id=o.subMeshes.length-1,a&&(this.refreshBoundingInfo(),o.computeWorldMatrix(!0))}return Object.defineProperty(t.prototype,"IsGlobal",{get:function(){return 0===this.verticesStart&&this.verticesCount==this._mesh.getTotalVertices()},enumerable:!0,configurable:!0}),t.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},t.prototype.getMesh=function(){return this._mesh},t.prototype.getRenderingMesh=function(){return this._renderingMesh},t.prototype.getMaterial=function(){var t=this._renderingMesh.material;if(t&&t instanceof e.MultiMaterial){var i=t;return i.getSubMaterial(this.materialIndex)}return t?t:this._mesh.getScene().defaultMaterial},t.prototype.refreshBoundingInfo=function(){if(this._lastColliderWorldVertices=null,!this.IsGlobal){var t=this._renderingMesh.getVerticesData(e.VertexBuffer.PositionKind);if(!t)return void(this._boundingInfo=this._mesh._boundingInfo);var i,r=this._renderingMesh.getIndices();i=0===this.indexStart&&this.indexCount===r.length?{minimum:this._renderingMesh.getBoundingInfo().minimum.clone(),maximum:this._renderingMesh.getBoundingInfo().maximum.clone()}:e.Tools.ExtractMinAndMaxIndexed(t,r,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias),this._boundingInfo=new e.BoundingInfo(i.minimum,i.maximum)}},t.prototype._checkCollision=function(e){return this.getBoundingInfo()._checkCollision(e)},t.prototype.updateBoundingInfo=function(e){this.getBoundingInfo()||this.refreshBoundingInfo(),this.getBoundingInfo().update(e)},t.prototype.isInFrustum=function(e){return this.getBoundingInfo().isInFrustum(e)},t.prototype.isCompletelyInFrustum=function(e){return this.getBoundingInfo().isCompletelyInFrustum(e)},t.prototype.render=function(e){this._renderingMesh.render(this,e)},t.prototype.getLinesIndexBuffer=function(e,t){if(!this._linesIndexBuffer){for(var i=[],r=this.indexStart;r<this.indexStart+this.indexCount;r+=3)i.push(e[r],e[r+1],e[r+1],e[r+2],e[r+2],e[r]);this._linesIndexBuffer=t.createIndexBuffer(i),this.linesIndexCount=i.length}return this._linesIndexBuffer},t.prototype.canIntersects=function(e){return e.intersectsBox(this.getBoundingInfo().boundingBox)},t.prototype.intersects=function(t,i,r,n){var o=null;if(this._mesh instanceof e.LinesMesh)for(var s=this._mesh,a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){var h=i[r[a]],c=i[r[a+1]],l=t.intersectionSegment(h,c,s.intersectionThreshold);if(!(l<0)&&(n||!o||l<o.distance)&&(o=new e.IntersectionInfo(null,null,l),n))break}else for(var a=this.indexStart;a<this.indexStart+this.indexCount;a+=3){var h=i[r[a]],c=i[r[a+1]],u=i[r[a+2]],d=t.intersectsTriangle(h,c,u);if(d){if(d.distance<0)continue;if((n||!o||d.distance<o.distance)&&(o=d,o.faceId=a/3,n))break}}return o},t.prototype.clone=function(i,r){var n=new t(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,i,r,(!1));return this.IsGlobal||(n._boundingInfo=new e.BoundingInfo(this.getBoundingInfo().minimum,this.getBoundingInfo().maximum)),n},t.prototype.dispose=function(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);var e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1)},t.CreateFromIndices=function(e,i,r,n,o){var s=Number.MAX_VALUE,a=-Number.MAX_VALUE;o=o||n;for(var h=o.getIndices(),c=i;c<i+r;c++){var l=h[c];l<s&&(s=l),l>a&&(a=l)}return new t(e,s,a-s+1,i,r,n,o)},t})();e.SubMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.updateSideOrientation=function(t,i){return t==e.Mesh.DOUBLESIDE?e.Mesh.DOUBLESIDE:void 0===t||null===t?e.Mesh.FRONTSIDE:t},t.CreateBox=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateBox(i);return o.applyToMesh(n,i.updatable),n},t.CreateSphere=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateSphere(i);return o.applyToMesh(n,i.updatable),n},t.CreateDisc=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateDisc(i);return o.applyToMesh(n,i.updatable),n},t.CreateIcoSphere=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateIcoSphere(i);return o.applyToMesh(n,i.updatable),n},t.CreateRibbon=function(t,i,r){var n=i.pathArray,o=i.closeArray,s=i.closePath,a=(i.offset,this.updateSideOrientation(i.sideOrientation,r)),h=i.instance,c=i.updatable;if(h){e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,e.Tmp.Vector3[0]),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,e.Tmp.Vector3[1]);var l=function(t){for(var i=n[0].length,r=0,o=h.sideOrientation===e.Mesh.DOUBLESIDE?2:1,s=1;s<=o;s++)for(var a=0;a<n.length;a++){var c=n[a],l=c.length;i=i<l?i:l;for(var u=0;u<i;)t[r]=c[u].x,t[r+1]=c[u].y,t[r+2]=c[u].z,c[u].x<e.Tmp.Vector3[0].x&&(e.Tmp.Vector3[0].x=c[u].x),c[u].x>e.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=c[u].x),c[u].y<e.Tmp.Vector3[0].y&&(e.Tmp.Vector3[0].y=c[u].y),c[u].y>e.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=c[u].y),c[u].z<e.Tmp.Vector3[0].z&&(e.Tmp.Vector3[0].z=c[u].z),c[u].z>e.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=c[u].z),u++,r+=3;h._closePath&&(t[r]=c[0].x,t[r+1]=c[0].y,t[r+2]=c[0].z,r+=3)}},u=h.getVerticesData(e.VertexBuffer.PositionKind);if(l(u),h._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),h._boundingInfo.update(h._worldMatrix),h.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),!h.areNormalsFrozen){var d=h.getIndices(),f=h.getVerticesData(e.VertexBuffer.NormalKind);if(e.VertexData.ComputeNormals(u,d,f),h._closePath)for(var p=0,m=0,_=0;_<n.length;_++)p=3*h._idx[_],m=_+1<n.length?3*(h._idx[_+1]-1):f.length-3,f[p]=.5*(f[p]+f[m]),f[p+1]=.5*(f[p+1]+f[m+1]),f[p+2]=.5*(f[p+2]+f[m+2]),f[m]=f[p],f[m+1]=f[p+1],f[m+2]=f[p+2];h.updateVerticesData(e.VertexBuffer.NormalKind,f,!1,!1)}return h}var g=new e.Mesh(t,r);g.sideOrientation=a;var v=e.VertexData.CreateRibbon(i);return s&&(g._idx=v._idx),g._closePath=s,g._closeArray=o,v.applyToMesh(g,c),g},t.CreateCylinder=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateCylinder(i);return o.applyToMesh(n,i.updatable),n},t.CreateTorus=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateTorus(i);return o.applyToMesh(n,i.updatable),n},t.CreateTorusKnot=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateTorusKnot(i);return o.applyToMesh(n,i.updatable),n},t.CreateLineSystem=function(t,i,r){var n=i.instance,o=i.lines;if(n){var s=function(e){for(var t=0,i=0;i<o.length;i++)for(var r=o[i],n=0;n<r.length;n++)e[t]=r[n].x,e[t+1]=r[n].y,e[t+2]=r[n].z,t+=3};return n.updateMeshPositions(s,!1),n}var a=new e.LinesMesh(t,r),h=e.VertexData.CreateLineSystem(i);return h.applyToMesh(a,i.updatable),a},t.CreateLines=function(e,i,r){var n=t.CreateLineSystem(e,{lines:[i.points],updatable:i.updatable,instance:i.instance},r);return n},t.CreateDashedLines=function(t,i,r){var n=i.points,o=i.instance,s=i.gapSize,a=(i.dashNb,i.dashSize);if(o){var h=function(t){var i=e.Vector3.Zero(),r=t.length/6,s=0,a=0,h=0,c=0,l=0,u=0,d=0,f=0;for(d=0;d<n.length-1;d++)n[d+1].subtractToRef(n[d],i),s+=i.length();for(h=s/r,c=o.dashSize*h/(o.dashSize+o.gapSize),d=0;d<n.length-1;d++)for(n[d+1].subtractToRef(n[d],i),a=Math.floor(i.length()/h),i.normalize(),f=0;f<a&&u<t.length;)l=h*f,t[u]=n[d].x+l*i.x,t[u+1]=n[d].y+l*i.y,t[u+2]=n[d].z+l*i.z,t[u+3]=n[d].x+(l+c)*i.x,t[u+4]=n[d].y+(l+c)*i.y,t[u+5]=n[d].z+(l+c)*i.z,u+=6,f++;for(;u<t.length;)t[u]=n[d].x,t[u+1]=n[d].y,t[u+2]=n[d].z,u+=3};return o.updateMeshPositions(h,!1),o}var c=new e.LinesMesh(t,r),l=e.VertexData.CreateDashedLines(i);return l.applyToMesh(c,i.updatable),c.dashSize=a,c.gapSize=s,c},t.ExtrudeShape=function(i,r,n){var o=r.path,s=r.shape,a=r.scale||1,h=r.rotation||0,c=0===r.cap?0:r.cap||e.Mesh.NO_CAP,l=r.updatable,u=this.updateSideOrientation(r.sideOrientation,n),d=r.instance,f=r.invertUV||!1;return t._ExtrudeShapeGeneric(i,s,o,a,h,null,null,!1,!1,c,!1,n,l,u,d,f)},t.ExtrudeShapeCustom=function(i,r,n){var o=r.path,s=r.shape,a=r.scaleFunction||function(){return 1},h=r.rotationFunction||function(){return 0},c=r.ribbonCloseArray||!1,l=r.ribbonClosePath||!1,u=0===r.cap?0:r.cap||e.Mesh.NO_CAP,d=r.updatable,f=this.updateSideOrientation(r.sideOrientation,n),p=r.instance,m=r.invertUV||!1;return t._ExtrudeShapeGeneric(i,s,o,null,null,a,h,c,l,u,!0,n,d,f,p,m)},t.CreateLathe=function(i,r,n){var o,s=r.arc<=0||r.arc>1?1:r.arc||1,a=void 0===r.closed||r.closed,h=r.shape,c=r.radius||1,l=r.tessellation||64,u=r.updatable,d=this.updateSideOrientation(r.sideOrientation,n),f=r.cap||e.Mesh.NO_CAP,p=2*Math.PI,m=new Array,_=r.invertUV||!1,g=0,v=0,y=p/l*s,x=new Array;for(g=0;g<=l;g++){var x=[];for(f!=e.Mesh.CAP_START&&f!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,h[0].y,0)),x.push(new e.Vector3(Math.cos(g*y)*h[0].x*c,h[0].y,Math.sin(g*y)*h[0].x*c))),v=0;v<h.length;v++)o=new e.Vector3(Math.cos(g*y)*h[v].x*c,h[v].y,Math.sin(g*y)*h[v].x*c),x.push(o);f!=e.Mesh.CAP_END&&f!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(Math.cos(g*y)*h[h.length-1].x*c,h[h.length-1].y,Math.sin(g*y)*h[h.length-1].x*c)),x.push(new e.Vector3(0,h[h.length-1].y,0))),m.push(x)}var b=t.CreateRibbon(i,{pathArray:m,closeArray:a,sideOrientation:d,updatable:u,invertUV:_},n);return b},t.CreatePlane=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreatePlane(i);if(o.applyToMesh(n,i.updatable),i.sourcePlane){n.translate(i.sourcePlane.normal,i.sourcePlane.d);var s=Math.acos(e.Vector3.Dot(i.sourcePlane.normal,e.Axis.Z)),a=e.Vector3.Cross(e.Axis.Z,i.sourcePlane.normal);n.rotate(a,s)}return n},t.CreateGround=function(t,i,r){var n=new e.GroundMesh(t,r);n._setReady(!1),n._subdivisionsX=i.subdivisionsX||i.subdivisions||1,n._subdivisionsY=i.subdivisionsY||i.subdivisions||1,n._width=i.width||1,n._height=i.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ;var o=e.VertexData.CreateGround(i);return o.applyToMesh(n,i.updatable),n._setReady(!0),n},t.CreateTiledGround=function(t,i,r){var n=new e.Mesh(t,r),o=e.VertexData.CreateTiledGround(i);return o.applyToMesh(n,i.updatable),n},t.CreateGroundFromHeightMap=function(t,i,r,n){var o=r.width||10,s=r.height||10,a=r.subdivisions||1,h=r.minHeight||0,c=r.maxHeight||10,l=r.updatable,u=r.onReady,d=new e.GroundMesh(t,n);d._subdivisionsX=a,d._subdivisionsY=a,d._width=o,d._height=s,d._maxX=d._width/2,d._maxZ=d._height/2,d._minX=-d._maxX,d._minZ=-d._maxZ,d._setReady(!1);var f=function(t){var i=document.createElement("canvas"),r=i.getContext("2d"),n=t.width,f=t.height;i.width=n,i.height=f,r.drawImage(t,0,0);var p=r.getImageData(0,0,n,f).data,m=e.VertexData.CreateGroundFromHeightMap({width:o,height:s,subdivisions:a,minHeight:h,maxHeight:c,buffer:p,bufferWidth:n,bufferHeight:f});m.applyToMesh(d,l),d._setReady(!0),u&&u(d)};return e.Tools.LoadImage(i,f,(function(){}),n.database),d},t.CreateTube=function(i,r,n){var o=r.path,s=r.radius||1,a=r.tessellation||64,h=r.radiusFunction,c=r.cap||e.Mesh.NO_CAP,l=r.invertUV||!1,u=r.updatable,d=this.updateSideOrientation(r.sideOrientation,n),f=r.instance;r.arc=r.arc<=0||r.arc>1?1:r.arc||1;var p,m,_=function(t,i,r,n,o,s,a,h){for(var c,l,u,d,f=i.getTangents(),p=i.getNormals(),m=i.getDistances(),_=2*Math.PI,g=_/o*h,v=function(){return n},y=s||v,x=e.Tmp.Matrix[0],b=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,T=0;T<t.length;T++){l=y(T,m[T]),c=Array(),u=p[T];for(var A=0;A<o;A++)e.Matrix.RotationAxisToRef(f[T],g*A,x),d=c[A]?c[A]:e.Vector3.Zero(),e.Vector3.TransformCoordinatesToRef(u,x,d),d.scaleInPlace(l).addInPlace(t[T]),c[A]=d;r[b]=c,b++}var E=function(e,i){for(var r=Array(),n=0;n<e;n++)r.push(t[i]);return r};switch(a){case e.Mesh.NO_CAP:break;case e.Mesh.CAP_START:r[0]=E(o,0),r[1]=r[2].slice(0);break;case e.Mesh.CAP_END:r[b]=r[b-1].slice(0),r[b+1]=E(o,t.length-1);break;case e.Mesh.CAP_ALL:r[0]=E(o,0),r[1]=r[2].slice(0),r[b]=r[b-1].slice(0),r[b+1]=E(o,t.length-1)}return r};if(f){var g=r.arc||f.arc;return p=f.path3D.update(o),m=_(o,p,f.pathArray,s,f.tessellation,h,f.cap,g),f=t.CreateRibbon(null,{pathArray:m,instance:f}),f.path3D=p,f.pathArray=m,f.arc=g,f}p=new e.Path3D(o);var v=new Array;c=c<0||c>3?0:c,m=_(o,p,v,s,a,h,c,r.arc);var y=t.CreateRibbon(i,{pathArray:m,closePath:!0,closeArray:!1,updatable:u,sideOrientation:d,invertUV:l},n);return y.pathArray=m,y.path3D=p,y.tessellation=a,y.cap=c,y.arc=r.arc,y},t.CreatePolyhedron=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreatePolyhedron(i);return o.applyToMesh(n,i.updatable),n},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),h=r.normal||e.Vector3.Up(),c=r.size||new e.Vector3(1,1,1),l=r.angle||0;if(!h){var u=new e.Vector3(0,0,1),d=i.getScene().activeCamera,f=e.Vector3.TransformCoordinates(u,d.getWorldMatrix());h=d.globalPosition.subtract(f)}var p=-Math.atan2(h.z,h.x)-Math.PI/2,m=Math.sqrt(h.x*h.x+h.z*h.z),_=Math.atan2(h.y,m),g=e.Matrix.RotationYawPitchRoll(p,_,l).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(g),y=i.getWorldMatrix(),x=y.multiply(v),b=new e.VertexData;b.indices=[],b.positions=[],b.normals=[],b.uvs=[];for(var T=0,A=function(t){var i=n[t],r=new e.PositionNormalVertex;return r.position=new e.Vector3(o[3*i],o[3*i+1],o[3*i+2]),r.position=e.Vector3.TransformCoordinates(r.position,x),r.normal=new e.Vector3(s[3*i],s[3*i+1],s[3*i+2]),r},E=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(c,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s<t.length;s+=3){var a,h,l,u,d,f,p,m=0,_=e.Vector3.Dot(t[s].position,i)-r,g=e.Vector3.Dot(t[s+1].position,i)-r,v=e.Vector3.Dot(t[s+2].position,i)-r;switch(a=_>0,h=g>0,l=v>0,m=(a?1:0)+(h?1:0)+(l?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],d=t[s+2],f=n(t[s],u),p=n(t[s],d)),h){u=t[s],d=t[s+2],f=n(t[s+1],u),p=n(t[s+1],d),o.push(f),o.push(d.clone()),o.push(u.clone()),o.push(d.clone()),o.push(f.clone()),o.push(p);break}l&&(u=t[s],d=t[s+1],f=n(t[s+2],u),p=n(t[s+2],d)),o.push(u.clone()),o.push(d.clone()),o.push(f),o.push(p),o.push(f.clone()),o.push(d.clone());break;case 2:a||(u=t[s].clone(),d=n(u,t[s+1]),f=n(u,t[s+2]),o.push(u),o.push(d),o.push(f)),h||(u=t[s+1].clone(),d=n(u,t[s+2]),f=n(u,t[s]),o.push(u),o.push(d),o.push(f)),l||(u=t[s+2].clone(),d=n(u,t[s]),f=n(u,t[s+1]),o.push(u),o.push(d),o.push(f));break;case 3:}}return o},P=0;P<n.length;P+=3){var M=new Array;if(M.push(A(P)),M.push(A(P+1)),M.push(A(P+2)),M=E(M,new e.Vector3(1,0,0)),M=E(M,new e.Vector3((-1),0,0)),M=E(M,new e.Vector3(0,1,0)),M=E(M,new e.Vector3(0,(-1),0)),M=E(M,new e.Vector3(0,0,1)),M=E(M,new e.Vector3(0,0,(-1))),0!==M.length)for(var S=0;S<M.length;S++){var C=M[S];b.indices.push(T),C.position.toArray(b.positions,3*T),C.normal.toArray(b.normals,3*T),b.uvs.push(.5+C.position.x/c.x),b.uvs.push(.5+C.position.y/c.y),T++}}var R=new e.Mesh(t,i.getScene());return b.applyToMesh(R),R.position=a.clone(),R.rotation=new e.Vector3(_,p,l),R},t._ExtrudeShapeGeneric=function(i,r,n,o,s,a,h,c,l,u,d,f,p,m,_,g){var v,y,x=function(t,i,r,n,o,s,a,h,c,l){for(var u=r.getTangents(),d=r.getNormals(),f=r.getBinormals(),p=r.getDistances(),m=0,_=function(){return o},g=function(){return s},v=l?h:g,y=l?a:_,x=c===e.Mesh.NO_CAP||c===e.Mesh.CAP_END?0:2,b=e.Tmp.Matrix[0],T=0;T<i.length;T++){for(var A=new Array,E=v(T,p[T]),P=y(T,p[T]),M=0;M<t.length;M++){e.Matrix.RotationAxisToRef(u[T],m,b);var S=u[T].scale(t[M].z).add(d[T].scale(t[M].x)).add(f[T].scale(t[M].y)),C=A[M]?A[M]:e.Vector3.Zero();e.Vector3.TransformCoordinatesToRef(S,b,C),C.scaleInPlace(P).addInPlace(i[T]),A[M]=C}n[x]=A,m+=E,x++}var R=function(t){var i,r=Array(),n=e.Vector3.Zero();for(i=0;i<t.length;i++)n.addInPlace(t[i]);for(n.scaleInPlace(1/t.length),i=0;i<t.length;i++)r.push(n);return r};switch(c){case e.Mesh.NO_CAP:break;case e.Mesh.CAP_START:n[0]=R(n[2]),n[1]=n[2].slice(0);break;case e.Mesh.CAP_END:n[x]=n[x-1],n[x+1]=R(n[x-1]);break;case e.Mesh.CAP_ALL:n[0]=R(n[2]),n[1]=n[2].slice(0),n[x]=n[x-1],n[x+1]=R(n[x-1])}return n};if(_)return v=_.path3D.update(n),y=x(r,n,_.path3D,_.pathArray,o,s,a,h,_.cap,d),_=e.Mesh.CreateRibbon(null,y,null,null,null,f,null,null,_);v=new e.Path3D(n);var b=new Array;u=u<0||u>3?0:u,y=x(r,n,v,b,o,s,a,h,u,d);var T=t.CreateRibbon(i,{pathArray:y,closeArray:c,closePath:l,updatable:p,sideOrientation:m,invertUV:g},f);return T.pathArray=y,T.path3D=v,T.cap=u,T},t})();e.MeshBuilder=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.hasAlpha=!1,this.getAlphaFromRGB=!1,this.level=1,this.coordinatesIndex=0,this.coordinatesMode=e.Texture.EXPLICIT_MODE,this.wrapU=e.Texture.WRAP_ADDRESSMODE,this.wrapV=e.Texture.WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.isCube=!1,this.isRenderTarget=!1,this.animations=new Array,this.onDisposeObservable=new e.Observable,this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this._scene=t,this._scene.textures.push(this),this._uid=null}return Object.defineProperty(t.prototype,"uid",{get:function(){return this._uid||(this._uid=e.Tools.RandomId()),this._uid},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return this.name},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getTextureMatrix=function(){return null},t.prototype.getReflectionTextureMatrix=function(){return null},t.prototype.getInternalTexture=function(){return this._texture},t.prototype.isReady=function(){return this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED||!!this._texture&&this._texture.isReady},t.prototype.getSize=function(){return this._texture._width?new e.Size(this._texture._width,this._texture._height):this._texture._size?new e.Size(this._texture._size,this._texture._size):e.Size.Zero()},t.prototype.getBaseSize=function(){return this.isReady()&&this._texture?this._texture._size?new e.Size(this._texture._size,this._texture._size):new e.Size(this._texture._baseWidth,this._texture._baseHeight):e.Size.Zero()},t.prototype.scale=function(e){},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),t.prototype._removeFromCache=function(e,t){for(var i=this._scene.getEngine().getLoadedTexturesCache(),r=0;r<i.length;r++){var n=i[r];if(n.url===e&&n.noMipmap===t)return void i.splice(r,1)}},t.prototype._getFromCache=function(e,t,i){for(var r=this._scene.getEngine().getLoadedTexturesCache(),n=0;n<r.length;n++){var o=r[n];if(o.url===e&&o.noMipmap===t&&(!i||i===o.samplingMode))return o.references++,o}return null},t.prototype.delayLoad=function(){},t.prototype.clone=function(){return null},t.prototype.releaseInternalTexture=function(){this._texture&&(this._scene.getEngine().releaseInternalTexture(this._texture),delete this._texture)},t.prototype.dispose=function(){this.getScene().stopAnimation(this);var e=this._scene.textures.indexOf(this);e>=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"hasAlpha",void 0),__decorate([e.serialize()],t.prototype,"getAlphaFromRGB",void 0),__decorate([e.serialize()],t.prototype,"level",void 0),__decorate([e.serialize()],t.prototype,"coordinatesIndex",void 0),__decorate([e.serialize()],t.prototype,"coordinatesMode",void 0),__decorate([e.serialize()],t.prototype,"wrapU",void 0),__decorate([e.serialize()],t.prototype,"wrapV",void 0),__decorate([e.serialize()],t.prototype,"anisotropicFilteringLevel",void 0),__decorate([e.serialize()],t.prototype,"isCube",void 0),__decorate([e.serialize()],t.prototype,"isRenderTarget",void 0),t})();e.BaseTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a,h,c,l,u){var d=this;if(void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=i.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=null),void 0===c&&(c=null),void 0===l&&(l=null),void 0===u&&(u=!1),t.call(this,n),this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.name=r,this.url=r,this._noMipmap=o,this._invertY=s,this._samplingMode=a,this._buffer=l,this._deleteBuffer=u,r){this._texture=this._getFromCache(r,o,a);var f=function(){d._onLoadObservarble&&d._onLoadObservarble.hasObservers()&&d.onLoadObservable.notifyObservers(!0),h&&h()};this._texture?this._texture.isReady?e.Tools.SetImmediate((function(){return f()})):this._texture.onLoadedCallbacks.push(f):n.useDelayedTextureLoading?(this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=f,this._delayedOnError=c):(this._texture=n.getEngine().createTexture(r,o,s,n,this._samplingMode,f,c,this._buffer),u&&delete this._buffer)}}return __extends(i,t),Object.defineProperty(i.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!0,configurable:!0}),i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this._samplingMode),this._texture||(this._texture=this.getScene().getEngine().createTexture(this.url,this._noMipmap,this._invertY,this.getScene(),this._samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer),this._deleteBuffer&&delete this._buffer))},i.prototype.updateSamplingMode=function(e){this._texture&&(this._samplingMode=e,this.getScene().getEngine().updateTextureSamplingMode(e,this._texture))},i.prototype._prepareRowForTextureGeneration=function(t,i,r,n){t*=this.uScale,i*=this.vScale,t-=.5*this.uScale,i-=.5*this.vScale,r-=.5,e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,this._rowGenerationMatrix,n),n.x+=.5*this.uScale+this.uOffset,n.y+=.5*this.vScale+this.vOffset,n.z+=.5},i.prototype.getTextureMatrix=function(){return this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng?this._cachedTextureMatrix:(this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedTextureMatrix||(this._cachedTextureMatrix=e.Matrix.Zero(),this._rowGenerationMatrix=new e.Matrix,this._t0=e.Vector3.Zero(),this._t1=e.Vector3.Zero(),this._t2=e.Vector3.Zero()),e.Matrix.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),e.Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix.m[0]=this._t1.x,this._cachedTextureMatrix.m[1]=this._t1.y,this._cachedTextureMatrix.m[2]=this._t1.z,this._cachedTextureMatrix.m[4]=this._t2.x,this._cachedTextureMatrix.m[5]=this._t2.y,this._cachedTextureMatrix.m[6]=this._t2.z,this._cachedTextureMatrix.m[8]=this._t0.x,this._cachedTextureMatrix.m[9]=this._t0.y,this._cachedTextureMatrix.m[10]=this._t0.z,this._cachedTextureMatrix)},i.prototype.getReflectionTextureMatrix=function(){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.coordinatesMode===this._cachedCoordinatesMode)return this._cachedTextureMatrix;switch(this._cachedTextureMatrix||(this._cachedTextureMatrix=e.Matrix.Zero(),this._projectionModeMatrix=e.Matrix.Zero()),this._cachedCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case i.PLANAR_MODE:e.Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix[0]=this.uScale,this._cachedTextureMatrix[5]=this.vScale,this._cachedTextureMatrix[12]=this.uOffset,this._cachedTextureMatrix[13]=this.vOffset;break;case i.PROJECTION_MODE:e.Matrix.IdentityToRef(this._projectionModeMatrix),this._projectionModeMatrix.m[0]=.5,this._projectionModeMatrix.m[5]=-.5,this._projectionModeMatrix.m[10]=0,this._projectionModeMatrix.m[12]=.5,this._projectionModeMatrix.m[13]=.5,this._projectionModeMatrix.m[14]=1,this._projectionModeMatrix.m[15]=1,this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix,this._cachedTextureMatrix);break;default:e.Matrix.IdentityToRef(this._cachedTextureMatrix)}return this._cachedTextureMatrix},i.prototype.clone=function(){var t=this;return e.SerializationHelper.Clone((function(){return new i(t._texture.url,t.getScene(),t._noMipmap,t._invertY,t._samplingMode)}),this)},Object.defineProperty(i.prototype,"onLoadObservable",{get:function(){return this._onLoadObservarble||(this._onLoadObservarble=new e.Observable),this._onLoadObservarble},enumerable:!0,configurable:!0}),i.CreateFromBase64String=function(e,t,r,n,o,s,a,h){return void 0===s&&(s=i.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===h&&(h=null),new i("data:"+t,r,n,o,s,a,h,e)},i.Parse=function(t,r,n){if(t.customType){var o=e.Tools.Instantiate(t.customType);return o.Parse(t,r,n)}if(t.isCube)return e.CubeTexture.Parse(t,r,n);if(!t.name&&!t.isRenderTarget)return null;var s=e.SerializationHelper.Parse((function(){if(t.mirrorPlane){var o=new e.MirrorTexture(t.name,t.renderTargetSize,r);return o._waitingRenderList=t.renderList,o.mirrorPlane=e.Plane.FromArray(t.mirrorPlane),o}if(t.isRenderTarget){var s=new e.RenderTargetTexture(t.name,t.renderTargetSize,r);return s._waitingRenderList=t.renderList,s}var a;return a=t.base64String?i.CreateFromBase64String(t.base64String,t.name,r):new i(n+t.name,r)}),t,r);if(t.animations)for(var a=0;a<t.animations.length;a++){var h=t.animations[a];s.animations.push(e.Animation.Parse(h))}return s},i.LoadFromDataString=function(e,t,r,n,o,s,a,h,c){return void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=i.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=null),void 0===c&&(c=null),"data:"!==e.substr(0,5)&&(e="data:"+e),new i(e,r,o,s,a,h,c,t,n)},i.NEAREST_SAMPLINGMODE=1,i.BILINEAR_SAMPLINGMODE=2,i.TRILINEAR_SAMPLINGMODE=3,i.EXPLICIT_MODE=0,i.SPHERICAL_MODE=1,i.PLANAR_MODE=2,i.CUBIC_MODE=3,i.PROJECTION_MODE=4,i.SKYBOX_MODE=5,i.INVCUBIC_MODE=6,i.EQUIRECTANGULAR_MODE=7,i.FIXED_EQUIRECTANGULAR_MODE=8,i.CLAMP_ADDRESSMODE=0,i.WRAP_ADDRESSMODE=1,i.MIRROR_ADDRESSMODE=2,__decorate([e.serialize()],i.prototype,"url",void 0),__decorate([e.serialize()],i.prototype,"uOffset",void 0),__decorate([e.serialize()],i.prototype,"vOffset",void 0),__decorate([e.serialize()],i.prototype,"uScale",void 0),__decorate([e.serialize()],i.prototype,"vScale",void 0),__decorate([e.serialize()],i.prototype,"uAng",void 0),__decorate([e.serialize()],i.prototype,"vAng",void 0),__decorate([e.serialize()],i.prototype,"wAng",void 0),i})(e.BaseTexture);e.Texture=t;
})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){if(void 0===a&&(a=null),void 0===h&&(h=null),t.call(this,r),this.coordinatesMode=e.Texture.CUBIC_MODE,this.name=i,this.url=i,this._noMipmap=o,this.hasAlpha=!1,i||s){if(this._texture=this._getFromCache(i,o),!s){n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[];for(var c=0;c<n.length;c++)s.push(i+n[c]);this._extensions=n}this._files=s,this._texture?a&&(this._texture.isReady?e.Tools.SetImmediate((function(){return a()})):this._texture.onLoadedCallbacks.push(a)):r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this._texture=r.getEngine().createCubeTexture(i,r,s,o,a,h),this.isCube=!0,this._textureMatrix=e.Matrix.Identity()}}return __extends(i,t),i.CreateFromImages=function(e,t,r){return new i("",t,null,r,e)},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||(this._texture=this.getScene().getEngine().createCubeTexture(this.url,this.getScene(),this._files,this._noMipmap)))},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.Parse=function(t,i,r){var n=e.SerializationHelper.Parse((function(){return new e.CubeTexture(r+t.name,i,t.extensions)}),t,i);if(t.animations)for(var o=0;o<t.animations.length;o++){var s=t.animations[o];n.animations.push(e.Animation.Parse(s))}return n},i.prototype.clone=function(){var t=this;return e.SerializationHelper.Clone((function(){return new i(t.url,t.getScene(),t._extensions,t._noMipmap,t._files)}),this)},i})(e.BaseTexture);e.CubeTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c,l,u){void 0===s&&(s=!0),void 0===a&&(a=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=!0),void 0===u&&(u=!1),t.call(this,null,n,!o),this.isCube=h,this.renderList=new Array,this.renderParticles=!0,this.renderSprites=!1,this.coordinatesMode=e.Texture.PROJECTION_MODE,this.onAfterUnbindObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onClearObservable=new e.Observable,this._currentRefreshId=-1,this._refreshRate=1,this.name=i,this.isRenderTarget=!0,this._size=r,this._generateMipMaps=o,this._doNotChangeAspectRatio=s,c===e.Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE),h?(this._texture=n.getEngine().createRenderTargetCubeTexture(r,{generateMipMaps:o,samplingMode:c,generateDepthBuffer:l,generateStencilBuffer:u}),this.coordinatesMode=e.Texture.INVCUBIC_MODE,this._textureMatrix=e.Matrix.Identity()):this._texture=n.getEngine().createRenderTargetTexture(r,{generateMipMaps:o,type:a,samplingMode:c,generateDepthBuffer:l,generateStencilBuffer:u}),this._renderingManager=new e.RenderingManager(n)}return __extends(i,t),Object.defineProperty(i,"REFRESHRATE_RENDER_ONCE",{get:function(){return i._REFRESHRATE_RENDER_ONCE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"REFRESHRATE_RENDER_ONEVERYFRAME",{get:function(){return i._REFRESHRATE_RENDER_ONEVERYFRAME},enumerable:!0,configurable:!0}),Object.defineProperty(i,"REFRESHRATE_RENDER_ONEVERYTWOFRAMES",{get:function(){return i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onAfterUnbind",{set:function(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onClear",{set:function(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)},enumerable:!0,configurable:!0}),i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.isReady=function(){return!!this.getScene().renderTargetsEnabled&&t.prototype.isReady.call(this)},i.prototype.getRenderSize=function(){return this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this._size*e;this.resize(t,this._generateMipMaps)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e,t){this.releaseInternalTexture(),this.isCube?this._texture=this.getScene().getEngine().createRenderTargetCubeTexture(e):this._texture=this.getScene().getEngine().createRenderTargetTexture(e,t)},i.prototype.render=function(e,t){var i=this.getScene();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(!0)),this._waitingRenderList){this.renderList=[];for(var r=0;r<this._waitingRenderList.length;r++){var n=this._waitingRenderList[r];this.renderList.push(i.getMeshByID(n))}delete this._waitingRenderList}if(this.renderListPredicate){this.renderList.splice(0);for(var o=this.getScene().meshes,r=0;r<o.length;r++){var s=o[r];this.renderListPredicate(s)&&this.renderList.push(s)}}if(!this.renderList||0!==this.renderList.length){this._renderingManager.reset();for(var a=this.renderList?this.renderList:i.getActiveMeshes().data,h=this.renderList?this.renderList.length:i.getActiveMeshes().length,c=i.getRenderId(),l=0;l<h;l++){var s=a[l];if(s){if(!s.isReady()){this.resetRefreshCounter();continue}if(s._preActivateForIntermediateRendering(c),s.isEnabled()&&s.isVisible&&s.subMeshes&&0!==(s.layerMask&i.activeCamera.layerMask)){s._activate(c);for(var u=0;u<s.subMeshes.length;u++){var d=s.subMeshes[u];i._activeIndices.addCount(d.indexCount,!1),this._renderingManager.dispatch(d)}}}}if(this.isCube)for(var f=0;f<6;f++)this.renderToTarget(f,a,h,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,a,h,e,t);this.onAfterUnbindObservable.notifyObservers(this),this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),i.resetCachedMaterial()}},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene(),a=s.getEngine();n&&s.postProcessManager._prepareFrame(this._texture)||(this.isCube?a.bindFramebuffer(this._texture,t):a.bindFramebuffer(this._texture)),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this.onAfterRenderObservable.notifyObservers(t),o&&e.Tools.DumpFramebuffer(this._size,this._size,a),this.isCube&&5!==t||(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),a.unBindFramebuffer(this._texture,this.isCube))},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t)},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.renderList=this.renderList.slice(0),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);e.renderTargetSize=this.getRenderSize(),e.renderList=[];for(var i=0;i<this.renderList.length;i++)e.renderList.push(this.renderList[i].id);return e},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){void 0===a&&(a=!0),void 0===h&&(h=!1),t.call(this,null,o,!a),this.isCube=h,this.isEnabled=!0,this._currentRefreshId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._textures=new Array,this._floats=new Array,this._floatsArrays={},this._colors3=new Array,this._colors4=new Array,this._vectors2=new Array,this._vectors3=new Array,this._matrices=new Array,this._fallbackTextureUsed=!1,o._proceduralTextures.push(this),this.name=i,this.isRenderTarget=!0,this._size=r,this._generateMipMaps=a,this.setFragment(n),this._fallbackTexture=s;var c=o.getEngine();h?(this._texture=c.createRenderTargetCubeTexture(r,{generateMipMaps:a}),this.setFloat("face",0)):this._texture=c.createRenderTargetTexture(r,a);var l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(c,l,e.VertexBuffer.PositionKind,(!1),(!1),2);var u=[];u.push(0),u.push(1),u.push(2),u.push(0),u.push(2),u.push(3),this._indexBuffer=c.createIndexBuffer(u)}return __extends(i,t),i.prototype.reset=function(){if(void 0!==this._effect){var e=this.getScene().getEngine();e._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this.getScene().getEngine();return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",null,null,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture.references++),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this.getScene().getEngine().createRenderTargetTexture(e,t))},i.prototype._checkUniform=function(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(e){var t=this.getScene(),i=t.getEngine();i.enableEffect(this._effect),i.setState(!1);for(var r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);if(i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this.isCube)for(var o=0;o<6;o++)i.bindFramebuffer(this._texture,o),this._effect.setFloat("face",o),i.clear(t.clearColor,!0,!0,!0),i.draw(!0,0,6),5===o&&i.generateMipMapsForCubemap(this._texture);else i.bindFramebuffer(this._texture),i.clear(t.clearColor,!0,!0,!0),i.draw(!0,0,6);i.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene()._proceduralTextures.indexOf(this);i>=0&&this.getScene()._proceduralTextures.splice(i,1);var r=this._vertexBuffers[e.VertexBuffer.PositionKind];r&&(r.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this.getScene().getEngine()._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)},i})(e.Texture);e.ProceduralTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,r,n,o,!0),this.mirrorPlane=new e.Plane(0,1,0,1),this._transformMatrix=e.Matrix.Zero(),this._mirrorMatrix=e.Matrix.Zero(),this.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(s.mirrorPlane,s._mirrorMatrix),s._savedViewMatrix=n.getViewMatrix(),s._mirrorMatrix.multiplyToRef(s._savedViewMatrix,s._transformMatrix),n.setTransformMatrix(s._transformMatrix,n.getProjectionMatrix()),n.clipPlane=s.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.position,s._mirrorMatrix)})),this.onAfterRenderObservable.add((function(){n.setTransformMatrix(s._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane}))}return __extends(i,t),i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.mirrorPlane=this.mirrorPlane.clone(),t.renderList=this.renderList.slice(0),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i})(e.RenderTargetTexture);e.MirrorTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,r,n,o,!0),this.refractionPlane=new e.Plane(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),this.onAfterRenderObservable.add((function(){delete n.clipPlane}))}return __extends(i,t),i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.refractionPlane=this.refractionPlane.clone(),t.renderList=this.renderList.slice(0),t.depth=this.depth,t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,n,!o),this.name=i,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=o,r.getContext?(this._canvas=r,this._texture=n.getEngine().createDynamicTexture(r.width,r.height,o,s)):(this._canvas=document.createElement("canvas"),r.width?this._texture=n.getEngine().createDynamicTexture(r.width,r.height,o,s):this._texture=n.getEngine().createDynamicTexture(r,r,o,s));var a=this.getSize();this._canvas.width=a.width,this._canvas.height=a.height,this._context=this._canvas.getContext("2d")}return __extends(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._canvas.width=t.width,this._canvas.height=t.height,this.releaseInternalTexture(),this._texture=this.getScene().getEngine().createDynamicTexture(t.width,t.height,this._generateMipMaps,this._samplingMode)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e){this.getScene().getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var h=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,h.width,h.height)),this._context.font=r,null===t){var c=this._context.measureText(e);t=(h.width-c.width)/2}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t},i})(e.Texture);e.DynamicTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,n,!o,s),this._autoLaunch=!0;var c;this.name=i,r instanceof HTMLVideoElement?this.video=r:(c=r,this.video=document.createElement("video"),this.video.autoplay=!1,this.video.loop=!0),this._generateMipMaps=o,this._samplingMode=a,e.Tools.IsExponentOfTwo(this.video.videoWidth)&&e.Tools.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=e.Texture.WRAP_ADDRESSMODE,this.wrapV=e.Texture.WRAP_ADDRESSMODE):(this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),c?(this.video.addEventListener("canplaythrough",(function(){h._createTexture()})),c.forEach((function(e){var t=document.createElement("source");t.src=e,h.video.appendChild(t)}))):this._createTexture(),this._lastUpdate=e.Tools.Now}return __extends(i,t),i.prototype._createTexture=function(){this._texture=this.getScene().getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this._samplingMode),this._texture.isReady=!0},i.prototype.update=function(){this._autoLaunch&&(this._autoLaunch=!1,this.video.play());var t=e.Tools.Now;return!(t-this._lastUpdate<15||this.video.readyState!==this.video.HAVE_ENOUGH_DATA)&&(this._lastUpdate=t,this.getScene().getEngine().updateVideoTexture(this._texture,this.video,this._invertY),!0)},i})(e.Texture);e.VideoTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){t.call(this,e,r,null,n,o,s),this._animate=!0,this._time=0,this._texturePath=i,this.loadJson(i),this.refreshRate=1}return __extends(i,t),i.prototype.loadJson=function(t){function i(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{n.setFragment(n._texturePath)}catch(i){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}}var r=this,n=this,o=t+"/config.json",s=new XMLHttpRequest;s.open("GET",o,!0),s.addEventListener("load",(function(){if(200===s.status||e.Tools.ValidateXHRData(s,1))try{r._config=JSON.parse(s.response),r.updateShaderUniforms(),r.updateTextures(),r.setFragment(r._texturePath+"/custom"),r._animate=r._config.animate,r.refreshRate=r._config.refreshrate}catch(t){i()}else i()}),!1),s.addEventListener("error",(function(){i()}),!1);try{s.send()}catch(a){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){var i=this._textures[e];if(!i.isReady())return!1}return!0},i.prototype.render=function(e){this._animate&&(this._time+=.03*this.getScene().getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t<this._config.sampler2Ds.length;t++)this.setTexture(this._config.sampler2Ds[t].sample2Dname,new e.Texture(this._texturePath+"/"+this._config.sampler2Ds[t].textureRelativeUrl,this.getScene()))},i.prototype.updateShaderUniforms=function(){if(this._config)for(var t=0;t<this._config.uniforms.length;t++){var i=this._config.uniforms[t];switch(i.type){case"float":this.setFloat(i.name,i.value);break;case"color3":this.setColor3(i.name,new e.Color3(i.r,i.g,i.b));break;case"color4":this.setColor4(i.name,new e.Color4(i.r,i.g,i.b,i.a));break;case"vector2":this.setVector2(i.name,new e.Vector2(i.x,i.y));break;case"vector3":this.setVector3(i.name,new e.Vector3(i.x,i.y,i.z))}}this.setFloat("time",this._time)},Object.defineProperty(i.prototype,"animate",{get:function(){return this._animate},set:function(e){this._animate=e},enumerable:!0,configurable:!0}),i})(e.ProceduralTexture);e.CustomProceduralTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._defines={},this._currentRank=32,this._maxRank=-1}return t.prototype.addFallback=function(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},t.prototype.addCPUSkinningFallback=function(e,t){this._meshRank=e,this._mesh=t,e>this._maxRank&&(this._maxRank=e)},Object.defineProperty(t.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),t.prototype.reduce=function(t){for(var i=this._defines[this._currentRank],r=0;r<i.length;r++)t=t.replace("#define "+i[r],"");return this._mesh&&this._currentRank===this._meshRank&&(this._mesh.computeBonesUsingShaders=!1,t=t.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),e.Tools.Log("Falling back to CPU skinning for "+this._mesh.name)),this._currentRank++,t},t})();e.EffectFallbacks=t;var i=(function(){function t(e,t,i,r,n,o,s,a,h,c){var l=this;this._isReady=!1,this._compilationError="",this._valueCache={},this._engine=n,this.name=e,this.defines=o,this._uniformsNames=i.concat(r),this._samplers=r,this._attributesNames=t,this.onError=h,this.onCompiled=a,this._indexParameters=c;var u,d;e.vertexElement?(u=document.getElementById(e.vertexElement),u||(u=e.vertexElement)):u=e.vertex||e,e.fragmentElement?(d=document.getElementById(e.fragmentElement),d||(d=e.fragmentElement)):d=e.fragment||e,this._loadVertexShader(u,(function(e){l._processIncludes(e,(function(e){l._loadFragmentShader(d,(function(i){l._processIncludes(i,(function(i){l._prepareEffect(e,i,t,o,s)}))}))}))}))}return t.prototype.isReady=function(){return this._isReady},t.prototype.getProgram=function(){return this._program},t.prototype.getAttributesNames=function(){return this._attributesNames},t.prototype.getAttributeLocation=function(e){return this._attributes[e]},t.prototype.getAttributeLocationByName=function(e){var t=this._attributesNames.indexOf(e);return this._attributes[t]},t.prototype.getAttributesCount=function(){return this._attributes.length},t.prototype.getUniformIndex=function(e){return this._uniformsNames.indexOf(e)},t.prototype.getUniform=function(e){return this._uniforms[this._uniformsNames.indexOf(e)]},t.prototype.getSamplers=function(){return this._samplers},t.prototype.getCompilationError=function(){return this._compilationError},t.prototype.getVertexShaderSource=function(){return this._engine.getVertexShaderSource(this._program)},t.prototype.getFragmentShaderSource=function(){return this._engine.getFragmentShaderSource(this._program)},t.prototype._loadVertexShader=function(i,r){if(i instanceof HTMLElement){var n=e.Tools.GetDOMTextContent(i);return void r(n)}if("base64:"===i.substr(0,7)){var o=window.atob(i.substr(7));return void r(o)}if(t.ShadersStore[i+"VertexShader"])return void r(t.ShadersStore[i+"VertexShader"]);var s;s="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,e.Tools.LoadFile(s+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(i instanceof HTMLElement){var n=e.Tools.GetDOMTextContent(i);return void r(n)}if("base64:"===i.substr(0,7)){var o=window.atob(i.substr(7));return void r(o)}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var s;s="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,e.Tools.LoadFile(s+".fragment.fx",r)},t.prototype._dumpShadersName=function(){this.name.vertexElement?(e.Tools.Error("Vertex shader:"+this.name.vertexElement),e.Tools.Error("Fragment shader:"+this.name.fragmentElement)):this.name.vertex?(e.Tools.Error("Vertex shader:"+this.name.vertex),e.Tools.Error("Fragment shader:"+this.name.fragment)):(e.Tools.Error("Vertex shader:"+this.name),e.Tools.Error("Fragment shader:"+this.name))},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var h=s[1];if(!t.IncludesShadersStore[h]){var c=e.Engine.ShadersRepository+"ShadersInclude/"+h+".fx";return void e.Tools.LoadFile(c,(function(e){t.IncludesShadersStore[h]=e,n._processIncludes(a,r)}))}var l=t.IncludesShadersStore[h];if(s[2])for(var u=s[3].split(","),d=0;d<u.length;d+=2){var f=new RegExp(u[d],"g"),p=u[d+1];l=l.replace(f,p)}if(s[4]){var m=s[5];if(m.indexOf("..")!==-1){var _=m.split(".."),g=parseInt(_[0]),v=parseInt(_[1]),y=l.slice(0);l="",isNaN(v)&&(v=this._indexParameters[_[1]]);for(var x=g;x<=v;x++)l+=y.replace(/\{X\}/g,x)+"\n"}else l=l.replace(/\{X\}/g,m)}a=a.replace(s[0],l),s=o.exec(i)}r(a)},t.prototype._processPrecision=function(e){return e.indexOf("precision highp float")===-1?e=this._engine.getCaps().highPrecisionShaderSupported?"precision highp float;\n"+e:"precision mediump float;\n"+e:this._engine.getCaps().highPrecisionShaderSupported||(e=e.replace("precision highp float","precision mediump float")),e},t.prototype._prepareEffect=function(t,i,r,n,o){try{var s=this._engine;t=this._processPrecision(t),i=this._processPrecision(i),this._program=s.createShaderProgram(t,i,n),this._uniforms=s.getUniforms(this._program,this._uniformsNames),this._attributes=s.getAttributes(this._program,r);var a;for(a=0;a<this._samplers.length;a++){var h=this.getUniform(this._samplers[a]);null==h&&(this._samplers.splice(a,1),a--)}s.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this)}catch(c){this._compilationError=c.message,e.Tools.Error("Unable to compile effect: "),e.Tools.Error("Defines: "+n),e.Tools.Error("Error: "+this._compilationError),this._dumpShadersName(),o&&o.isMoreFallbacks?(e.Tools.Error("Trying next fallback."),n=o.reduce(n),this._prepareEffect(t,i,r,n,o)):this.onError&&this.onError(this,this._compilationError)}},Object.defineProperty(t.prototype,"isSupported",{get:function(){return""===this._compilationError},enumerable:!0,configurable:!0}),t.prototype._bindTexture=function(e,t){this._engine._bindTexture(this._samplers.indexOf(e),t)},t.prototype.setTexture=function(e,t){this._engine.setTexture(this._samplers.indexOf(e),this.getUniform(e),t)},t.prototype.setTextureArray=function(e,t){if(this._samplers.indexOf(e+"Ex")===-1)for(var i=this._samplers.indexOf(e),r=1;r<t.length;r++)this._samplers.splice(i+r,0,e+"Ex");this._engine.setTextureArray(this._samplers.indexOf(e),this.getUniform(e),t)},t.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers.indexOf(e),t)},t.prototype._cacheMatrix=function(t,i){var r=!1,n=this._valueCache[t];n&&n instanceof e.Matrix||(r=!0,n=new e.Matrix);for(var o=n.m,s=i.m,a=0;a<16;a++)o[a]!==s[a]&&(o[a]=s[a],r=!0);return this._valueCache[t]=n,r},t.prototype._cacheFloat2=function(e,t,i){var r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;var n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n},t.prototype._cacheFloat3=function(e,t,i,r){var n=this._valueCache[e];if(!n)return n=[t,i,r],this._valueCache[e]=n,!0;var o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==r&&(n[2]=r,o=!0),o},t.prototype._cacheFloat4=function(e,t,i,r,n){var o=this._valueCache[e];if(!o)return o=[t,i,r,n],this._valueCache[e]=o,!0;var s=!1;return o[0]!==t&&(o[0]=t,s=!0),o[1]!==i&&(o[1]=i,s=!0),o[2]!==r&&(o[2]=r,s=!0),o[3]!==n&&(o[3]=n,s=!0),s},t.prototype.setIntArray=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray(this.getUniform(e),t),this},t.prototype.setIntArray2=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray2(this.getUniform(e),t),this},t.prototype.setIntArray3=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray3(this.getUniform(e),t),this},t.prototype.setIntArray4=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray4(this.getUniform(e),t),this},t.prototype.setFloatArray=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray(this.getUniform(e),t),this},t.prototype.setFloatArray2=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray2(this.getUniform(e),t),this},t.prototype.setFloatArray3=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray3(this.getUniform(e),t),this},t.prototype.setFloatArray4=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray4(this.getUniform(e),t),this},t.prototype.setArray=function(e,t){return this._valueCache[e]=null,this._engine.setArray(this.getUniform(e),t),this},t.prototype.setArray2=function(e,t){return this._valueCache[e]=null,this._engine.setArray2(this.getUniform(e),t),this},t.prototype.setArray3=function(e,t){return this._valueCache[e]=null,this._engine.setArray3(this.getUniform(e),t),this},t.prototype.setArray4=function(e,t){return this._valueCache[e]=null,this._engine.setArray4(this.getUniform(e),t),this},t.prototype.setMatrices=function(e,t){return this._valueCache[e]=null,this._engine.setMatrices(this.getUniform(e),t),this},t.prototype.setMatrix=function(e,t){return this._cacheMatrix(e,t)&&this._engine.setMatrix(this.getUniform(e),t),this},t.prototype.setMatrix3x3=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix3x3(this.getUniform(e),t),this},t.prototype.setMatrix2x2=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix2x2(this.getUniform(e),t),this},t.prototype.setFloat=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setFloat(this.getUniform(e),t),this)},t.prototype.setBool=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setBool(this.getUniform(e),t?1:0),
this)},t.prototype.setVector2=function(e,t){return this._cacheFloat2(e,t.x,t.y)&&this._engine.setFloat2(this.getUniform(e),t.x,t.y),this},t.prototype.setFloat2=function(e,t,i){return this._cacheFloat2(e,t,i)&&this._engine.setFloat2(this.getUniform(e),t,i),this},t.prototype.setVector3=function(e,t){return this._cacheFloat3(e,t.x,t.y,t.z)&&this._engine.setFloat3(this.getUniform(e),t.x,t.y,t.z),this},t.prototype.setFloat3=function(e,t,i,r){return this._cacheFloat3(e,t,i,r)&&this._engine.setFloat3(this.getUniform(e),t,i,r),this},t.prototype.setVector4=function(e,t){return this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&this._engine.setFloat4(this.getUniform(e),t.x,t.y,t.z,t.w),this},t.prototype.setFloat4=function(e,t,i,r,n){return this._cacheFloat4(e,t,i,r,n)&&this._engine.setFloat4(this.getUniform(e),t,i,r,n),this},t.prototype.setColor3=function(e,t){return this._cacheFloat3(e,t.r,t.g,t.b)&&this._engine.setColor3(this.getUniform(e),t),this},t.prototype.setColor4=function(e,t,i){return this._cacheFloat4(e,t.r,t.g,t.b,i)&&this._engine.setColor4(this.getUniform(e),t,i),this},t.ShadersStore={},t.IncludesShadersStore={},t})();e.Effect=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.PrepareDefinesForLights=function(t,i,r,n){void 0===n&&(n=4);for(var o=0,s=!1,a=!1,h=!1,c=!1,l=0;l<t.lights.length;l++){var u=t.lights[l];if(u.isEnabled()){if(u._excludedMeshesIds.length>0){for(var d=0;d<u._excludedMeshesIds.length;d++){var f=t.getMeshByID(u._excludedMeshesIds[d]);f&&u.excludedMeshes.push(f)}u._excludedMeshesIds=[]}if(u._includedOnlyMeshesIds.length>0){for(var p=0;p<u._includedOnlyMeshesIds.length;p++){var m=t.getMeshByID(u._includedOnlyMeshesIds[p]);m&&u.includedOnlyMeshes.push(m)}u._includedOnlyMeshesIds=[]}if(u.canAffectMesh(i)){s=!0,void 0===r["LIGHT"+o]&&(a=!0),r["LIGHT"+o]=!0;var _;if(_=u instanceof e.SpotLight?"SPOTLIGHT"+o:u instanceof e.HemisphericLight?"HEMILIGHT"+o:u instanceof e.PointLight?"POINTLIGHT"+o:"DIRLIGHT"+o,void 0===r[_]&&(a=!0),r[_]=!0,u.specular.equalsFloats(0,0,0)||void 0===r.SPECULARTERM||(r.SPECULARTERM=!0),t.shadowsEnabled){var g=u.getShadowGenerator();i&&i.receiveShadows&&g&&(void 0===r["SHADOW"+o]&&(a=!0),r["SHADOW"+o]=!0,r.SHADOWS=!0,(g.useVarianceShadowMap||g.useBlurVarianceShadowMap)&&(void 0===r["SHADOWVSM"+o]&&(a=!0),r["SHADOWVSM"+o]=!0),g.usePoissonSampling&&(void 0===r["SHADOWPCF"+o]&&(a=!0),r["SHADOWPCF"+o]=!0),h=!0)}if(u.lightmapMode!=e.Light.LIGHTMAP_DEFAULT&&(c=!0,void 0===r["LIGHTMAPEXCLUDED"+o]&&(a=!0),void 0===r["LIGHTMAPNOSPECULAR"+o]&&(a=!0),r["LIGHTMAPEXCLUDED"+o]=!0,u.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY&&(r["LIGHTMAPNOSPECULAR"+o]=!0)),o++,o===n)break}}}var v=t.getEngine().getCaps();return h&&v.textureFloat&&v.textureFloatLinearFiltering&&v.textureFloatRender&&(void 0===r.SHADOWFULLFLOAT&&(a=!0),r.SHADOWFULLFLOAT=!0),void 0===r.LIGHTMAPEXCLUDED&&(a=!0),c&&(r.LIGHTMAPEXCLUDED=!0),a&&r.rebuild(),s},t.PrepareUniformsAndSamplersList=function(e,t,i,r){void 0===r&&(r=4);for(var n=0;n<r&&i["LIGHT"+n];n++)e.push("vLightData"+n,"vLightDiffuse"+n,"vLightSpecular"+n,"vLightDirection"+n,"vLightGround"+n,"lightMatrix"+n,"shadowsInfo"+n),t.push("shadowSampler"+n)},t.HandleFallbacksForShadows=function(e,t,i){void 0===i&&(i=4);for(var r=0;r<i&&e["LIGHT"+r];r++)r>0&&t.addFallback(r,"LIGHT"+r),e["SHADOW"+r]&&t.addFallback(0,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(0,"SHADOWPCF"+r),e["SHADOWVSM"+r]&&t.addFallback(0,"SHADOWVSM"+r)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n,o){var s=e.getShadowGenerator();return i.receiveShadows&&s&&(e.needCube()?o||(o=!0,n.setFloat2("depthValues",t.activeCamera.minZ,t.activeCamera.maxZ)):n.setMatrix("lightMatrix"+r,s.getTransformMatrix()),n.setTexture("shadowSampler"+r,s.getShadowMapForRendering()),n.setFloat3("shadowsInfo"+r,s.getDarkness(),s.blurScale/s.getShadowMap().getSize().width,s.bias)),o},t.BindLightProperties=function(t,i,r){t instanceof e.PointLight?t.transferToEffect(i,"vLightData"+r):t instanceof e.DirectionalLight?t.transferToEffect(i,"vLightData"+r):t instanceof e.SpotLight?t.transferToEffect(i,"vLightData"+r,"vLightDirection"+r):t instanceof e.HemisphericLight&&t.transferToEffect(i,"vLightData"+r,"vLightGround"+r)},t.BindLights=function(i,r,n,o,s){void 0===s&&(s=4);for(var a=0,h=!1,c=0;c<i.lights.length;c++){var l=i.lights[c];if(l.isEnabled()&&l.canAffectMesh(r)&&(t.BindLightProperties(l,n,a),l.diffuse.scaleToRef(l.intensity,e.Tmp.Color3[0]),n.setColor4("vLightDiffuse"+a,e.Tmp.Color3[0],l.range),o.SPECULARTERM&&(l.specular.scaleToRef(l.intensity,e.Tmp.Color3[1]),n.setColor3("vLightSpecular"+a,e.Tmp.Color3[1])),i.shadowsEnabled&&(h=this.BindLightShadow(l,i,r,a,n,h)),a++,a===s))break}},t.BindFogParameters=function(t,i,r){t.fogEnabled&&i.applyFog&&t.fogMode!==e.Scene.FOGMODE_NONE&&(r.setFloat4("vFogInfos",t.fogMode,t.fogStart,t.fogEnd,t.fogDensity),r.setColor3("vFogColor",t.fogColor))},t.BindBonesParameters=function(e,t){if(e&&e.useBones&&e.computeBonesUsingShaders){var i=e.skeleton.getTransformMatrices(e);i&&t.setMatrices("mBones",i)}},t.BindLogDepth=function(e,t,i){e.LOGARITHMICDEPTH&&t.setFloat("logarithmicDepthConstant",2/(Math.log(i.activeCamera.maxZ+1)/Math.LN2))},t.BindClipPlane=function(e,t){if(t.clipPlane){var i=t.clipPlane;e.setFloat4("vClipPlane",i.normal.x,i.normal.y,i.normal.z,i.d)}},t})();e.MaterialHelper=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor,e.rightColor=this.rightColor,e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e.prototype.rebuild=function(){this._keys&&delete this._keys,this._keys=Object.keys(this)},e.prototype.isEqual=function(e){if(this._keys.length!==e._keys.length)return!1;for(var t=0;t<this._keys.length;t++){var i=this._keys[t];if(this[i]!==e[i])return!1}return!0},e.prototype.cloneTo=function(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(var t=0;t<this._keys.length;t++){var i=this._keys[t];e[i]=this[i]}},e.prototype.reset=function(){for(var e=0;e<this._keys.length;e++){var t=this._keys[e];"number"==typeof this[t]?this[t]=0:this[t]=!1}},e.prototype.toString=function(){for(var e="",t=0;t<this._keys.length;t++){var i=this._keys[t];"number"==typeof this[i]?e+="#define "+i+" "+this[i]+"\n":this[i]&&(e+="#define "+i+"\n")}return e},e})();e.MaterialDefines=t;var i=(function(){function t(i,r,n){this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this.alpha=1,this.backFaceCulling=!0,this.doNotSerialize=!1,this.onDisposeObservable=new e.Observable,this.onBindObservable=new e.Observable,this.onUnBindObservable=new e.Observable,this.alphaMode=e.Engine.ALPHA_COMBINE,this.disableDepthWrite=!1,this.fogEnabled=!0,this.pointSize=1,this.zOffset=0,this._wasPreviouslyReady=!1,this._fillMode=t.TriangleFillMode,this.name=i,this.id=i,this._scene=r,r.useRightHandedSystem?this.sideOrientation=t.ClockWiseSideOrientation:this.sideOrientation=t.CounterClockWiseSideOrientation,n||r.materials.push(this)}return Object.defineProperty(t,"TriangleFillMode",{get:function(){return t._TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WireFrameFillMode",{get:function(){return t._WireFrameFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PointFillMode",{get:function(){return t._PointFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ClockWiseSideOrientation",{get:function(){return t._ClockWiseSideOrientation},enumerable:!0,configurable:!0}),Object.defineProperty(t,"CounterClockWiseSideOrientation",{get:function(){return t._CounterClockWiseSideOrientation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBind",{set:function(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wireframe",{get:function(){return this._fillMode===t.WireFrameFillMode},set:function(e){this._fillMode=e?t.WireFrameFillMode:t.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pointsCloud",{get:function(){return this._fillMode===t.PointFillMode},set:function(e){this._fillMode=e?t.PointFillMode:t.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fillMode",{get:function(){return this._fillMode},set:function(e){this._fillMode=e},enumerable:!0,configurable:!0}),t.prototype.toString=function(e){var t="Name: "+this.name;return t},Object.defineProperty(t.prototype,"isFrozen",{get:function(){return this.checkReadyOnlyOnce},enumerable:!0,configurable:!0}),t.prototype.freeze=function(){this.checkReadyOnlyOnce=!0},t.prototype.unfreeze=function(){this.checkReadyOnlyOnce=!1},t.prototype.isReady=function(e,t){return!0},t.prototype.getEffect=function(){return this._effect},t.prototype.getScene=function(){return this._scene},t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.markDirty=function(){this._wasPreviouslyReady=!1},t.prototype._preBind=function(){var e=this._scene.getEngine(),i=this.sideOrientation===t.ClockWiseSideOrientation;e.enableEffect(this._effect),e.setState(this.backFaceCulling,this.zOffset,!1,i)},t.prototype.bind=function(e,t){if(this._scene._cachedMaterial=this,this.onBindObservable.notifyObservers(t),this.disableDepthWrite){var i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}},t.prototype.bindOnlyWorldMatrix=function(e){},t.prototype.unbind=function(){if(this.onUnBindObservable.notifyObservers(this),this.disableDepthWrite){var e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}},t.prototype.clone=function(e){return null},t.prototype.getBindedMeshes=function(){for(var e=new Array,t=0;t<this._scene.meshes.length;t++){var i=this._scene.meshes[t];i.material===this&&e.push(i)}return e},t.prototype.dispose=function(e,t){this.getScene().stopAnimation(this);var i=this._scene.materials.indexOf(this);for(i>=0&&this._scene.materials.splice(i,1),e&&this._effect&&(this._scene.getEngine()._releaseEffect(this._effect),this._effect=null),i=0;i<this._scene.meshes.length;i++){var r=this._scene.meshes[i];r.material===this&&(r.material=null)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBindObservable.clear(),this.onUnBindObservable.clear()},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.ParseMultiMaterial=function(t,i){var r=new e.MultiMaterial(t.name,i);r.id=t.id,e.Tags.AddTagsTo(r,t.tags);for(var n=0;n<t.materials.length;n++){var o=t.materials[n];o?r.subMaterials.push(i.getMaterialByID(o)):r.subMaterials.push(null)}return r},t.Parse=function(t,i,r){if(!t.customType)return e.StandardMaterial.Parse(t,i,r);var n=e.Tools.Instantiate(t.customType);return n.Parse(t,i,r)},t._TriangleFillMode=0,t._WireFrameFillMode=1,t._PointFillMode=2,t._ClockWiseSideOrientation=0,t._CounterClockWiseSideOrientation=1,__decorate([e.serialize()],t.prototype,"id",void 0),__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"checkReadyOnEveryCall",void 0),__decorate([e.serialize()],t.prototype,"checkReadyOnlyOnce",void 0),__decorate([e.serialize()],t.prototype,"state",void 0),__decorate([e.serialize()],t.prototype,"alpha",void 0),__decorate([e.serialize()],t.prototype,"backFaceCulling",void 0),__decorate([e.serialize()],t.prototype,"sideOrientation",void 0),__decorate([e.serialize()],t.prototype,"alphaMode",void 0),__decorate([e.serialize()],t.prototype,"disableDepthWrite",void 0),__decorate([e.serialize()],t.prototype,"fogEnabled",void 0),__decorate([e.serialize()],t.prototype,"pointSize",void 0),__decorate([e.serialize()],t.prototype,"zOffset",void 0),__decorate([e.serialize()],t.prototype,"wireframe",null),__decorate([e.serialize()],t.prototype,"pointsCloud",null),__decorate([e.serialize()],t.prototype,"fillMode",null),t})();e.Material=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(){e.call(this),this.DIFFUSE=!1,this.AMBIENT=!1,this.OPACITY=!1,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.SPECULAR=!1,this.BUMP=!1,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.ALPHATEST=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.INVERTNORMALMAPX=!1,this.INVERTNORMALMAPY=!1,this.SHADOWFULLFLOAT=!1,this.CAMERACOLORGRADING=!1,this.CAMERACOLORCURVES=!1,this.rebuild()}return __extends(t,e),t})(e.MaterialDefines),i=(function(i){function r(r,n){var o=this;i.call(this,r,n),this.ambientColor=new e.Color3(0,0,0),this.diffuseColor=new e.Color3(1,1,1),this.specularColor=new e.Color3(1,1,1),this.emissiveColor=new e.Color3(0,0,0),this.specularPower=64,this.useAlphaFromDiffuseTexture=!1,this.useEmissiveAsIllumination=!1,this.linkEmissiveWithDiffuse=!1,this.useReflectionFresnelFromSpecular=!1,this.useSpecularOverAlpha=!1,this.useReflectionOverAlpha=!1,this.disableLighting=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.useLightmapAsShadowmap=!1,this.useGlossinessFromSpecularMapAlpha=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.cameraColorGradingTexture=null,this.cameraColorCurves=null,this._renderTargets=new e.SmartArray(16),this._worldViewProjectionMatrix=e.Matrix.Zero(),this._globalAmbientColor=new e.Color3(0,0,0),this._defines=new t,this._cachedDefines=new t,this._cachedDefines.BonesPerMesh=-1,this.getRenderTargetTextures=function(){return o._renderTargets.reset(),o.reflectionTexture&&o.reflectionTexture.isRenderTarget&&o._renderTargets.push(o.reflectionTexture),o.refractionTexture&&o.refractionTexture.isRenderTarget&&o._renderTargets.push(o.refractionTexture),o._renderTargets}}return __extends(r,i),Object.defineProperty(r.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),r.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this.opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled},r.prototype.needAlphaTesting=function(){return null!=this.diffuseTexture&&this.diffuseTexture.hasAlpha},r.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this.diffuseTexture&&this.diffuseTexture.hasAlpha&&this.useAlphaFromDiffuseTexture},r.prototype.getAlphaTestTexture=function(){return this.diffuseTexture},r.prototype._checkCache=function(e,t,i){return!t||this._defines.INSTANCES===i&&!(!t._materialDefines||!t._materialDefines.isEqual(this._defines))},r.prototype.isReady=function(i,n){if(this.isFrozen&&this._wasPreviouslyReady)return!0;var o=this.getScene(),s=o.getEngine(),a=!1,h=!1;if(this._defines.reset(),o.lightsEnabled&&!this.disableLighting&&(h=e.MaterialHelper.PrepareDefinesForLights(o,i,this._defines,this.maxSimultaneousLights)),!this.checkReadyOnEveryCall&&this._renderId===o.getRenderId()&&this._checkCache(o,i,n))return!0;if(o.texturesEnabled){if(this.diffuseTexture&&r.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;a=!0,this._defines.DIFFUSE=!0}if(this.ambientTexture&&r.AmbientTextureEnabled){if(!this.ambientTexture.isReady())return!1;a=!0,this._defines.AMBIENT=!0}if(this.opacityTexture&&r.OpacityTextureEnabled){if(!this.opacityTexture.isReady())return!1;a=!0,this._defines.OPACITY=!0,this.opacityTexture.getAlphaFromRGB&&(this._defines.OPACITYRGB=!0)}if(this.reflectionTexture&&r.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady())return!1;switch(h=!0,this._defines.REFLECTION=!0,this.roughness>0&&(this._defines.ROUGHNESS=!0),this.useReflectionOverAlpha&&(this._defines.REFLECTIONOVERALPHA=!0),this.reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE&&(this._defines.INVERTCUBICMAP=!0),this._defines.REFLECTIONMAP_3D=this.reflectionTexture.isCube,this.reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:this._defines.REFLECTIONMAP_CUBIC=!0;break;case e.Texture.EXPLICIT_MODE:this._defines.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:this._defines.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:this._defines.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:this._defines.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:this._defines.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0}}if(this.emissiveTexture&&r.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady())return!1;a=!0,this._defines.EMISSIVE=!0}if(this.lightmapTexture&&r.LightmapTextureEnabled){if(!this.lightmapTexture.isReady())return!1;a=!0,this._defines.LIGHTMAP=!0,this._defines.USELIGHTMAPASSHADOWMAP=this.useLightmapAsShadowmap}if(this.specularTexture&&r.SpecularTextureEnabled){if(!this.specularTexture.isReady())return!1;a=!0,this._defines.SPECULAR=!0,this._defines.GLOSSINESS=this.useGlossinessFromSpecularMapAlpha}if(o.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&r.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;a=!0,this._defines.BUMP=!0,this.useParallax&&(this._defines.PARALLAX=!0,this.useParallaxOcclusion&&(this._defines.PARALLAXOCCLUSION=!0)),this.invertNormalMapX&&(this._defines.INVERTNORMALMAPX=!0),this.invertNormalMapY&&(this._defines.INVERTNORMALMAPY=!0)}if(this.refractionTexture&&r.RefractionTextureEnabled){if(!this.refractionTexture.isReady())return!1;a=!0,this._defines.REFRACTION=!0,this._defines.REFRACTIONMAP_3D=this.refractionTexture.isCube}if(this.cameraColorGradingTexture&&r.ColorGradingTextureEnabled){if(!this.cameraColorGradingTexture.isReady())return!1;this._defines.CAMERACOLORGRADING=!0}}if(o.clipPlane&&(this._defines.CLIPPLANE=!0),s.getAlphaTesting()&&(this._defines.ALPHATEST=!0),this._shouldUseAlphaFromDiffuseTexture()&&(this._defines.ALPHAFROMDIFFUSE=!0),this.useEmissiveAsIllumination&&(this._defines.EMISSIVEASILLUMINATION=!0),this.linkEmissiveWithDiffuse&&(this._defines.LINKEMISSIVEWITHDIFFUSE=!0),this.useLogarithmicDepth&&(this._defines.LOGARITHMICDEPTH=!0),this.cameraColorCurves&&(this._defines.CAMERACOLORCURVES=!0),(this.pointsCloud||o.forcePointsCloud)&&(this._defines.POINTSIZE=!0),o.fogEnabled&&i&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(this._defines.FOG=!0),r.FresnelEnabled&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled||this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled||this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled||this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled)&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._defines.DIFFUSEFRESNEL=!0),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&(this._defines.OPACITYFRESNEL=!0),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._defines.REFLECTIONFRESNEL=!0,this.useReflectionFresnelFromSpecular&&(this._defines.REFLECTIONFRESNELFROMSPECULAR=!0)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._defines.REFRACTIONFRESNEL=!0),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._defines.EMISSIVEFRESNEL=!0),h=!0,this._defines.FRESNEL=!0),this._defines.SPECULARTERM&&this.useSpecularOverAlpha&&(this._defines.SPECULAROVERALPHA=!0),i&&(h&&i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(this._defines.NORMAL=!0),a&&(i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(this._defines.UV1=!0),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(this._defines.UV2=!0)),i.useVertexColors&&i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(this._defines.VERTEXCOLOR=!0,i.hasVertexAlpha&&(this._defines.VERTEXALPHA=!0)),i.useBones&&i.computeBonesUsingShaders&&(this._defines.NUM_BONE_INFLUENCERS=i.numBoneInfluencers,this._defines.BonesPerMesh=i.skeleton.bones.length+1),n&&(this._defines.INSTANCES=!0)),!this._defines.isEqual(this._cachedDefines)){this._defines.cloneTo(this._cachedDefines),o.resetCachedMaterial();var c=new e.EffectFallbacks;this._defines.REFLECTION&&c.addFallback(0,"REFLECTION"),this._defines.SPECULAR&&c.addFallback(0,"SPECULAR"),this._defines.BUMP&&c.addFallback(0,"BUMP"),this._defines.PARALLAX&&c.addFallback(1,"PARALLAX"),this._defines.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),this._defines.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),this._defines.FOG&&c.addFallback(1,"FOG"),this._defines.POINTSIZE&&c.addFallback(0,"POINTSIZE"),this._defines.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(this._defines,c,this.maxSimultaneousLights),this._defines.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),this._defines.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),this._defines.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),this._defines.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),this._defines.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),this._defines.FRESNEL&&c.addFallback(4,"FRESNEL");var l=[e.VertexBuffer.PositionKind];this._defines.NORMAL&&l.push(e.VertexBuffer.NormalKind),this._defines.UV1&&l.push(e.VertexBuffer.UVKind),this._defines.UV2&&l.push(e.VertexBuffer.UV2Kind),this._defines.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,i,this._defines,c),e.MaterialHelper.PrepareAttributesForInstances(l,this._defines);var u="default",d=this._defines.toString(),f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","depthValues","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","logarithmicDepthConstant"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"];this._defines.CAMERACOLORCURVES&&e.ColorCurves.PrepareUniforms(f),this._defines.CAMERACOLORGRADING&&e.ColorGradingTexture.PrepareUniformsAndSamplers(f,p),e.MaterialHelper.PrepareUniformsAndSamplersList(f,p,this._defines,this.maxSimultaneousLights),this._effect=o.getEngine().createEffect(u,l,f,p,d,c,this.onCompiled,this.onError,{maxSimultaneousLights:this.maxSimultaneousLights-1})}return!!this._effect.isReady()&&(this._renderId=o.getRenderId(),this._wasPreviouslyReady=!0,i&&(i._materialDefines||(i._materialDefines=new t),this._defines.cloneTo(i._materialDefines)),!0)},r.prototype.unbind=function(){this.reflectionTexture&&this.reflectionTexture.isRenderTarget&&this._effect.setTexture("reflection2DSampler",null),this.refractionTexture&&this.refractionTexture.isRenderTarget&&this._effect.setTexture("refraction2DSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._effect.setMatrix("world",e)},r.prototype.bind=function(t,n){var o=this.getScene();if(this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(n,this._effect),o.getCachedMaterial()!==this){if(this._effect.setMatrix("viewProjection",o.getTransformMatrix()),r.FresnelEnabled&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._effect.setColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._effect.setColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._effect.setColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._effect.setColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._effect.setColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._effect.setColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._effect.setColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._effect.setColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._effect.setColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this.diffuseTexture&&r.DiffuseTextureEnabled&&(this._effect.setTexture("diffuseSampler",this.diffuseTexture),this._effect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._effect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.ambientTexture&&r.AmbientTextureEnabled&&(this._effect.setTexture("ambientSampler",this.ambientTexture),this._effect.setFloat2("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level),this._effect.setMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix())),this.opacityTexture&&r.OpacityTextureEnabled&&(this._effect.setTexture("opacitySampler",this.opacityTexture),this._effect.setFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level),this._effect.setMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix())),this.reflectionTexture&&r.ReflectionTextureEnabled&&(this.reflectionTexture.isCube?this._effect.setTexture("reflectionCubeSampler",this.reflectionTexture):this._effect.setTexture("reflection2DSampler",this.reflectionTexture),this._effect.setMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix()),this._effect.setFloat2("vReflectionInfos",this.reflectionTexture.level,this.roughness)),this.emissiveTexture&&r.EmissiveTextureEnabled&&(this._effect.setTexture("emissiveSampler",this.emissiveTexture),this._effect.setFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level),this._effect.setMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix())),this.lightmapTexture&&r.LightmapTextureEnabled&&(this._effect.setTexture("lightmapSampler",this.lightmapTexture),this._effect.setFloat2("vLightmapInfos",this.lightmapTexture.coordinatesIndex,this.lightmapTexture.level),this._effect.setMatrix("lightmapMatrix",this.lightmapTexture.getTextureMatrix())),this.specularTexture&&r.SpecularTextureEnabled&&(this._effect.setTexture("specularSampler",this.specularTexture),this._effect.setFloat2("vSpecularInfos",this.specularTexture.coordinatesIndex,this.specularTexture.level),this._effect.setMatrix("specularMatrix",this.specularTexture.getTextureMatrix())),this.bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._effect.setTexture("bumpSampler",this.bumpTexture),this._effect.setFloat3("vBumpInfos",this.bumpTexture.coordinatesIndex,1/this.bumpTexture.level,this.parallaxScaleBias),this._effect.setMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix())),this.refractionTexture&&r.RefractionTextureEnabled){var s=1;this.refractionTexture.isCube?this._effect.setTexture("refractionCubeSampler",this.refractionTexture):(this._effect.setTexture("refraction2DSampler",this.refractionTexture),this._effect.setMatrix("refractionMatrix",this.refractionTexture.getReflectionTextureMatrix()),this.refractionTexture.depth&&(s=this.refractionTexture.depth)),this._effect.setFloat4("vRefractionInfos",this.refractionTexture.level,this.indexOfRefraction,s,this.invertRefractionY?-1:1)}this.cameraColorGradingTexture&&r.ColorGradingTextureEnabled&&e.ColorGradingTexture.Bind(this.cameraColorGradingTexture,this._effect)}e.MaterialHelper.BindClipPlane(this._effect,o),this.pointsCloud&&this._effect.setFloat("pointSize",this.pointSize),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),this._effect.setVector3("vEyePosition",o._mirroredCameraPosition?o._mirroredCameraPosition:o.activeCamera.position),this._effect.setColor3("vAmbientColor",this._globalAmbientColor),this._defines.SPECULARTERM&&this._effect.setColor4("vSpecularColor",this.specularColor,this.specularPower),this._effect.setColor3("vEmissiveColor",this.emissiveColor)}o.getCachedMaterial()===this&&this.isFrozen||(this._effect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*n.visibility),o.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(o,n,this._effect,this._defines,this.maxSimultaneousLights),(o.fogEnabled&&n.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this.reflectionTexture||this.refractionTexture)&&this._effect.setMatrix("view",o.getViewMatrix()),e.MaterialHelper.BindFogParameters(o,n,this._effect),e.MaterialHelper.BindLogDepth(this._defines,this._effect,o),
this.cameraColorCurves&&e.ColorCurves.Bind(this.cameraColorCurves,this._effect)),i.prototype.bind.call(this,t,n)},r.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0&&e.push(this.ambientTexture),this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0&&e.push(this.opacityTexture),this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0&&e.push(this.reflectionTexture),this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0&&e.push(this.emissiveTexture),this.specularTexture&&this.specularTexture.animations&&this.specularTexture.animations.length>0&&e.push(this.specularTexture),this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this.lightmapTexture&&this.lightmapTexture.animations&&this.lightmapTexture.animations.length>0&&e.push(this.lightmapTexture),this.refractionTexture&&this.refractionTexture.animations&&this.refractionTexture.animations.length>0&&e.push(this.refractionTexture),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.animations&&this.cameraColorGradingTexture.animations.length>0&&e.push(this.cameraColorGradingTexture),e},r.prototype.dispose=function(e,t){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.ambientTexture&&this.ambientTexture.dispose(),this.opacityTexture&&this.opacityTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose(),this.emissiveTexture&&this.emissiveTexture.dispose(),this.specularTexture&&this.specularTexture.dispose(),this.bumpTexture&&this.bumpTexture.dispose(),this.lightmapTexture&&this.lightmapTexture.dispose(),this.refractionTexture&&this.refractionTexture.dispose(),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.dispose()),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.DiffuseTextureEnabled=!0,r.AmbientTextureEnabled=!0,r.OpacityTextureEnabled=!0,r.ReflectionTextureEnabled=!0,r.EmissiveTextureEnabled=!0,r.SpecularTextureEnabled=!0,r.BumpTextureEnabled=!0,r.FresnelEnabled=!0,r.LightmapTextureEnabled=!0,r.RefractionTextureEnabled=!0,r.ColorGradingTextureEnabled=!0,__decorate([e.serializeAsTexture()],r.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"ambientTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"specularTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),__decorate([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),__decorate([e.serialize()],r.prototype,"specularPower",void 0),__decorate([e.serialize()],r.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([e.serialize()],r.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize()],r.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([e.serialize()],r.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([e.serialize()],r.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useReflectionOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"disableLighting",void 0),__decorate([e.serialize()],r.prototype,"useParallax",void 0),__decorate([e.serialize()],r.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],r.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize()],r.prototype,"roughness",void 0),__decorate([e.serialize()],r.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],r.prototype,"invertRefractionY",void 0),__decorate([e.serialize()],r.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"diffuseFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"reflectionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"refractionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize()],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.serialize()],r.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapX",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapY",void 0),__decorate([e.serializeAsTexture()],r.prototype,"cameraColorGradingTexture",void 0),__decorate([e.serializeAsColorCurves()],r.prototype,"cameraColorCurves",void 0),__decorate([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.Material);e.StandardMaterial=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i){t.call(this,e,i,!0),this.subMaterials=new Array,i.multiMaterials.push(this)}return __extends(i,t),i.prototype.getSubMaterial=function(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.isReady=function(e){for(var t=0;t<this.subMaterials.length;t++){var i=this.subMaterials[t];if(i&&!this.subMaterials[t].isReady(e))return!1}return!0},i.prototype.clone=function(e,t){for(var r=new i(e,this.getScene()),n=0;n<this.subMaterials.length;n++){var o=null;o=t?this.subMaterials[n].clone(e+"-"+this.subMaterials[n].name):this.subMaterials[n],r.subMaterials.push(o)}return r},i.prototype.serialize=function(){var t={};t.name=this.name,t.id=this.id,t.tags=e.Tags.GetTags(this),t.materials=[];for(var i=0;i<this.subMaterials.length;i++){var r=this.subMaterials[i];r?t.materials.push(r.id):t.materials.push(null)}return t},i})(e.Material);e.MultiMaterial=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"NO_LOGGING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MINIMAL_LOGGING",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"SUMMARY_LOGGING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DETAILED_LOGGING",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ForceFullSceneLoadingForIncremental",{get:function(){return t._ForceFullSceneLoadingForIncremental},set:function(e){t._ForceFullSceneLoadingForIncremental=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ShowLoadingScreen",{get:function(){return t._ShowLoadingScreen},set:function(e){t._ShowLoadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"loggingLevel",{get:function(){return t._loggingLevel},set:function(e){t._loggingLevel=e},enumerable:!0,configurable:!0}),t._getDefaultPlugin=function(){return t._registeredPlugins[".babylon"]},t._getPluginForExtension=function(e){var i=t._registeredPlugins[e];return i?i:t._getDefaultPlugin()},t._getPluginForFilename=function(e){e.name&&(e=e.name);var i=e.lastIndexOf("."),r=e.indexOf("?");r===-1&&(r=e.length);var n=e.substring(i,r).toLowerCase();return t._getPluginForExtension(n)},t._getDirectLoad=function(e){return e.substr&&"data:"===e.substr(0,5)?e.substr(5):null},t.GetPluginForExtension=function(e){return t._getPluginForExtension(e).plugin},t.RegisterPlugin=function(e){if("string"==typeof e.extensions){var i=e.extensions;t._registeredPlugins[i.toLowerCase()]={plugin:e,isBinary:!1}}else{var r=e.extensions;Object.keys(r).forEach((function(i){t._registeredPlugins[i.toLowerCase()]={plugin:e,isBinary:r[i].isBinary}}))}},t.ImportMesh=function(i,r,n,o,s,a,h){if(n.substr&&"/"===n.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");if(n.substr&&"/"===n.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");var c=t._getDirectLoad(n),l={};o._addPendingData(l);var u=function(u){o.database=d;var f=c?t._getDefaultPlugin():t._getPluginForFilename(n),p=f.plugin,m=f.isBinary,_=function(e){var t=[],a=[],c=[];try{if(p.importMesh){var u=p;if(!u.importMesh(i,o,e,r,t,a,c))return h&&h(o,"Unable to import meshes from "+r+n),void o._removePendingData(l);s&&(o.importedMeshesFiles.push(r+n),s(t,a,c),o._removePendingData(l))}else{var d=p;d.importMeshAsync(i,o,e,r,(function(e,t,i){s&&(o.importedMeshesFiles.push(r+n),s(e,t,i),o._removePendingData(l))}),(function(){h&&h(o,"Unable to import meshes from "+r+n),o._removePendingData(l)}))}}catch(f){h&&h(o,"Unable to import meshes from "+r+n,f),o._removePendingData(l)}};return c?void _(c):void e.Tools.LoadFile(r+n,(function(e){_(e)}),a,d,m)};if(o.getEngine().enableOfflineSupport&&!c)var d=new e.Database(r+n,u);else u(!0)},t.Load=function(i,r,n,o,s,a){t.Append(i,r,new e.Scene(n),o,s,a)},t.Append=function(i,r,n,o,s,a){if(r.substr&&"/"===r.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");var h,c=t._getDirectLoad(r),l=c?t._getDefaultPlugin():t._getPluginForFilename(r),u=l.plugin,d=l.isBinary,f={};n._addPendingData(f),t.ShowLoadingScreen&&n.getEngine().displayLoadingUI();var p=function(e){if(n.database=h,u.load){var r=u;if(!r.load(n,e,i))return a&&a(n),n._removePendingData(f),void n.getEngine().hideLoadingUI();o&&o(n),n._removePendingData(f)}else{var s=u;s.loadAsync(n,e,i,(function(){o&&o(n),n._removePendingData(f)}),(function(){a&&a(n),n._removePendingData(f),n.getEngine().hideLoadingUI()}))}t.ShowLoadingScreen&&n.executeWhenReady((function(){n.getEngine().hideLoadingUI()}))},m=function(t){e.Tools.LoadFile(i+r,p,s,h,d)};return c?void p(c):void(i.indexOf("file:")===-1?n.getEngine().enableOfflineSupport?h=new e.Database(i+r,m):m(!0):e.Tools.ReadFile(r,p,s,d))},t._ForceFullSceneLoadingForIncremental=!1,t._ShowLoadingScreen=!0,t._loggingLevel=t.NO_LOGGING,t._registeredPlugins={},t})();e.SceneLoader=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=function(t,i,r,n){for(var o=0,s=i.materials.length;o<s;o++){var a=i.materials[o];if(a.id===t)return e.Material.Parse(a,r,n)}return null},r=function(e,t,i){t=t instanceof Array?t:[t];for(var r in t)if(e.name===t[r])return i.push(e.id),!0;return!(!e.parentId||i.indexOf(e.parentId)===-1)&&(i.push(e.id),!0)},n=function(e,t){return e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown")};e.SceneLoader.RegisterPlugin({extensions:".babylon",importMesh:function(t,o,s,a,h,c,l){var u="importMesh has failed JSON parse";try{var d=JSON.parse(s);u="";var f,p,m=e.SceneLoader.loggingLevel===e.SceneLoader.DETAILED_LOGGING,_=[],g=[],v=[];for(f=0,p=d.meshes.length;f<p;f++){var y=d.meshes[f];if(!t||r(y,t,v)){if(t instanceof Array&&delete t[t.indexOf(y.name)],y.geometryId&&d.geometries){var x=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach((function(t){!x&&d.geometries[t]&&d.geometries[t]instanceof Array&&d.geometries[t].forEach((function(i){if(i.id===y.geometryId){switch(t){case"boxes":e.Geometry.Primitives.Box.Parse(i,o);break;case"spheres":e.Geometry.Primitives.Sphere.Parse(i,o);break;case"cylinders":e.Geometry.Primitives.Cylinder.Parse(i,o);break;case"toruses":e.Geometry.Primitives.Torus.Parse(i,o);break;case"grounds":e.Geometry.Primitives.Ground.Parse(i,o);break;case"planes":e.Geometry.Primitives.Plane.Parse(i,o);break;case"torusKnots":e.Geometry.Primitives.TorusKnot.Parse(i,o);break;case"vertexData":e.Geometry.Parse(i,o,a)}x=!0}}))})),x||e.Tools.Warn("Geometry not found for mesh "+y.id)}if(y.materialId){var b=g.indexOf(y.materialId)!==-1;if(!b&&d.multiMaterials)for(var T=0,A=d.multiMaterials.length;T<A;T++){var E=d.multiMaterials[T];if(E.id===y.materialId){for(var P=0,M=E.materials.length;P<M;P++){var S=E.materials[P];g.push(S);var C=i(S,d,o,a);u+="\n\tMaterial "+C.toString(m)}g.push(E.id);var R=e.Material.ParseMultiMaterial(E,o);b=!0,u+="\n\tMulti-Material "+R.toString(m);break}}if(!b){g.push(y.materialId);var C=i(y.materialId,d,o,a);C?u+="\n\tMaterial "+C.toString(m):e.Tools.Warn("Material not found for mesh "+y.id)}}if(y.skeletonId>-1&&o.skeletons){var O=_.indexOf(y.skeletonId)>-1;if(!O)for(var D=0,I=d.skeletons.length;D<I;D++){var w=d.skeletons[D];if(w.id===y.skeletonId){var L=e.Skeleton.Parse(w,o);l.push(L),_.push(w.id),u+="\n\tSkeleton "+L.toString(m)}}}var B=e.Mesh.Parse(y,o,a);h.push(B),u+="\n\tMesh "+B.toString(m)}}var F;for(f=0,p=o.meshes.length;f<p;f++)F=o.meshes[f],F._waitingParentId&&(F.parent=o.getLastEntryByID(F._waitingParentId),F._waitingParentId=void 0);for(f=0,p=o.meshes.length;f<p;f++)F=o.meshes[f],F._waitingFreezeWorldMatrix?(F.freezeWorldMatrix(),F._waitingFreezeWorldMatrix=void 0):F.computeWorldMatrix(!0);if(d.particleSystems)for(f=0,p=d.particleSystems.length;f<p;f++){var V=d.particleSystems[f];v.indexOf(V.emitterId)!==-1&&c.push(e.ParticleSystem.Parse(V,o,a))}return!0}catch(N){throw e.Tools.Log(n("importMesh",d?d.producer:"Unknown")+u),u=null,N}finally{null!==u&&e.SceneLoader.loggingLevel!==e.SceneLoader.NO_LOGGING&&e.Tools.Log(n("importMesh",d?d.producer:"Unknown")+(e.SceneLoader.loggingLevel!==e.SceneLoader.MINIMAL_LOGGING?u:""))}},load:function(t,i,r){var o="importScene has failed JSON parse";try{var s=JSON.parse(i);o="";var a=e.SceneLoader.loggingLevel===e.SceneLoader.DETAILED_LOGGING;if(t.useDelayedTextureLoading=s.useDelayedTextureLoading&&!e.SceneLoader.ForceFullSceneLoadingForIncremental,t.autoClear=s.autoClear,t.clearColor=e.Color4.FromArray(s.clearColor),t.ambientColor=e.Color3.FromArray(s.ambientColor),s.gravity&&(t.gravity=e.Vector3.FromArray(s.gravity)),s.fogMode&&0!==s.fogMode)switch(t.fogMode=s.fogMode,t.fogColor=e.Color3.FromArray(s.fogColor),t.fogStart=s.fogStart,t.fogEnd=s.fogEnd,t.fogDensity=s.fogDensity,o+="\tFog mode for scene:  ",t.fogMode){case 1:o+="exp\n";break;case 2:o+="exp2\n";break;case 3:o+="linear\n"}if(s.physicsEnabled){var h;"cannon"===s.physicsEngine?h=new e.CannonJSPlugin:"oimo"===s.physicsEngine&&(h=new e.OimoJSPlugin),o="\tPhysics engine "+(s.physicsEngine?s.physicsEngine:"oimo")+" enabled\n";var c=s.physicsGravity?e.Vector3.FromArray(s.physicsGravity):null;t.enablePhysics(c,h)}void 0!==s.metadata&&(t.metadata=s.metadata),void 0!=s.collisionsEnabled&&(t.collisionsEnabled=s.collisionsEnabled),t.workerCollisions=!!s.workerCollisions;var l,u;for(l=0,u=s.lights.length;l<u;l++){var d=s.lights[l],f=e.Light.Parse(d,t);o+=0===l?"\n\tLights:":"",o+="\n\t\t"+f.toString(a)}if(s.animations)for(l=0,u=s.animations.length;l<u;l++){var p=s.animations[l],m=e.Animation.Parse(p);t.animations.push(m),o+=0===l?"\n\tAnimations:":"",o+="\n\t\t"+m.toString(a)}if(s.autoAnimate&&t.beginAnimation(t,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1),s.materials)for(l=0,u=s.materials.length;l<u;l++){var _=s.materials[l],g=e.Material.Parse(_,t,r);o+=0===l?"\n\tMaterials:":"",o+="\n\t\t"+g.toString(a)}if(s.multiMaterials)for(l=0,u=s.multiMaterials.length;l<u;l++){var v=s.multiMaterials[l],y=e.Material.ParseMultiMaterial(v,t);o+=0===l?"\n\tMultiMaterials:":"",o+="\n\t\t"+y.toString(a)}if(s.skeletons)for(l=0,u=s.skeletons.length;l<u;l++){var x=s.skeletons[l],b=e.Skeleton.Parse(x,t);o+=0===l?"\n\tSkeletons:":"",o+="\n\t\t"+b.toString(a)}var T=s.geometries;if(T){var A=T.boxes;if(A)for(l=0,u=A.length;l<u;l++){var E=A[l];e.Geometry.Primitives.Box.Parse(E,t)}var P=T.spheres;if(P)for(l=0,u=P.length;l<u;l++){var M=P[l];e.Geometry.Primitives.Sphere.Parse(M,t)}var S=T.cylinders;if(S)for(l=0,u=S.length;l<u;l++){var C=S[l];e.Geometry.Primitives.Cylinder.Parse(C,t)}var R=T.toruses;if(R)for(l=0,u=R.length;l<u;l++){var O=R[l];e.Geometry.Primitives.Torus.Parse(O,t)}var D=T.grounds;if(D)for(l=0,u=D.length;l<u;l++){var I=D[l];e.Geometry.Primitives.Ground.Parse(I,t)}var w=T.planes;if(w)for(l=0,u=w.length;l<u;l++){var L=w[l];e.Geometry.Primitives.Plane.Parse(L,t)}var B=T.torusKnots;if(B)for(l=0,u=B.length;l<u;l++){var F=B[l];e.Geometry.Primitives.TorusKnot.Parse(F,t)}var V=T.vertexData;if(V)for(l=0,u=V.length;l<u;l++){var N=V[l];e.Geometry.Parse(N,t,r)}}for(l=0,u=s.meshes.length;l<u;l++){var z=s.meshes[l],U=e.Mesh.Parse(z,t,r);o+=0===l?"\n\tMeshes:":"",o+="\n\t\t"+U.toString(a)}for(l=0,u=s.cameras.length;l<u;l++){var k=s.cameras[l],G=e.Camera.Parse(k,t);o+=0===l?"\n\tCameras:":"",o+="\n\t\t"+G.toString(a)}for(s.activeCameraID&&t.setActiveCameraByID(s.activeCameraID),l=0,u=t.cameras.length;l<u;l++){var G=t.cameras[l];G._waitingParentId&&(G.parent=t.getLastEntryByID(G._waitingParentId),G._waitingParentId=void 0)}for(l=0,u=t.lights.length;l<u;l++){var f=t.lights[l];f._waitingParentId&&(f.parent=t.getLastEntryByID(f._waitingParentId),f._waitingParentId=void 0)}var W,Y=[];if(e.AudioEngine&&s.sounds)for(l=0,u=s.sounds.length;l<u;l++){var H=s.sounds[l];if(e.Engine.audioEngine.canUseWebAudio)H.url||(H.url=H.name),Y[H.url]?e.Sound.Parse(H,t,r,Y[H.url]):(W=e.Sound.Parse(H,t,r),Y[H.url]=W);else{new e.Sound(H.name,null,t)}}for(Y=[],l=0,u=t.meshes.length;l<u;l++){var U=t.meshes[l];U._waitingParentId&&(U.parent=t.getLastEntryByID(U._waitingParentId),U._waitingParentId=void 0),U._waitingActions&&(e.ActionManager.Parse(U._waitingActions,U,t),U._waitingActions=void 0)}for(l=0,u=t.meshes.length;l<u;l++){var j=t.meshes[l];j._waitingFreezeWorldMatrix?(j.freezeWorldMatrix(),j._waitingFreezeWorldMatrix=void 0):j.computeWorldMatrix(!0)}if(s.particleSystems)for(l=0,u=s.particleSystems.length;l<u;l++){var X=s.particleSystems[l];e.ParticleSystem.Parse(X,t,r)}if(s.lensFlareSystems)for(l=0,u=s.lensFlareSystems.length;l<u;l++){var K=s.lensFlareSystems[l];e.LensFlareSystem.Parse(K,t,r)}if(s.shadowGenerators)for(l=0,u=s.shadowGenerators.length;l<u;l++){var Z=s.shadowGenerators[l];e.ShadowGenerator.Parse(Z,t)}return s.actions&&e.ActionManager.Parse(s.actions,null,t),!0}catch(q){throw e.Tools.Log(n("importScene",s?s.producer:"Unknown")+o),o=null,q}finally{null!==o&&e.SceneLoader.loggingLevel!==e.SceneLoader.NO_LOGGING&&e.Tools.Log(n("importScene",s?s.producer:"Unknown")+(e.SceneLoader.loggingLevel!==e.SceneLoader.MINIMAL_LOGGING?o:""))}}})})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a){if(void 0===s&&(s=.01),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),this.name=t,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.fogEnabled=!0,this.isPickable=!1,this.onDisposeObservable=new e.Observable,this._vertexBuffers={},this._capacity=r,this._spriteTexture=new e.Texture(i,o,(!0),(!1),a),this._spriteTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._spriteTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return;this.cellWidth=n,this.cellHeight=n}this._epsilon=s,this._scene=o,this._scene.spriteManagers.push(this);for(var h=[],c=0,l=0;l<r;l++)h.push(c),h.push(c+1),h.push(c+2),h.push(c),h.push(c+2),h.push(c+3),c+=4;this._indexBuffer=o.getEngine().createIndexBuffer(h),this._vertexData=new Float32Array(16*r*4),this._buffer=new e.Buffer(o.getEngine(),this._vertexData,(!0),16);var u=this._buffer.createVertexBuffer(e.VertexBuffer.PositionKind,0,4),d=this._buffer.createVertexBuffer("options",4,4),f=this._buffer.createVertexBuffer("cellInfo",8,4),p=this._buffer.createVertexBuffer(e.VertexBuffer.ColorKind,12,4);this._vertexBuffers[e.VertexBuffer.PositionKind]=u,this._vertexBuffers.options=d,this._vertexBuffers.cellInfo=f,this._vertexBuffers[e.VertexBuffer.ColorKind]=p,this._effectBase=this._scene.getEngine().createEffect("sprites",[e.VertexBuffer.PositionKind,"options","cellInfo",e.VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],""),this._effectFog=this._scene.getEngine().createEffect("sprites",[e.VertexBuffer.PositionKind,"options","cellInfo",e.VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],"#define FOG")}return Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"texture",{get:function(){return this._spriteTexture},set:function(e){this._spriteTexture=e},enumerable:!0,configurable:!0}),t.prototype._appendSpriteVertex=function(e,t,i,r,n){var o=16*e;0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._vertexData[o+6]=i,this._vertexData[o+7]=r,this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0;var s=t.cellIndex/n>>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o,s=Math.min(this._capacity,this.sprites.length),a=e.Vector3.Zero(),h=e.Vector3.Zero(),c=Number.MAX_VALUE,l=e.Vector3.Zero(),u=i.getViewMatrix(),d=0;d<s;d++){var f=this.sprites[d];if(f){if(r){if(!r(f))continue}else if(!f.isPickable)continue;if(e.Vector3.TransformCoordinatesToRef(f.position,u,l),a.copyFromFloats(l.x-f.width/2,l.y-f.height/2,l.z),h.copyFromFloats(l.x+f.width/2,l.y+f.height/2,l.z),t.intersectsBoxMinMax(a,h)){var p=e.Vector3.Distance(l,t.origin);if(c>p&&(c=p,o=f,n))break}}}if(o){var m=new e.PickingInfo;return m.hit=!0,m.pickedSprite=o,m.distance=c,m}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;a<n;a++){var h=this.sprites[a];h&&(h._animate(r),this._appendSpriteVertex(s++,h,0,0,o),this._appendSpriteVertex(s++,h,1,0,o),this._appendSpriteVertex(s++,h,1,1,o),this._appendSpriteVertex(s++,h,0,1,o))}this._buffer.update(this._vertexData);var c=this._effectBase;this._scene.fogEnabled&&this._scene.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(c=this._effectFog),t.enableEffect(c);var l=this._scene.getViewMatrix();c.setTexture("diffuseSampler",this._spriteTexture),c.setMatrix("view",l),c.setMatrix("projection",this._scene.getProjectionMatrix()),c.setFloat2("textureInfos",this.cellWidth/i.width,this.cellHeight/i.height),this._scene.fogEnabled&&this._scene.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(c.setFloat4("vFogInfos",this._scene.fogMode,this._scene.fogStart,this._scene.fogEnd,this._scene.fogDensity),c.setColor3("vFogColor",this._scene.fogColor)),t.bindBuffers(this._vertexBuffers,this._indexBuffer,c),t.setDepthFunctionToLessOrEqual(),c.setBool("alphaTest",!0),t.setColorWrite(!1),t.draw(!0,0,6*n),t.setColorWrite(!0),c.setBool("alphaTest",!1),t.setAlphaMode(e.Engine.ALPHA_COMBINE),t.draw(!0,0,6*n),t.setAlphaMode(e.Engine.ALPHA_DISABLE)}},t.prototype.dispose=function(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._spriteTexture&&(this._spriteTexture.dispose(),this._spriteTexture=null);var e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t})();e.SpriteManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.name=t,this.color=new e.Color4(1,1,1,1),this.width=1,this.height=1,this.angle=0,this.cellIndex=0,this.invertU=0,this.invertV=0,this.animations=new Array,this.isPickable=!1,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._frameCount=0,this._time=0,this._manager=i,this._manager.sprites.push(this),this.position=e.Vector3.Zero()}return Object.defineProperty(t.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!0,configurable:!0}),t.prototype.playAnimation=function(e,t,i,r,n){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r,this._animationStarted=!0,this._direction=e<t?1:-1,this.cellIndex=e,this._time=0,this._onAnimationEnd=n},t.prototype.stopAnimation=function(){this._animationStarted=!1},t.prototype._animate=function(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex===this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1)},t})();e.Sprite=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.name=t,this.scale=new e.Vector2(1,1),this.offset=new e.Vector2(0,0),this.alphaBlendingMode=e.Engine.ALPHA_COMBINE,this._vertexBuffers={},this.onDisposeObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.texture=i?new e.Texture(i,r,(!0)):null,this.isBackground=void 0===n||n,this.color=void 0===o?new e.Color4(1,1,1,1):o,this._scene=r,this._scene.layers.push(this);var s=r.getEngine(),a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);var h=new e.VertexBuffer(s,a,e.VertexBuffer.PositionKind,(!1),(!1),2);this._vertexBuffers[e.VertexBuffer.PositionKind]=h;var c=[];c.push(0),c.push(1),c.push(2),c.push(0),c.push(2),c.push(3),this._indexBuffer=s.createIndexBuffer(c),this._effect=s.createEffect("layer",[e.VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],""),this._alphaTestEffect=s.createEffect("layer",[e.VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],"#define ALPHATEST")}return Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.render=function(){var t=this.alphaTest?this._alphaTestEffect:this._effect;if(t.isReady()&&this.texture&&this.texture.isReady()){var i=this._scene.getEngine();this.onBeforeRenderObservable.notifyObservers(this),i.enableEffect(t),i.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?i.draw(!0,0,6):(i.setAlphaMode(this.alphaBlendingMode),i.draw(!0,0,6),i.setAlphaMode(e.Engine.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this)}},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null);var i=this._scene.layers.indexOf(this);this._scene.layers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},t})();e.Layer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.position=e.Vector3.Zero(),this.direction=e.Vector3.Zero(),this.color=new e.Color4(0,0,0,0),this.colorStep=new e.Color4(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.angle=0,this.angularSpeed=0}return t.prototype.copyTo=function(e){e.position.copyFrom(this.position),e.direction.copyFrom(this.direction),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e.size=this.size,e.angle=this.angle,e.angularSpeed=this.angularSpeed},t})();e.Particle=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t){if(e===t)return e;var i=Math.random();return i*(t-e)+e},i=(function(){function i(r,n,o,s){var a=this;this.name=r,this.animations=[],this.renderingGroupId=0,this.emitter=null,this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.onDisposeObservable=new e.Observable,this.blendMode=i.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.gravity=e.Vector3.Zero(),this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3((-.5),(-.5),(-.5)),this.maxEmitBox=new e.Vector3(.5,.5,.5),this.color1=new e.Color4(1,1,1,1),this.color2=new e.Color4(1,1,1,1),this.colorDead=new e.Color4(0,0,0,1),this.textureMask=new e.Color4(1,1,1,1),this.particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new e.Color4(0,0,0,0),this._colorDiff=new e.Color4(0,0,0,0),this._scaledDirection=e.Vector3.Zero(),this._scaledGravity=e.Vector3.Zero(),this._currentRenderId=-1,this._started=!1,this._stopped=!1,this._actualFrame=0,this.id=r,this._capacity=n,this._scene=o,this._customEffect=s,o.particleSystems.push(this);for(var h=[],c=0,l=0;l<n;l++)h.push(c),h.push(c+1),h.push(c+2),h.push(c),h.push(c+2),h.push(c+3),c+=4;this._indexBuffer=o.getEngine().createIndexBuffer(h),this._vertexData=new Float32Array(11*n*4),this._vertexBuffer=new e.Buffer(o.getEngine(),this._vertexData,(!0),11);var u=this._vertexBuffer.createVertexBuffer(e.VertexBuffer.PositionKind,0,3),d=this._vertexBuffer.createVertexBuffer(e.VertexBuffer.ColorKind,3,4),f=this._vertexBuffer.createVertexBuffer("options",7,4);this._vertexBuffers[e.VertexBuffer.PositionKind]=u,this._vertexBuffers[e.VertexBuffer.ColorKind]=d,this._vertexBuffers.options=f,this.startDirectionFunction=function(i,r,n,o){var s=t(a.direction1.x,a.direction2.x),h=t(a.direction1.y,a.direction2.y),c=t(a.direction1.z,a.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(s*i,h*i,c*i,r,n)},this.startPositionFunction=function(i,r,n){var o=t(a.minEmitBox.x,a.maxEmitBox.x),s=t(a.minEmitBox.y,a.maxEmitBox.y),h=t(a.minEmitBox.z,a.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(o,s,h,i,r);
},this.updateFunction=function(e){for(var t=0;t<e.length;t++){var i=e[t];i.age+=a._scaledUpdateSpeed,i.age>=i.lifeTime?(a.recycleParticle(i),t--):(i.colorStep.scaleToRef(a._scaledUpdateSpeed,a._scaledColorStep),i.color.addInPlace(a._scaledColorStep),i.color.a<0&&(i.color.a=0),i.angle+=i.angularSpeed*a._scaledUpdateSpeed,i.direction.scaleToRef(a._scaledUpdateSpeed,a._scaledDirection),i.position.addInPlace(a._scaledDirection),a.gravity.scaleToRef(a._scaledUpdateSpeed,a._scaledGravity),i.direction.addInPlace(a._scaledGravity))}}}return Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),i.prototype.recycleParticle=function(e){var t=this.particles.pop();t!==e&&(t.copyTo(e),this._stockParticles.push(t))},i.prototype.getCapacity=function(){return this._capacity},i.prototype.isAlive=function(){return this._alive},i.prototype.isStarted=function(){return this._started},i.prototype.start=function(){this._started=!0,this._stopped=!1,this._actualFrame=0},i.prototype.stop=function(){this._stopped=!0},i.prototype._appendParticleVertex=function(e,t,i,r){var n=11*e;this._vertexData[n]=t.position.x,this._vertexData[n+1]=t.position.y,this._vertexData[n+2]=t.position.z,this._vertexData[n+3]=t.color.r,this._vertexData[n+4]=t.color.g,this._vertexData[n+5]=t.color.b,this._vertexData[n+6]=t.color.a,this._vertexData[n+7]=t.angle,this._vertexData[n+8]=t.size,this._vertexData[n+9]=i,this._vertexData[n+10]=r},i.prototype._update=function(i){this._alive=this.particles.length>0,this.updateFunction(this.particles);var r;r=this.emitter.position?this.emitter.getWorldMatrix():e.Matrix.Translation(this.emitter.x,this.emitter.y,this.emitter.z);for(var n,o=0;o<i&&this.particles.length!==this._capacity;o++){0!==this._stockParticles.length?(n=this._stockParticles.pop(),n.age=0):n=new e.Particle,this.particles.push(n);var s=t(this.minEmitPower,this.maxEmitPower);this.startDirectionFunction(s,r,n.direction,n),n.lifeTime=t(this.minLifeTime,this.maxLifeTime),n.size=t(this.minSize,this.maxSize),n.angularSpeed=t(this.minAngularSpeed,this.maxAngularSpeed),this.startPositionFunction(r,n.position,n);var a=t(0,1);e.Color4.LerpToRef(this.color1,this.color2,a,n.color),this.colorDead.subtractToRef(n.color,this._colorDiff),this._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)}},i.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var t=[];this._scene.clipPlane&&t.push("#define CLIPPLANE");var i=t.join("\n");return this._cachedDefines!==i&&(this._cachedDefines=i,this._effect=this._scene.getEngine().createEffect("particles",[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"options"],["invView","view","projection","vClipPlane","textureMask"],["diffuseSampler"],i)),this._effect},i.prototype.animate=function(){if(this._started){var e=this._getEffect();if(this.emitter&&e.isReady()&&this.particleTexture&&this.particleTexture.isReady()&&this._currentRenderId!==this._scene.getRenderId()){this._currentRenderId=this._scene.getRenderId(),this._scaledUpdateSpeed=this.updateSpeed*this._scene.getAnimationRatio();var t;this.manualEmitCount>-1?(t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(t=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-t),this._newPartsExcess>1&&(t+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.disposeOnStop&&this._scene._toBeDisposed.push(this)));for(var i=0,r=0;r<this.particles.length;r++){var n=this.particles[r];this._appendParticleVertex(i++,n,0,0),this._appendParticleVertex(i++,n,1,0),this._appendParticleVertex(i++,n,1,1),this._appendParticleVertex(i++,n,0,1)}this._vertexBuffer.update(this._vertexData)}}},i.prototype.render=function(){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()&&this.particles.length))return 0;var r=this._scene.getEngine();r.enableEffect(t),r.setState(!1);var n=this._scene.getViewMatrix();if(t.setTexture("diffuseSampler",this.particleTexture),t.setMatrix("view",n),t.setMatrix("projection",this._scene.getProjectionMatrix()),t.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._scene.clipPlane){var o=this._scene.clipPlane,s=n.clone();s.invert(),t.setMatrix("invView",s),t.setFloat4("vClipPlane",o.normal.x,o.normal.y,o.normal.z,o.d)}return r.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.blendMode===i.BLENDMODE_ONEONE?r.setAlphaMode(e.Engine.ALPHA_ONEONE):r.setAlphaMode(e.Engine.ALPHA_COMBINE),this.forceDepthWrite&&r.setDepthWrite(!0),r.draw(!0,0,6*this.particles.length),r.setAlphaMode(e.Engine.ALPHA_DISABLE),this.particles.length},i.prototype.dispose=function(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null);var e=this._scene.particleSystems.indexOf(this);this._scene.particleSystems.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},i.prototype.clone=function(t,r){var n=new i(t,this._capacity,this._scene);return e.Tools.DeepCopy(this,n,["particles"]),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n.start(),n},i.prototype.serialize=function(){var t={};return t.name=this.name,t.id=this.id,this.emitter.position?t.emitterId=this.emitter.id:t.emitter=this.emitter.asArray(),t.capacity=this.getCapacity(),this.particleTexture&&(t.textureName=this.particleTexture.name),e.Animation.AppendSerializedAnimations(this,t),t.minAngularSpeed=this.minAngularSpeed,t.maxAngularSpeed=this.maxAngularSpeed,t.minSize=this.minSize,t.maxSize=this.maxSize,t.minEmitPower=this.minEmitPower,t.maxEmitPower=this.maxEmitPower,t.minLifeTime=this.minLifeTime,t.maxLifeTime=this.maxLifeTime,t.emitRate=this.emitRate,t.minEmitBox=this.minEmitBox.asArray(),t.maxEmitBox=this.maxEmitBox.asArray(),t.gravity=this.gravity.asArray(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.color1=this.color1.asArray(),t.color2=this.color2.asArray(),t.colorDead=this.colorDead.asArray(),t.updateSpeed=this.updateSpeed,t.targetStopDuration=this.targetStopDuration,t.textureMask=this.textureMask.asArray(),t.blendMode=this.blendMode,t},i.Parse=function(t,r,n){var o=t.name,s=new i(o,t.capacity,r);if(t.id&&(s.id=t.id),t.textureName&&(s.particleTexture=new e.Texture(n+t.textureName,r),s.particleTexture.name=t.textureName),t.emitterId?s.emitter=r.getLastMeshByID(t.emitterId):s.emitter=e.Vector3.FromArray(t.emitter),t.animations)for(var a=0;a<t.animations.length;a++){var h=t.animations[a];s.animations.push(e.Animation.Parse(h))}return t.autoAnimate&&r.beginAnimation(s,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),s.minAngularSpeed=t.minAngularSpeed,s.maxAngularSpeed=t.maxAngularSpeed,s.minSize=t.minSize,s.maxSize=t.maxSize,s.minLifeTime=t.minLifeTime,s.maxLifeTime=t.maxLifeTime,s.minEmitPower=t.minEmitPower,s.maxEmitPower=t.maxEmitPower,s.emitRate=t.emitRate,s.minEmitBox=e.Vector3.FromArray(t.minEmitBox),s.maxEmitBox=e.Vector3.FromArray(t.maxEmitBox),s.gravity=e.Vector3.FromArray(t.gravity),s.direction1=e.Vector3.FromArray(t.direction1),s.direction2=e.Vector3.FromArray(t.direction2),s.color1=e.Color4.FromArray(t.color1),s.color2=e.Color4.FromArray(t.color2),s.colorDead=e.Color4.FromArray(t.colorDead),s.updateSpeed=t.updateSpeed,s.targetStopDuration=t.targetStopDuration,s.textureMask=e.Color4.FromArray(t.textureMask),s.blendMode=t.blendMode,t.preventAutoStart||s.start(),s},i.BLENDMODE_ONEONE=0,i.BLENDMODE_STANDARD=1,i})();e.ParticleSystem=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(e){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._events=new Array,this.allowMatricesInterpolation=!1,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,h,c){var l=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?l=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?l=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?l=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?l=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?l=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(l=i.ANIMATIONTYPE_SIZE),void 0==l)return null;var u=new i(t,r,n,l,h),d=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(d),void 0!==c&&u.setEasingFunction(c),u},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,h,c,l){var u=i._PrepareAnimation(e,r,n,o,s,a,h,c);return t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,l)},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,h,c,l){var u=i._PrepareAnimation(e,r,n,o,s,a,h,c);return t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,l)},i.prototype.toString=function(e){var t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},i.prototype.addEvent=function(e){this._events.push(e)},i.prototype.removeEvents=function(e){for(var t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)},i.prototype.createRange=function(e,i,r){this._ranges[e]||(this._ranges[e]=new t(e,i,r))},i.prototype.deleteRange=function(e,t){if(void 0===t&&(t=!0),this._ranges[e]){if(t)for(var i=this._ranges[e].from,r=this._ranges[e].to,n=this._keys.length-1;n>=0;n--)this._keys[n].frame>=i&&this._keys[n].frame<=r&&this._keys.splice(n,1);this._ranges[e]=void 0}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.reset=function(){this._offsetsCache={},this._highLimitsCache={},this.currentFrame=0,this._blendingFactor=0,this._originalBlendValue=null},i.prototype.isStopped=function(){return this._stopped},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e},i.prototype.getEasingFunction=function(){return this._easingFunction},i.prototype.setEasingFunction=function(e){this._easingFunction=e},i.prototype.floatInterpolateFunction=function(e,t,i){return e+(t-e)*i},i.prototype.quaternionInterpolateFunction=function(t,i,r){return e.Quaternion.Slerp(t,i,r)},i.prototype.vector3InterpolateFunction=function(t,i,r){return e.Vector3.Lerp(t,i,r)},i.prototype.vector2InterpolateFunction=function(t,i,r){return e.Vector2.Lerp(t,i,r)},i.prototype.sizeInterpolateFunction=function(t,i,r){return e.Size.Lerp(t,i,r)},i.prototype.color3InterpolateFunction=function(t,i,r){return e.Color3.Lerp(t,i,r)},i.prototype.matrixInterpolateFunction=function(t,i,r){return e.Matrix.Lerp(t,i,r)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges)e._ranges[t]=this._ranges[t].clone()}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0),this._offsetsCache={},this._highLimitsCache={}},i.prototype._getKeyValue=function(e){return"function"==typeof e?e():e},i.prototype._interpolate=function(e,t,r,n,o){if(r===i.ANIMATIONLOOPMODE_CONSTANT&&t>0)return o.clone?o.clone():o;this.currentFrame=e;var s=Math.max(0,Math.min(this._keys.length-1,Math.floor(this._keys.length*(e-this._keys[0].frame)/(this._keys[this._keys.length-1].frame-this._keys[0].frame))-1));if(this._keys[s].frame>=e)for(;s-1>=0&&this._keys[s].frame>=e;)s--;for(var a=s;a<this._keys.length;a++)if(this._keys[a+1].frame>=e){var h=this._getKeyValue(this._keys[a].value),c=this._getKeyValue(this._keys[a+1].value),l=(e-this._keys[a].frame)/(this._keys[a+1].frame-this._keys[a].frame);switch(null!=this._easingFunction&&(l=this._easingFunction.ease(l)),this.dataType){case i.ANIMATIONTYPE_FLOAT:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.floatInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return n*t+this.floatInterpolateFunction(h,c,l)}break;case i.ANIMATIONTYPE_QUATERNION:var u=null;switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:u=this.quaternionInterpolateFunction(h,c,l);break;case i.ANIMATIONLOOPMODE_RELATIVE:u=this.quaternionInterpolateFunction(h,c,l).add(n.scale(t))}return u;case i.ANIMATIONTYPE_VECTOR3:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.vector3InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.vector3InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_VECTOR2:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.vector2InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.vector2InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(this.allowMatricesInterpolation)return this.matrixInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return h}}break}return this._getKeyValue(this._keys[this._keys.length-1].value)},i.prototype.setValue=function(t,i){void 0===i&&(i=!1);var r,n;if(this.targetPropertyPath.length>1){for(var o=this._target[this.targetPropertyPath[0]],s=1;s<this.targetPropertyPath.length-1;s++)o=o[this.targetPropertyPath[s]];r=this.targetPropertyPath[this.targetPropertyPath.length-1],n=o}else r=this.targetPropertyPath[0],n=this._target;this.enableBlending&&this._blendingFactor<=1?(this._originalBlendValue||(n[r].clone?this._originalBlendValue=n[r].clone():this._originalBlendValue=n[r]),this._originalBlendValue.prototype?this._originalBlendValue.prototype.Lerp?n[r]=this._originalBlendValue.construtor.prototype.Lerp(t,this._originalBlendValue,this._blendingFactor):n[r]=t:this._originalBlendValue.m?n[r]=e.Matrix.Lerp(this._originalBlendValue,t,this._blendingFactor):n[r]=this._originalBlendValue*(1-this._blendingFactor)+this._blendingFactor*t,this._blendingFactor+=this.blendingSpeed):n[r]=t,this._target.markAsDirty&&this._target.markAsDirty(this.targetProperty)},i.prototype.goToFrame=function(e){e<this._keys[0].frame?e=this._keys[0].frame:e>this._keys[this._keys.length-1].frame&&(e=this._keys[this._keys.length-1].frame);var t=this._interpolate(e,0,this.loopMode);this.setValue(t)},i.prototype.animate=function(t,r,n,o,s,a){if(void 0===a&&(a=!1),!this.targetPropertyPath||this.targetPropertyPath.length<1)return this._stopped=!0,!1;var h=!0;if(0!==this._keys[0].frame){var c={frame:0,value:this._keys[0].value};this._keys.splice(0,0,c)}(r<this._keys[0].frame||r>this._keys[this._keys.length-1].frame)&&(r=this._keys[0].frame),(n<this._keys[0].frame||n>this._keys[this._keys.length-1].frame)&&(n=this._keys[this._keys.length-1].frame),r===n&&r++;var l,u=n-r,d=t*(this.framePerSecond*s)/1e3,f=0;if(d>u&&!o)h=!1,f=this._getKeyValue(this._keys[this._keys.length-1].value);else if(this.loopMode!==i.ANIMATIONLOOPMODE_CYCLE){var p=n.toString()+r.toString();if(!this._offsetsCache[p]){var m=this._interpolate(r,0,i.ANIMATIONLOOPMODE_CYCLE),_=this._interpolate(n,0,i.ANIMATIONLOOPMODE_CYCLE);switch(this.dataType){case i.ANIMATIONTYPE_FLOAT:this._offsetsCache[p]=_-m;break;case i.ANIMATIONTYPE_QUATERNION:this._offsetsCache[p]=_.subtract(m);break;case i.ANIMATIONTYPE_VECTOR3:this._offsetsCache[p]=_.subtract(m);case i.ANIMATIONTYPE_VECTOR2:this._offsetsCache[p]=_.subtract(m);case i.ANIMATIONTYPE_SIZE:this._offsetsCache[p]=_.subtract(m);case i.ANIMATIONTYPE_COLOR3:this._offsetsCache[p]=_.subtract(m)}this._highLimitsCache[p]=_}f=this._highLimitsCache[p],l=this._offsetsCache[p]}if(void 0===l)switch(this.dataType){case i.ANIMATIONTYPE_FLOAT:l=0;break;case i.ANIMATIONTYPE_QUATERNION:l=new e.Quaternion(0,0,0,0);break;case i.ANIMATIONTYPE_VECTOR3:l=e.Vector3.Zero();break;case i.ANIMATIONTYPE_VECTOR2:l=e.Vector2.Zero();break;case i.ANIMATIONTYPE_SIZE:l=e.Size.Zero();break;case i.ANIMATIONTYPE_COLOR3:l=e.Color3.Black()}var g=d/u>>0,v=h?r+d%u:n,y=this._interpolate(v,g,this.loopMode,l,f);this.setValue(y);for(var x=0;x<this._events.length;x++)if(v>=this._events[x].frame){var b=this._events[x];b.isDone||(b.onlyOnce&&(this._events.splice(x,1),x--),b.isDone=!0,b.action())}else this._events[x].isDone&&!this._events[x].onlyOnce&&(this._events[x].isDone=!1);return h||(this._stopped=!0),h},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n<r.length;n++){var o=r[n],s={};switch(s.frame=o.frame,t){case i.ANIMATIONTYPE_FLOAT:s.values=[o.value];break;case i.ANIMATIONTYPE_QUATERNION:case i.ANIMATIONTYPE_MATRIX:case i.ANIMATIONTYPE_VECTOR3:case i.ANIMATIONTYPE_COLOR3:s.values=o.value.asArray()}e.keys.push(s)}e.ranges=[];for(var a in this._ranges){var h={};h.name=a,h.from=this._ranges[a].from,h.to=this._ranges[a].to,e.ranges.push(h)}return e},Object.defineProperty(i,"ANIMATIONTYPE_FLOAT",{get:function(){return i._ANIMATIONTYPE_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_VECTOR3",{get:function(){return i._ANIMATIONTYPE_VECTOR3},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_VECTOR2",{get:function(){return i._ANIMATIONTYPE_VECTOR2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_SIZE",{get:function(){return i._ANIMATIONTYPE_SIZE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_QUATERNION",{get:function(){return i._ANIMATIONTYPE_QUATERNION},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_MATRIX",{get:function(){return i._ANIMATIONTYPE_MATRIX},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_COLOR3",{get:function(){return i._ANIMATIONTYPE_COLOR3},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_RELATIVE",{get:function(){return i._ANIMATIONLOOPMODE_RELATIVE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_CYCLE",{get:function(){return i._ANIMATIONLOOPMODE_CYCLE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_CONSTANT",{get:function(){return i._ANIMATIONLOOPMODE_CONSTANT},enumerable:!0,configurable:!0}),i.Parse=function(t){var r,n,o=new i(t.name,t.property,t.framePerSecond,t.dataType,t.loopBehavior),s=t.dataType,a=[];for(n=0;n<t.keys.length;n++){var h=t.keys[n];switch(s){case i.ANIMATIONTYPE_FLOAT:r=h.values[0];break;case i.ANIMATIONTYPE_QUATERNION:r=e.Quaternion.FromArray(h.values);break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(h.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(h.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(h.values)}a.push({frame:h.frame,value:r})}if(o.setKeys(a),t.ranges)for(n=0;n<t.ranges.length;n++)r=t.ranges[n],o.createRange(r.name,r.from,r.to);return o},i.AppendSerializedAnimations=function(e,t){if(e.animations){t.animations=[];for(var i=0;i<e.animations.length;i++){var r=e.animations[i];t.animations.push(r.serialize())}}},i._ANIMATIONTYPE_FLOAT=0,i._ANIMATIONTYPE_VECTOR3=1,i._ANIMATIONTYPE_QUATERNION=2,i._ANIMATIONTYPE_MATRIX=3,i._ANIMATIONTYPE_COLOR3=4,i._ANIMATIONTYPE_VECTOR2=5,i._ANIMATIONTYPE_SIZE=6,i._ANIMATIONLOOPMODE_RELATIVE=0,i._ANIMATIONLOOPMODE_CYCLE=1,i._ANIMATIONLOOPMODE_CONSTANT=2,i})();e.Animation=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i,r,n,o,s,a){void 0===i&&(i=0),void 0===r&&(r=100),void 0===n&&(n=!1),void 0===o&&(o=1),this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=n,this.speedRatio=o,this.onAnimationEnd=s,this._animations=new Array,this._paused=!1,this.animationStarted=!1,a&&this.appendAnimations(t,a),this._scene=e,e._activeAnimatables.push(this)}return e.prototype.getAnimations=function(){return this._animations},e.prototype.appendAnimations=function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r._target=e,this._animations.push(r)}},e.prototype.getAnimationByTargetProperty=function(e){for(var t=this._animations,i=0;i<t.length;i++)if(t[i].targetProperty===e)return t[i];return null},e.prototype.reset=function(){for(var e=this._animations,t=0;t<e.length;t++)e[t].reset();this._localDelayOffset=null,this._pausedDelay=null},e.prototype.enableBlending=function(e){for(var t=this._animations,i=0;i<t.length;i++)t[i].enableBlending=!0,t[i].blendingSpeed=e},e.prototype.disableBlending=function(){for(var e=this._animations,t=0;t<e.length;t++)e[t].enableBlending=!1},e.prototype.goToFrame=function(e){var t=this._animations;if(t[0]){var i=t[0].framePerSecond,r=t[0].currentFrame,n=e-r,o=1e3*n/i;this._localDelayOffset-=o}for(var s=0;s<t.length;s++)t[s].goToFrame(e)},e.prototype.pause=function(){this._paused||(this._paused=!0)},e.prototype.restart=function(){this._paused=!1},e.prototype.stop=function(e){var t=this._scene._activeAnimatables.indexOf(this);if(t>-1){for(var i=this._animations,r=0,t=i.length-1;t>=0;t--)"string"==typeof e&&i[t].name!=e||(i[t].reset(),i.splice(t,1),r++);i.length==r&&(this._scene._activeAnimatables.splice(t,1),this.onAnimationEnd&&this.onAnimationEnd())}},e.prototype._animate=function(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay||(this._pausedDelay=e),!0;this._localDelayOffset?this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null):this._localDelayOffset=e;var t,i=!1,r=this._animations;for(t=0;t<r.length;t++){var n=r[t],o=n.animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this.speedRatio);i=i||o}return this.animationStarted=i,i||(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1)),!i&&this.onAnimationEnd&&(this.onAnimationEnd(),this.onAnimationEnd=null),i},e})();e.Animatable=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._easingMode=e.EASINGMODE_EASEIN}return Object.defineProperty(e,"EASINGMODE_EASEIN",{get:function(){return e._EASINGMODE_EASEIN},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EASINGMODE_EASEOUT",{get:function(){return e._EASINGMODE_EASEOUT},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EASINGMODE_EASEINOUT",{get:function(){return e._EASINGMODE_EASEINOUT},enumerable:!0,configurable:!0}),e.prototype.setEasingMode=function(e){var t=Math.min(Math.max(e,0),2);this._easingMode=t},e.prototype.getEasingMode=function(){return this._easingMode},e.prototype.easeInCore=function(e){throw new Error("You must implement this method")},e.prototype.ease=function(t){switch(this._easingMode){case e.EASINGMODE_EASEIN:return this.easeInCore(t);case e.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-t)}return t>=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1),e.call(this),this.amplitude=t}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2),e.call(this),this.bounces=t,this.bounciness=i}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),h=Math.floor(a),c=h+1,l=(1-Math.pow(i,h))/(n*o),u=(1-Math.pow(i,c))/(n*o),d=.5*(l+u),f=e-d,p=d-l;return-Math.pow(1/i,t-h)/(p*p)*(f-p)*(f+p)},t})(t);e.BounceEase=n;var o=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=o;var s=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3),e.call(this),this.oscillations=t,this.springiness=i}return __extends(t,e),t.prototype.easeInCore=function(e){var t,i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return t=0==r?e:(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)},t})(t);e.ElasticEase=s;var a=(function(e){function t(t){void 0===t&&(t=2),e.call(this),this.exponent=t}return __extends(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=a;var h=(function(e){function t(t){void 0===t&&(t=2),e.call(this),this.power=t}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=h;var c=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=c;var l=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=l;var u=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=u;var d=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=d;var f=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1),t.call(this),this.x1=e,this.y1=i,this.x2=r,this.y2=n}return __extends(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=f})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){t.call(this,i,r.getScene()),this.name=i,this.children=new Array,this.animations=new Array,this._worldTransform=new e.Matrix,this._absoluteTransform=new e.Matrix,this._invertedAbsoluteTransform=new e.Matrix,this._scaleMatrix=e.Matrix.Identity(),this._scaleVector=new e.Vector3(1,1,1),this._negateScaleChildren=new e.Vector3(1,1,1),this._scalingDeterminant=1,this._syncScaleVector=function(){var t=this.getLocalMatrix(),i=t.m[0]*t.m[0]+t.m[1]*t.m[1]+t.m[2]*t.m[2],r=t.m[4]*t.m[4]+t.m[5]*t.m[5]+t.m[6]*t.m[6],n=t.m[8]*t.m[8]+t.m[9]*t.m[9]+t.m[10]*t.m[10],o=t.m[0]*t.m[1]*t.m[2]*t.m[3]<0?-1:1,s=t.m[4]*t.m[5]*t.m[6]*t.m[7]<0?-1:1,a=t.m[8]*t.m[9]*t.m[10]*t.m[11]<0?-1:1;this._scaleVector.x=o*Math.sqrt(i),this._scaleVector.y=s*Math.sqrt(r),this._scaleVector.z=a*Math.sqrt(n),this._parent&&(this._scaleVector.x/=this._parent._negateScaleChildren.x,this._scaleVector.y/=this._parent._negateScaleChildren.y,this._scaleVector.z/=this._parent._negateScaleChildren.z),e.Matrix.FromValuesToRef(this._scaleVector.x,0,0,0,0,this._scaleVector.y,0,0,0,0,this._scaleVector.z,0,0,0,0,1,this._scaleMatrix)},this._skeleton=r,this._matrix=o,this._baseMatrix=o,this._restPose=s?s:o.clone(),r.bones.push(this),n?(this._parent=n,n.children.push(this)):this._parent=null,this._updateDifferenceMatrix(),this.getAbsoluteTransform().determinant()<0&&(this._scalingDeterminant*=-1)}return __extends(i,t),i.prototype.getParent=function(){return this._parent},i.prototype.getLocalMatrix=function(){return this._matrix},i.prototype.getBaseMatrix=function(){return this._baseMatrix},i.prototype.getRestPose=function(){return this._restPose},i.prototype.returnToRest=function(){this.updateMatrix(this._restPose.clone())},i.prototype.getWorldMatrix=function(){return this._worldTransform},i.prototype.getInvertedAbsoluteTransform=function(){return this._invertedAbsoluteTransform},i.prototype.getAbsoluteTransform=function(){return this._absoluteTransform},i.prototype.updateMatrix=function(e,t){void 0===t&&(t=!0),this._baseMatrix=e.clone(),this._matrix=e.clone(),this._skeleton._markAsDirty(),t&&this._updateDifferenceMatrix()},i.prototype._updateDifferenceMatrix=function(e){e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);for(var t=0;t<this.children.length;t++)this.children[t]._updateDifferenceMatrix()},i.prototype.markAsDirty=function(){this._currentRenderId++,this._skeleton._markAsDirty()},i.prototype.copyAnimationRange=function(t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=null),0===this.animations.length&&(this.animations.push(new e.Animation(this.name,"_matrix",t.animations[0].framePerSecond,e.Animation.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));var s=t.animations[0].getRange(i);if(!s)return!1;for(var a,h,c,l=s.from,u=s.to,d=t.animations[0].getKeys(),f=t.length,p=t.getParent(),m=this.getParent(),_=n&&p&&f&&this.length&&f!==this.length,g=_?m.length/p.length:null,v=n&&!m&&o&&(1!==o.x||1!==o.y||1!==o.z),y=this.animations[0].getKeys(),x=0,b=d.length;x<b;x++)a=d[x],a.frame>=l&&a.frame<=u&&(n?(c=a.value.clone(),_?(h=c.getTranslation(),c.setTranslation(h.scaleInPlace(g))):v?(h=c.getTranslation(),c.setTranslation(h.multiplyInPlace(o))):c=a.value):c=a.value,y.push({frame:a.frame+r,value:c}));return this.animations[0].createRange(i,l+r,u+r),!0},i.prototype.translate=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix();if(i==e.Space.LOCAL)n.m[12]+=t.x,n.m[13]+=t.y,n.m[14]+=t.z;else{this._skeleton.computeAbsoluteTransforms();
var o=e.Tmp.Matrix[0],s=e.Tmp.Vector3[0];r?(o.copyFrom(this._parent.getAbsoluteTransform()),o.multiplyToRef(r.getWorldMatrix(),o)):o.copyFrom(this._parent.getAbsoluteTransform()),o.m[12]=0,o.m[13]=0,o.m[14]=0,o.invert(),e.Vector3.TransformCoordinatesToRef(t,o,s),n.m[12]+=s.x,n.m[13]+=s.y,n.m[14]+=s.z}this.markAsDirty()},i.prototype.setPosition=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix();if(i==e.Space.LOCAL)n.m[12]=t.x,n.m[13]=t.y,n.m[14]=t.z;else{this._skeleton.computeAbsoluteTransforms();var o=e.Tmp.Matrix[0],s=e.Tmp.Vector3[0];r?(o.copyFrom(this._parent.getAbsoluteTransform()),o.multiplyToRef(r.getWorldMatrix(),o)):o.copyFrom(this._parent.getAbsoluteTransform()),o.invert(),e.Vector3.TransformCoordinatesToRef(t,o,s),n.m[12]=s.x,n.m[13]=s.y,n.m[14]=s.z}this.markAsDirty()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.setScale=function(e,t,i,r){void 0===r&&(r=!1),this.animations[0]&&!this.animations[0].isStopped()&&(r||(this._negateScaleChildren.x=1/e,this._negateScaleChildren.y=1/t,this._negateScaleChildren.z=1/i),this._syncScaleVector()),this.scale(e/this._scaleVector.x,t/this._scaleVector.y,i/this._scaleVector.z,r)},i.prototype.scale=function(t,i,r,n){void 0===n&&(n=!1);var o=this.getLocalMatrix(),s=e.Tmp.Matrix[0];s.copyFrom(o);var a=e.Tmp.Matrix[1];a.copyFrom(s),a.invert();var h=e.Tmp.Matrix[2];e.Matrix.FromValuesToRef(t,0,0,0,0,i,0,0,0,0,r,0,0,0,0,1,h),this._scaleMatrix.multiplyToRef(h,this._scaleMatrix),this._scaleVector.x*=t,this._scaleVector.y*=i,this._scaleVector.z*=r,o.multiplyToRef(a,o),o.multiplyToRef(h,o),o.multiplyToRef(s,o);var c=this.getParent();c?o.multiplyToRef(c.getAbsoluteTransform(),this.getAbsoluteTransform()):this.getAbsoluteTransform().copyFrom(o);var l=this.children.length;h.invert();for(var u=0;u<l;u++){var d=this.children[u],f=d.getLocalMatrix();f.multiplyToRef(h,f);var p=d.getLocalMatrix();p.m[12]*=t,p.m[13]*=i,p.m[14]*=r}if(this.computeAbsoluteTransforms(),n)for(var u=0;u<l;u++)this.children[u].scale(t,i,r,n);this.markAsDirty()},i.prototype.setYawPitchRoll=function(t,i,r,n,o){void 0===n&&(n=e.Space.LOCAL);var s=e.Tmp.Matrix[0];e.Matrix.RotationYawPitchRollToRef(t,i,r,s);var a=e.Tmp.Matrix[1];this._getNegativeRotationToRef(a,n,o),a.multiplyToRef(s,s),this._rotateWithMatrix(s,n,o)},i.prototype.rotate=function(t,i,r,n){void 0===r&&(r=e.Space.LOCAL);var o=e.Tmp.Matrix[0];o.m[12]=0,o.m[13]=0,o.m[14]=0,e.Matrix.RotationAxisToRef(t,i,o),this._rotateWithMatrix(o,r,n)},i.prototype.setAxisAngle=function(t,i,r,n){void 0===r&&(r=e.Space.LOCAL);var o=e.Tmp.Matrix[0];e.Matrix.RotationAxisToRef(t,i,o);var s=e.Tmp.Matrix[1];this._getNegativeRotationToRef(s,r,n),s.multiplyToRef(o,o),this._rotateWithMatrix(o,r,n)},i.prototype.setRotation=function(t,i,r){void 0===i&&(i=e.Space.LOCAL),this.setYawPitchRoll(t.y,t.x,t.z,i,r)},i.prototype.setRotationQuaternion=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=e.Tmp.Matrix[0];this._getNegativeRotationToRef(n,i,r);var o=e.Tmp.Matrix[1];e.Matrix.FromQuaternionToRef(t,o),n.multiplyToRef(o,o),this._rotateWithMatrix(o,i,r)},i.prototype.setRotationMatrix=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=e.Tmp.Matrix[0];this._getNegativeRotationToRef(n,i,r);var o=e.Tmp.Matrix[1];o.copyFrom(t),n.multiplyToRef(t,o),this._rotateWithMatrix(o,i,r)},i.prototype._rotateWithMatrix=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix(),o=n.m[12],s=n.m[13],a=n.m[14],h=this.getParent(),c=e.Tmp.Matrix[3],l=e.Tmp.Matrix[4];h?(i==e.Space.WORLD?r?(c.copyFrom(r.getWorldMatrix()),h.getAbsoluteTransform().multiplyToRef(c,c)):c.copyFrom(h.getAbsoluteTransform()):c=h._scaleMatrix,l.copyFrom(c),l.invert(),n.multiplyToRef(c,n),n.multiplyToRef(t,n),n.multiplyToRef(l,n)):i==e.Space.WORLD&&r?(c.copyFrom(r.getWorldMatrix()),l.copyFrom(c),l.invert(),n.multiplyToRef(c,n),n.multiplyToRef(t,n),n.multiplyToRef(l,n)):n.multiplyToRef(t,n),n.m[12]=o,n.m[13]=s,n.m[14]=a,this.computeAbsoluteTransforms(),this.markAsDirty()},i.prototype._getNegativeRotationToRef=function(t,i,r){if(void 0===i&&(i=e.Space.LOCAL),i==e.Space.WORLD){var n=e.Tmp.Matrix[2];if(n.copyFrom(this._scaleMatrix),t.copyFrom(this.getAbsoluteTransform()),r){t.multiplyToRef(r.getWorldMatrix(),t);var o=e.Tmp.Matrix[3];e.Matrix.ScalingToRef(r.scaling.x,r.scaling.y,r.scaling.z,o),n.multiplyToRef(o,n)}t.invert(),n.m[0]*=this._scalingDeterminant,t.multiplyToRef(n,t)}else{t.copyFrom(this.getLocalMatrix()),t.invert();var n=e.Tmp.Matrix[2];if(n.copyFrom(this._scaleMatrix),this._parent){var s=e.Tmp.Matrix[3];s.copyFrom(this._parent._scaleMatrix),s.invert(),s.multiplyToRef(t,t)}else n.m[0]*=this._scalingDeterminant;t.multiplyToRef(n,t)}},i.prototype.getScale=function(){return this._scaleVector.clone()},i.prototype.getScaleToRef=function(e){e.copyFrom(this._scaleVector)},i.prototype.getPosition=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Vector3.Zero();return this.getPositionToRef(t,i,r),r},i.prototype.getPositionToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL){var n=this.getLocalMatrix();r.x=n.m[12],r.y=n.m[13],r.z=n.m[14]}else{this._skeleton.computeAbsoluteTransforms();var o=e.Tmp.Matrix[0];i?(o.copyFrom(this.getAbsoluteTransform()),o.multiplyToRef(i.getWorldMatrix(),o)):o=this.getAbsoluteTransform(),r.x=o.m[12],r.y=o.m[13],r.z=o.m[14]}},i.prototype.getAbsolutePosition=function(t){var i=e.Vector3.Zero();return this.getPositionToRef(e.Space.WORLD,t,i),i},i.prototype.getAbsolutePositionToRef=function(t,i){this.getPositionToRef(e.Space.WORLD,t,i)},i.prototype.computeAbsoluteTransforms=function(){if(this._parent)this._matrix.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform);else{this._absoluteTransform.copyFrom(this._matrix);var e=this._skeleton.getPoseMatrix();e&&this._absoluteTransform.multiplyToRef(e,this._absoluteTransform)}for(var t=this.children,i=t.length,r=0;r<i;r++)t[r].computeAbsoluteTransforms()},i.prototype.getDirection=function(t,i){var r=e.Vector3.Zero();return this.getDirectionToRef(t,i,r),r},i.prototype.getDirectionToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];n.copyFrom(this.getAbsoluteTransform()),i&&n.multiplyToRef(i.getWorldMatrix(),n),e.Vector3.TransformNormalToRef(t,n,r),r.normalize()},i.prototype.getRotation=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Vector3.Zero();return this.getRotationToRef(t,i,r),r},i.prototype.getRotationToRef=function(t,i,r){void 0===t&&(t=e.Space.LOCAL);var n=e.Tmp.Quaternion[0];this.getRotationQuaternionToRef(t,i,n),n.toEulerAnglesToRef(r)},i.prototype.getRotationQuaternion=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Quaternion.Identity();return this.getRotationQuaternionToRef(t,i,r),r},i.prototype.getRotationQuaternionToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL)this.getLocalMatrix().decompose(e.Tmp.Vector3[0],r,e.Tmp.Vector3[1]);else{var n=e.Tmp.Matrix[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.m[0]*=this._scalingDeterminant,n.m[1]*=this._scalingDeterminant,n.m[2]*=this._scalingDeterminant,n.decompose(e.Tmp.Vector3[0],r,e.Tmp.Vector3[1])}},i.prototype.getRotationMatrix=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Matrix.Identity();return this.getRotationMatrixToRef(t,i,r),r},i.prototype.getRotationMatrixToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(r);else{var n=e.Tmp.Matrix[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.m[0]*=this._scalingDeterminant,n.m[1]*=this._scalingDeterminant,n.m[2]*=this._scalingDeterminant,n.getRotationMatrixToRef(r)}},i.prototype.getAbsolutePositionFromLocal=function(t,i){var r=e.Vector3.Zero();return this.getAbsolutePositionFromLocalToRef(t,i,r),r},i.prototype.getAbsolutePositionFromLocalToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];i?(n.copyFrom(this.getAbsoluteTransform()),n.multiplyToRef(i.getWorldMatrix(),n)):n=this.getAbsoluteTransform(),e.Vector3.TransformCoordinatesToRef(t,n,r)},i.prototype.getLocalPositionFromAbsolute=function(t,i){var r=e.Vector3.Zero();return this.getLocalPositionFromAbsoluteToRef(t,i,r),r},i.prototype.getLocalPositionFromAbsoluteToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];n.copyFrom(this.getAbsoluteTransform()),i&&n.multiplyToRef(i.getWorldMatrix(),n),n.invert(),e.Vector3.TransformCoordinatesToRef(t,n,r)},i})(e.Node);e.Bone=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){if(this.targetPosition=e.Vector3.Zero(),this.poleTargetPosition=e.Vector3.Zero(),this.poleTargetLocalOffset=e.Vector3.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=e.Quaternion.Identity(),this._bone1Mat=e.Matrix.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._tmpVec1=e.Vector3.Zero(),this._tmpVec2=e.Vector3.Zero(),this._tmpVec3=e.Vector3.Zero(),this._tmpVec4=e.Vector3.Zero(),this._tmpVec5=e.Vector3.Zero(),this._tmpMat1=e.Matrix.Identity(),this._tmpMat2=e.Matrix.Identity(),this._tmpQuat1=e.Quaternion.Identity(),this._rightHandedSystem=!1,this._bendAxis=e.Vector3.Right(),this._slerping=!1,this._bone2=i,this._bone1=i.getParent(),this.mesh=t,i.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=1),this._bone1.length){var n=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*n.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*o.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var s=this._bone2.children[0].getAbsolutePosition(t),a=this._bone2.getAbsolutePosition(t),h=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(s,a),this._bone2Length=e.Vector3.Distance(a,h)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var t=this._bone1,i=this.targetPosition,r=this.poleTargetPosition,n=this._tmpMat1,o=this._tmpMat2;this.targetMesh&&i.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,r):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),r);var s=this._tmpVec1,a=this._tmpVec2,h=this._tmpVec3,c=this._tmpVec4,l=this._tmpVec5;t.getAbsolutePositionToRef(this.mesh,s),r.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),i.subtractToRef(s,c),c.normalize(),e.Vector3.CrossToRef(c,l,a),a.normalize(),e.Vector3.CrossToRef(c,a,h),h.normalize(),e.Matrix.FromXYZAxesToRef(h,c,a,n);var u=this._bone1Length,d=this._bone2Length,f=e.Vector3.Distance(s,i);this._maxReach>0&&(f=Math.min(this._maxReach,f));var p=(d*d+f*f-u*u)/(2*d*f),m=(f*f+u*u-d*d)/(2*f*u);p>1&&(p=1),m>1&&(m=1),p<-1&&(p=-1),m<-1&&(m=-1);var _=Math.acos(p),g=Math.acos(m),v=-_-g;this._rightHandedSystem?(e.Matrix.RotationYawPitchRollToRef(0,0,.5*Math.PI,o),o.multiplyToRef(n,n),e.Matrix.RotationAxisToRef(this._bendAxis,g,o),o.multiplyToRef(n,n)):(this._tmpVec1.copyFrom(this._bendAxis),this._tmpVec1.x*=-1,e.Matrix.RotationAxisToRef(this._tmpVec1,-g,o),o.multiplyToRef(n,n)),this.poleAngle&&(e.Matrix.RotationAxisToRef(c,this.poleAngle,o),n.multiplyToRef(o,n)),this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(n,this._tmpQuat1),e.Quaternion.SlerpToRef(this._bone1Quat,this._tmpQuat1,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(n,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(n),this._slerping=!1),this._bone2.setAxisAngle(this._bendAxis,v,e.Space.LOCAL),this._bone2Ang=v},t})();e.BoneIKController=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){this.upAxis=e.Vector3.Up(),this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this._tmpVec1=e.Vector3.Zero(),this._tmpVec2=e.Vector3.Zero(),this._tmpVec3=e.Vector3.Zero(),this._tmpVec4=e.Vector3.Zero(),this._tmpMat1=e.Matrix.Identity(),this._tmpMat2=e.Matrix.Identity(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll))}return t.prototype.update=function(){var t=this.bone,i=this.target,r=this._tmpVec1,n=this._tmpVec2,o=this._tmpVec3,s=this._tmpVec4,a=this._tmpMat1,h=this._tmpMat2;t.getAbsolutePositionToRef(this.mesh,r),i.subtractToRef(r,n),n.normalize(),e.Vector3.CrossToRef(this.upAxis,n,o),o.normalize(),e.Vector3.CrossToRef(n,o,s),s.normalize(),e.Matrix.FromXYZAxesToRef(o,s,n,a),(this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(e.Matrix.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,h),h.multiplyToRef(a,a)),this.bone.setRotationMatrix(a,e.Space.WORLD,this.mesh)},t})();e.BoneLookController=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.id=i,this.bones=new Array,this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=e.Matrix.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this.bones=[],this._scene=r,r.skeletons.push(this),this._isDirty=!0}return t.prototype.getTransformMatrices=function(e){return this.needInitialSkinMatrix&&e._bonesTransformMatrices?e._bonesTransformMatrices:this._transformMatrices},t.prototype.getScene=function(){return this._scene},t.prototype.toString=function(e){var t="Name: "+this.name+", nBones: "+this.bones.length;if(t+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},t.prototype.getBoneIndexByName=function(e){for(var t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1},t.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=new e.AnimationRange(t,i,r);for(var n=0,o=this.bones.length;n<o;n++)this.bones[n].animations[0]&&this.bones[n].animations[0].createRange(t,i,r)}},t.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=void 0},t.prototype.getAnimationRange=function(e){return this._ranges[e]},t.prototype.getAnimationRanges=function(){var e,t=[],i=0;for(e in this._ranges)t[i]=this._ranges[e],i++;return t},t.prototype.copyAnimationRange=function(t,i,r){if(void 0===r&&(r=!1),this._ranges[i]||!t.getAnimationRange(i))return!1;var n,o,s=!0,a=this._getHighestAnimationFrame()+1,h={},c=t.bones;for(o=0,n=c.length;o<n;o++)h[c[o].name]=c[o];this.bones.length!==c.length&&(e.Tools.Warn("copyAnimationRange: this rig has "+this.bones.length+" bones, while source as "+c.length),s=!1);var l=r&&this.dimensionsAtRest&&t.dimensionsAtRest?this.dimensionsAtRest.divide(t.dimensionsAtRest):null;for(o=0,n=this.bones.length;o<n;o++){var u=this.bones[o].name,d=h[u];d?s=s&&this.bones[o].copyAnimationRange(d,i,a,r,l):(e.Tools.Warn("copyAnimationRange: not same rig, missing source bone "+u),s=!1)}var f=t.getAnimationRange(i);return this._ranges[i]=new e.AnimationRange(i,f.from+a,f.to+a),s},t.prototype.returnToRest=function(){for(var e=0;e<this.bones.length;e++)this.bones[e].returnToRest()},t.prototype._getHighestAnimationFrame=function(){for(var e=0,t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){var r=this.bones[t].animations[0].getHighestFrame();e<r&&(e=r)}return e},t.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},t.prototype._markAsDirty=function(){this._isDirty=!0},t.prototype._registerMeshWithPoseMatrix=function(e){this._meshesWithPoseMatrix.push(e)},t.prototype._unregisterMeshWithPoseMatrix=function(e){var t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){for(var i=0;i<this.bones.length;i++){var r=this.bones[i],n=r.getParent();n?r.getLocalMatrix().multiplyToRef(n.getWorldMatrix(),r.getWorldMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getWorldMatrix()):r.getWorldMatrix().copyFrom(r.getLocalMatrix()),r.getInvertedAbsoluteTransform().multiplyToArray(r.getWorldMatrix(),e,16*i)}this._identity.copyToArray(e,16*this.bones.length)},t.prototype.prepare=function(){if(this._isDirty){if(this.needInitialSkinMatrix)for(var t=0;t<this._meshesWithPoseMatrix.length;t++){var i=this._meshesWithPoseMatrix[t];i._bonesTransformMatrices&&i._bonesTransformMatrices.length===16*(this.bones.length+1)||(i._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)));for(var r=i.getPoseMatrix(),n=0;n<this.bones.length;n++){var o=this.bones[n];if(!o.getParent()){var s=o.getBaseMatrix();s.multiplyToRef(r,e.Tmp.Matrix[0]),o._updateDifferenceMatrix(e.Tmp.Matrix[0])}}this._computeTransformMatrices(i._bonesTransformMatrices,r)}else this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1))),this._computeTransformMatrices(this._transformMatrices,null);this._isDirty=!1,this._scene._activeBones.addCount(this.bones.length,!1)}},t.prototype.getAnimatables=function(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(var e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables},t.prototype.clone=function(i,r){var n=new t(i,r||i,this._scene);n.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var o=0;o<this.bones.length;o++){var s=this.bones[o],a=null;if(s.getParent()){var h=this.bones.indexOf(s.getParent());a=n.bones[h]}var c=new e.Bone(s.name,n,a,s.getBaseMatrix().clone(),s.getRestPose().clone());e.Tools.DeepCopy(s.animations,c.animations)}if(this._ranges){n._ranges={};for(var l in this._ranges)n._ranges[l]=this._ranges[l].clone()}return this._isDirty=!0,n},t.prototype.enableBlending=function(e){void 0===e&&(e=.01),this.bones.forEach((function(t){t.animations.forEach((function(t){t.enableBlending=!0,t.blendingSpeed=e}))}))},t.prototype.dispose=function(){this._meshesWithPoseMatrix=[],this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this)},t.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,e.dimensionsAtRest=this.dimensionsAtRest,e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var t=0;t<this.bones.length;t++){var i=this.bones[t],r={parentBoneIndex:i.getParent()?this.bones.indexOf(i.getParent()):-1,name:i.name,matrix:i.getLocalMatrix().toArray(),rest:i.getRestPose().toArray()};e.bones.push(r),i.length&&(r.length=i.length),i.animations&&i.animations.length>0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(var n in this._ranges){var o={};o.name=n,o.from=this._ranges[n].from,o.to=this._ranges[n].to,e.ranges.push(o)}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o<i.bones.length;o++){var s=i.bones[o],a=null;s.parentBoneIndex>-1&&(a=n.bones[s.parentBoneIndex]);var h=s.rest?e.Matrix.FromArray(s.rest):null,c=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),h);s.length&&(c.length=s.length),s.animation&&c.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o<i.ranges.length;o++){var l=i.ranges[o];n.createAnimationRange(l.name,l.from,l.to)}return n},t.prototype.computeAbsoluteTransforms=function(e){void 0===e&&(e=!1);var t=this._scene.getRenderId();(this._lastAbsoluteTransformsUpdateId!=t||e)&&(this.bones[0].computeAbsoluteTransforms(),this._lastAbsoluteTransformsUpdateId=t)},t.prototype.getPoseMatrix=function(){var e;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t})();e.Skeleton=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,h,c,l,u){void 0===a&&(a=e.Texture.NEAREST_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),this.name=t,this.width=-1,this.height=-1,this.enablePixelPerfectMode=!1,this._reusable=!1,this._textures=new e.SmartArray(2),this._currentRenderTextureInd=0,this._scaleRatio=new e.Vector2(1,1),this.onActivateObservable=new e.Observable,this.onSizeChangedObservable=new e.Observable,this.onApplyObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,null!=s?(this._camera=s,this._scene=s.getScene(),s.attachPostProcess(this),this._engine=this._scene.getEngine()):this._engine=h,this._options=o,this.renderTargetSamplingMode=a?a:e.Texture.NEAREST_SAMPLINGMODE,this._reusable=c||!1,this._textureType=u,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=i,this._parameters=r||[],this._parameters.push("scale"),this.updateEffect(l)}return Object.defineProperty(t.prototype,"onActivate",{set:function(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),this._onActivateObserver=this.onActivateObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onSizeChanged",{set:function(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onApply",{set:function(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.updateEffect=function(e){this._effect=this._engine.createEffect({vertex:"postprocess",fragment:this._fragmentUrl},["position"],this._parameters,this._samplers,void 0!==e?e:"")},t.prototype.isReusable=function(){return this._reusable},t.prototype.markTextureDirty=function(){this.width=-1},t.prototype.activate=function(t,i){t=t||this._camera;var r=t.getScene(),n=t.getEngine().getCaps().maxTextureSize,o=(i?i._width:this._engine.getRenderingCanvas().width)*this._options|0,s=(i?i._height:this._engine.getRenderingCanvas().height)*this._options|0,a=this._options.width||o,h=this._options.height||s;if(this.renderTargetSamplingMode!==e.Texture.NEAREST_SAMPLINGMODE&&(this._options.width||(a=e.Tools.GetExponentOfTwo(a,n)),this._options.height||(h=e.Tools.GetExponentOfTwo(h,n))),this.width!==a||this.height!==h){if(this._textures.length>0){for(var c=0;c<this._textures.length;c++)this._engine._releaseTexture(this._textures.data[c]);this._textures.reset()}this.width=a,this.height=h;var l={width:this.width,height:this.height},u={generateMipMaps:!1,generateDepthBuffer:0===t._postProcesses.indexOf(this),generateStencilBuffer:0===t._postProcesses.indexOf(this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType};this._textures.push(this._engine.createRenderTargetTexture(l,u)),this._reusable&&this._textures.push(this._engine.createRenderTargetTexture(l,u)),this.onSizeChangedObservable.notifyObservers(this)}this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/a,s/h),this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd],0,o,s)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd])),this.onActivateObservable.notifyObservers(t),this.clearColor?this._engine.clear(this.clearColor,!0,!0,!0):this._engine.clear(r.clearColor,r.autoClear||r.forceWireframe,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2)},Object.defineProperty(t.prototype,"isSupported",{get:function(){return this._effect.isSupported},enumerable:!0,configurable:!0}),t.prototype.apply=function(){return this._effect.isReady()?(this._engine.enableEffect(this._effect),this._engine.setState(!1),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._effect._bindTexture("textureSampler",this._textures.data[this._currentRenderTextureInd]),this._effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effect),this._effect):null},t.prototype.dispose=function(e){if(e=e||this._camera,this._textures.length>0){for(var t=0;t<this._textures.length;t++)this._engine._releaseTexture(this._textures.data[t]);this._textures.reset()}if(e){e.detachPostProcess(this);var i=e._postProcesses.indexOf(this);0===i&&e._postProcesses.length>0&&this._camera._postProcesses[0].markTextureDirty(),this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,(!1),(!1),2);var i=[];i.push(0),i.push(1),i.push(2),i.push(0),i.push(2),i.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(i)}},t.prototype._prepareFrame=function(e){var t=this._scene.activeCamera._postProcesses;return!(0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(this._scene.activeCamera,e),!0)},t.prototype.directRender=function(e,t){for(var i=this._scene.getEngine(),r=0;r<e.length;r++){r<e.length-1?e[r+1].activate(this._scene.activeCamera,t):t?i.bindFramebuffer(t):i.restoreDefaultFramebuffer();var n=e[r],o=n.apply();o&&(n.onBeforeRenderObservable.notifyObservers(o),this._prepareBuffers(),i.bindBuffers(this._vertexBuffers,this._indexBuffer,o),i.draw(!0,0,6),n.onAfterRenderObservable.notifyObservers(o))}i.setDepthBuffer(!0),i.setDepthWrite(!0)},t.prototype._finalizeFrame=function(e,t,i,r){if(r=r||this._scene.activeCamera._postProcesses,0!==r.length&&this._scene.postProcessesEnabled){for(var n=this._scene.getEngine(),o=0,s=r.length;o<s&&(o<s-1?r[o+1].activate(this._scene.activeCamera,t):t?n.bindFramebuffer(t,i):n.restoreDefaultFramebuffer(),!e);o++){var a=r[o],h=a.apply();h&&(a.onBeforeRenderObservable.notifyObservers(h),this._prepareBuffers(),n.bindBuffers(this._vertexBuffers,this._indexBuffer,h),n.draw(!0,0,6),a.onAfterRenderObservable.notifyObservers(h))}n.setDepthBuffer(!0),n.setDepthWrite(!0)}},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)},t})();e.PostProcessManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"pass",null,null,i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.PassPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}return Object.defineProperty(e.prototype,"physicsJoint",{get:function(){return this._physicsJoint},set:function(e){this._physicsJoint,this._physicsJoint=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"physicsPlugin",{set:function(e){this._physicsPlugin=e},enumerable:!0,configurable:!0}),e.prototype.executeNativeFunction=function(e){e(this._physicsPlugin.world,this._physicsJoint)},e.DistanceJoint=0,e.HingeJoint=1,e.BallAndSocketJoint=2,e.WheelJoint=3,e.SliderJoint=4,e.PrismaticJoint=5,e.UniversalJoint=6,e.Hinge2Joint=e.WheelJoint,e.PointToPointJoint=8,e.SpringJoint=9,e.LockJoint=10,e})();e.PhysicsJoint=t;var i=(function(e){function i(i){e.call(this,t.DistanceJoint,i)}return __extends(i,e),i.prototype.updateDistance=function(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)},i})(t);e.DistanceJoint=i;var r=(function(e){function t(t,i){e.call(this,t,i)}return __extends(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t})(t);e.MotorEnabledJoint=r;var n=(function(e){function i(i){e.call(this,t.HingeJoint,i)}return __extends(i,e),i.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e,t)},i.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},i})(r);e.HingeJoint=n;var o=(function(e){function i(i){e.call(this,t.Hinge2Joint,i)}return __extends(i,e),i.prototype.setMotor=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setMotor(this,e,t,i)},i.prototype.setLimit=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setLimit(this,e,t,i)},i})(r);e.Hinge2Joint=o})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){var o=this;return void 0===r&&(r={mass:0}),this.object=t,this.type=i,this._options=r,this._scene=n,this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=e.Vector3.Zero(),this._tmpPositionWithDelta=e.Vector3.Zero(),this._tmpRotationWithDelta=new e.Quaternion,this.beforeStep=function(){o.object.position.subtractToRef(o._deltaPosition,o._tmpPositionWithDelta),o._deltaRotationConjugated?o.object.rotationQuaternion.multiplyToRef(o._deltaRotationConjugated,o._tmpRotationWithDelta):o._tmpRotationWithDelta.copyFrom(o.object.rotationQuaternion),o._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(o,o._tmpPositionWithDelta,o._tmpRotationWithDelta),o._onBeforePhysicsStepCallbacks.forEach((function(e){e(o)}))},this.afterStep=function(){o._onAfterPhysicsStepCallbacks.forEach((function(e){e(o)})),o._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(o),o.object.position.addInPlace(o._deltaPosition),o._deltaRotation&&o.object.rotationQuaternion.multiplyInPlace(o._deltaRotation)},this.onCollide=function(e){if(o._onPhysicsCollideCallbacks.length){var t=o._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&o._onPhysicsCollideCallbacks.filter((function(e){return e.otherImpostors.indexOf(t)!==-1})).forEach((function(e){
e.callback(o,t)}))}},this.object?(!this._scene&&t.getScene&&(this._scene=t.getScene()),this._physicsEngine=this._scene.getPhysicsEngine(),void(this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new e.Quaternion),this._options.mass=void 0===r.mass?0:r.mass,this._options.friction=void 0===r.friction?.2:r.friction,this._options.restitution=void 0===r.restitution?.2:r.restitution,this._joints=[],this.object.parent||this._init()):e.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):void e.Tools.Error("No object was provided. A physics object is obligatory")}return t.prototype._init=function(){this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this.parent||this._physicsEngine.addImpostor(this)},t.prototype._getPhysicsParent=function(){if(this.object.parent instanceof e.AbstractMesh){var t=this.object.parent;return t.physicsImpostor}},t.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},t.prototype.setScalingUpdated=function(e){this.forceUpdate()},t.prototype.forceUpdate=function(){this._init(),this.parent&&this.parent.forceUpdate()},Object.defineProperty(t.prototype,"physicsBody",{get:function(){return this._parent?this._parent.physicsBody:this._physicsBody},set:function(e){this._physicsBody&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},set:function(e){this._parent=e},enumerable:!0,configurable:!0}),t.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},t.prototype.getObjectExtendSize=function(){return this.object.getBoundingInfo?(this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling)):t.DEFAULT_OBJECT_SIZE},t.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.center:this.object.position},t.prototype.getParam=function(e){return this._options[e]},t.prototype.setParam=function(e,t){this._options[e]=t,this._bodyUpdateRequired=!0},t.prototype.setMass=function(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)},t.prototype.getLinearVelocity=function(){return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this)},t.prototype.setLinearVelocity=function(e){this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)},t.prototype.getAngularVelocity=function(){return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this)},t.prototype.setAngularVelocity=function(e){this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)},t.prototype.executeNativeFunction=function(e){e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},t.prototype.registerBeforePhysicsStep=function(e){this._onBeforePhysicsStepCallbacks.push(e)},t.prototype.unregisterBeforePhysicsStep=function(t){var i=this._onBeforePhysicsStepCallbacks.indexOf(t);i>-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=this._onPhysicsCollideCallbacks.indexOf({callback:i,otherImpostors:r});n>-1?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.applyForce=function(e,t){this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t)},t.prototype.applyImpulse=function(e,t){this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t)},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);this.addJoint(t,n)},t.prototype.addJoint=function(e,t){this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine.addJoint(this,e,t)},t.prototype.sleep=function(){this._physicsEngine.getPhysicsPlugin().sleepBody(this)},t.prototype.wakeUp=function(){this._physicsEngine.getPhysicsPlugin().wakeUpBody(this)},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate())},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,(-9.807),0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t]},t.prototype.getImpostorWithPhysicsBody=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t]},t.NoImpostor=e.PhysicsImpostor.NoImpostor,t.SphereImpostor=e.PhysicsImpostor.SphereImpostor,t.BoxImpostor=e.PhysicsImpostor.BoxImpostor,t.PlaneImpostor=e.PhysicsImpostor.PlaneImpostor,t.MeshImpostor=e.PhysicsImpostor.MeshImpostor,t.CylinderImpostor=e.PhysicsImpostor.CylinderImpostor,t.HeightmapImpostor=e.PhysicsImpostor.HeightmapImpostor,t.CapsuleImpostor=-1,t.ConeImpostor=-1,t.ConvexHullImpostor=-1,t.Epsilon=.001,t})();e.PhysicsEngine=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.prototype.set=function(t,i){switch(i){case e.VertexBuffer.PositionKind:this.positions=t;break;case e.VertexBuffer.NormalKind:this.normals=t;break;case e.VertexBuffer.UVKind:this.uvs=t;break;case e.VertexBuffer.UV2Kind:this.uvs2=t;break;case e.VertexBuffer.UV3Kind:this.uvs3=t;break;case e.VertexBuffer.UV4Kind:this.uvs4=t;break;case e.VertexBuffer.UV5Kind:this.uvs5=t;break;case e.VertexBuffer.UV6Kind:this.uvs6=t;break;case e.VertexBuffer.ColorKind:this.colors=t;break;case e.VertexBuffer.MatricesIndicesKind:this.matricesIndices=t;break;case e.VertexBuffer.MatricesWeightsKind:this.matricesWeights=t;break;case e.VertexBuffer.MatricesIndicesExtraKind:this.matricesIndicesExtra=t;break;case e.VertexBuffer.MatricesWeightsExtraKind:this.matricesWeightsExtra=t}},t.prototype.applyToMesh=function(e,t){this._applyTo(e,t)},t.prototype.applyToGeometry=function(e,t){this._applyTo(e,t)},t.prototype.updateMesh=function(e,t,i){this._update(e)},t.prototype.updateGeometry=function(e,t,i){this._update(e)},t.prototype._applyTo=function(t,i){this.positions&&t.setVerticesData(e.VertexBuffer.PositionKind,this.positions,i),this.normals&&t.setVerticesData(e.VertexBuffer.NormalKind,this.normals,i),this.uvs&&t.setVerticesData(e.VertexBuffer.UVKind,this.uvs,i),this.uvs2&&t.setVerticesData(e.VertexBuffer.UV2Kind,this.uvs2,i),this.uvs3&&t.setVerticesData(e.VertexBuffer.UV3Kind,this.uvs3,i),this.uvs4&&t.setVerticesData(e.VertexBuffer.UV4Kind,this.uvs4,i),this.uvs5&&t.setVerticesData(e.VertexBuffer.UV5Kind,this.uvs5,i),this.uvs6&&t.setVerticesData(e.VertexBuffer.UV6Kind,this.uvs6,i),this.colors&&t.setVerticesData(e.VertexBuffer.ColorKind,this.colors,i),this.matricesIndices&&t.setVerticesData(e.VertexBuffer.MatricesIndicesKind,this.matricesIndices,i),this.matricesWeights&&t.setVerticesData(e.VertexBuffer.MatricesWeightsKind,this.matricesWeights,i),this.matricesIndicesExtra&&t.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,i),this.matricesWeightsExtra&&t.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,i),this.indices&&t.setIndices(this.indices)},t.prototype._update=function(t,i,r){this.positions&&t.updateVerticesData(e.VertexBuffer.PositionKind,this.positions,i,r),this.normals&&t.updateVerticesData(e.VertexBuffer.NormalKind,this.normals,i,r),this.uvs&&t.updateVerticesData(e.VertexBuffer.UVKind,this.uvs,i,r),this.uvs2&&t.updateVerticesData(e.VertexBuffer.UV2Kind,this.uvs2,i,r),this.uvs3&&t.updateVerticesData(e.VertexBuffer.UV3Kind,this.uvs3,i,r),this.uvs4&&t.updateVerticesData(e.VertexBuffer.UV4Kind,this.uvs4,i,r),this.uvs5&&t.updateVerticesData(e.VertexBuffer.UV5Kind,this.uvs5,i,r),this.uvs6&&t.updateVerticesData(e.VertexBuffer.UV6Kind,this.uvs6,i,r),this.colors&&t.updateVerticesData(e.VertexBuffer.ColorKind,this.colors,i,r),this.matricesIndices&&t.updateVerticesData(e.VertexBuffer.MatricesIndicesKind,this.matricesIndices,i,r),this.matricesWeights&&t.updateVerticesData(e.VertexBuffer.MatricesWeightsKind,this.matricesWeights,i,r),this.matricesIndicesExtra&&t.updateVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,i,r),this.matricesWeightsExtra&&t.updateVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,i,r),this.indices&&t.setIndices(this.indices)},t.prototype.transform=function(t){var i,r=e.Vector3.Zero();if(this.positions){var n=e.Vector3.Zero();for(i=0;i<this.positions.length;i+=3)e.Vector3.FromArrayToRef(this.positions,i,n),e.Vector3.TransformCoordinatesToRef(n,t,r),this.positions[i]=r.x,this.positions[i+1]=r.y,this.positions[i+2]=r.z}if(this.normals){var o=e.Vector3.Zero();for(i=0;i<this.normals.length;i+=3)e.Vector3.FromArrayToRef(this.normals,i,o),e.Vector3.TransformNormalToRef(o,t,r),this.normals[i]=r.x,this.normals[i+1]=r.y,this.normals[i+2]=r.z}},t.prototype.merge=function(e){if(e.indices){this.indices||(this.indices=[]);for(var t=this.positions?this.positions.length/3:0,i=0;i<e.indices.length;i++)this.indices.push(e.indices[i]+t)}this.positions=this._mergeElement(this.positions,e.positions),this.normals=this._mergeElement(this.normals,e.normals),this.uvs=this._mergeElement(this.uvs,e.uvs),this.uvs2=this._mergeElement(this.uvs2,e.uvs2),this.uvs3=this._mergeElement(this.uvs3,e.uvs3),this.uvs4=this._mergeElement(this.uvs4,e.uvs4),this.uvs5=this._mergeElement(this.uvs5,e.uvs5),this.uvs6=this._mergeElement(this.uvs6,e.uvs6),this.colors=this._mergeElement(this.colors,e.colors),this.matricesIndices=this._mergeElement(this.matricesIndices,e.matricesIndices),this.matricesWeights=this._mergeElement(this.matricesWeights,e.matricesWeights),this.matricesIndicesExtra=this._mergeElement(this.matricesIndicesExtra,e.matricesIndicesExtra),this.matricesWeightsExtra=this._mergeElement(this.matricesWeightsExtra,e.matricesWeightsExtra)},t.prototype._mergeElement=function(e,t){if(!t)return e;if(!e)return t;var i=t.length+e.length,r=e instanceof Float32Array,n=t instanceof Float32Array;if(r){var o=new Float32Array(i);return o.set(e),o.set(t,e.length),o}if(n){for(var s=e.slice(0),a=0,i=t.length;a<i;a++)s.push(t[a]);return s}return e.concat(t)},t.prototype.serialize=function(){var e=this.serialize();return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e},t.ExtractFromMesh=function(e,i){return t._ExtractFrom(e,i)},t.ExtractFromGeometry=function(e,i){return t._ExtractFrom(e,i)},t._ExtractFrom=function(i,r){var n=new t;return i.isVerticesDataPresent(e.VertexBuffer.PositionKind)&&(n.positions=i.getVerticesData(e.VertexBuffer.PositionKind,r)),i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.normals=i.getVerticesData(e.VertexBuffer.NormalKind,r)),i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.uvs=i.getVerticesData(e.VertexBuffer.UVKind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(n.uvs2=i.getVerticesData(e.VertexBuffer.UV2Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV3Kind)&&(n.uvs3=i.getVerticesData(e.VertexBuffer.UV3Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV4Kind)&&(n.uvs4=i.getVerticesData(e.VertexBuffer.UV4Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV5Kind)&&(n.uvs5=i.getVerticesData(e.VertexBuffer.UV5Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV6Kind)&&(n.uvs6=i.getVerticesData(e.VertexBuffer.UV6Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(n.colors=i.getVerticesData(e.VertexBuffer.ColorKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&(n.matricesIndices=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)&&(n.matricesWeights=i.getVerticesData(e.VertexBuffer.MatricesWeightsKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=i.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,r)),n.indices=i.getIndices(r),n},t.CreateRibbon=function(i){var r=i.pathArray,n=i.closeArray||!1,o=i.closePath||!1,s=i.invertUV||!1,a=Math.floor(r[0].length/2),h=i.offset||a;h=h>a?a:Math.floor(h);var c,l,u,d,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=[],m=[],_=[],g=[],v=[],y=[],x=[],b=[],T=[],A=[];if(r.length<2){var E=[],P=[];for(u=0;u<r[0].length-h;u++)E.push(r[0][u]),P.push(r[0][u+h]);r=[E,P]}var M,S,C=0,R=o?1:0;c=r[0].length;var O,D;for(l=0;l<r.length;l++){for(x[l]=0,v[l]=[0],M=r[l],S=M.length,c=c<S?c:S,d=0;d<S;)p.push(M[d].x,M[d].y,M[d].z),d>0&&(O=M[d].subtract(M[d-1]).length(),D=O+x[l],v[l].push(D),x[l]=D),d++;o&&(d--,p.push(M[0].x,M[0].y,M[0].z),O=M[d].subtract(M[0]).length(),D=O+x[l],v[l].push(D),x[l]=D),T[l]=S+R,A[l]=C,C+=S+R}var I,w,L,B;for(u=0;u<c+R;u++){for(b[u]=0,y[u]=[0],l=0;l<r.length-1;l++)I=r[l],w=r[l+1],u===c?(L=I[0],B=w[0]):(L=I[u],B=w[u]),O=B.subtract(L).length(),D=O+b[u],y[u].push(D),b[u]=D;n&&(I=r[l],w=r[0],u===c&&(B=w[0]),O=B.subtract(L).length(),D=O+b[u],b[u]=D)}var F,V;for(l=0;l<r.length;l++)for(u=0;u<c+R;u++)F=v[l][u]/x[l],V=y[u][l]/b[u],s?g.push(V,F):g.push(F,V);l=0;for(var N=0,z=T[l]-1,U=T[l+1]-1,k=z<U?z:U,G=A[1]-A[0],W=n?T.length:T.length-1;N<=k&&l<W;)m.push(N,N+G,N+1),m.push(N+G+1,N+1,N+G),N+=1,N===k&&(l++,l===T.length-1?(G=A[0]-A[l],z=T[l]-1,U=T[0]-1):(G=A[l+1]-A[l],z=T[l]-1,U=T[l+1]-1),N=A[l],k=z<U?z+N:U+N);if(t.ComputeNormals(p,m,_),o){var Y=0,H=0;for(l=0;l<r.length;l++)Y=3*A[l],H=l+1<r.length?3*(A[l+1]-1):_.length-3,_[Y]=.5*(_[Y]+_[H]),_[Y+1]=.5*(_[Y+1]+_[H+1]),_[Y+2]=.5*(_[Y+2]+_[H+2]),_[H]=_[Y],_[H+1]=_[Y+1],_[H+2]=_[Y+2]}t._ComputeSides(f,p,m,_,g);var j=new t;return j.indices=m,j.positions=p,j.normals=_,j.uvs=g,o&&(j._idx=A),j},t.CreateBox=function(i){for(var r=[new e.Vector3(0,0,1),new e.Vector3(0,0,(-1)),new e.Vector3(1,0,0),new e.Vector3((-1),0,0),new e.Vector3(0,1,0),new e.Vector3(0,(-1),0)],n=[],o=[],s=[],a=[],h=i.width||i.size||1,c=i.height||i.size||1,l=i.depth||i.size||1,u=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,d=i.faceUV||new Array(6),f=i.faceColors,p=[],m=0;m<6;m++)void 0===d[m]&&(d[m]=new e.Vector4(0,0,1,1)),f&&void 0===f[m]&&(f[m]=new e.Color4(1,1,1,1));for(var _=new e.Vector3(h/2,c/2,l/2),g=0;g<r.length;g++){var v=r[g],y=new e.Vector3(v.y,v.z,v.x),x=e.Vector3.Cross(v,y),b=o.length/3;n.push(b),n.push(b+1),n.push(b+2),n.push(b),n.push(b+2),n.push(b+3);var T=v.subtract(y).subtract(x).multiply(_);o.push(T.x,T.y,T.z),s.push(v.x,v.y,v.z),a.push(d[g].z,d[g].w),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a),T=v.subtract(y).add(x).multiply(_),o.push(T.x,T.y,T.z),s.push(v.x,v.y,v.z),a.push(d[g].x,d[g].w),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a),T=v.add(y).add(x).multiply(_),o.push(T.x,T.y,T.z),s.push(v.x,v.y,v.z),a.push(d[g].x,d[g].y),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a),T=v.add(y).subtract(x).multiply(_),o.push(T.x,T.y,T.z),s.push(v.x,v.y,v.z),a.push(d[g].z,d[g].y),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a)}t._ComputeSides(u,o,n,s,a);var A=new t;if(A.indices=n,A.positions=o,A.normals=s,A.uvs=a,f){var E=u===e.Mesh.DOUBLESIDE?p.concat(p):p;A.colors=E}return A},t.CreateSphere=function(i){for(var r=i.segments||32,n=i.diameterX||i.diameter||1,o=i.diameterY||i.diameter||1,s=i.diameterZ||i.diameter||1,a=i.arc<=0||i.arc>1?1:i.arc||1,h=i.slice<=0?1:i.slice||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,l=new e.Vector3(n/2,o/2,s/2),u=2+r,d=2*u,f=[],p=[],m=[],_=[],g=0;g<=u;g++){for(var v=g/u,y=v*Math.PI*h,x=0;x<=d;x++){var b=x/d,T=b*Math.PI*2*a,A=e.Matrix.RotationZ(-y),E=e.Matrix.RotationY(T),P=e.Vector3.TransformCoordinates(e.Vector3.Up(),A),M=e.Vector3.TransformCoordinates(P,E),S=M.multiply(l),C=M.divide(l).normalize();p.push(S.x,S.y,S.z),m.push(C.x,C.y,C.z),_.push(b,v)}if(g>0)for(var R=p.length/3,O=R-2*(d+1);O+d+2<R;O++)f.push(O),f.push(O+1),f.push(O+d+1),f.push(O+d+1),f.push(O+1),f.push(O+d+2)}t._ComputeSides(c,p,f,m,_);var D=new t;return D.indices=f,D.positions=p,D.normals=m,D.uvs=_,D},t.CreateCylinder=function(i){var r,n=i.height||2,o=0===i.diameterTop?0:i.diameterTop||i.diameter||1,s=0===i.diameterBottom?0:i.diameterBottom||i.diameter||1,a=i.tessellation||24,h=i.subdivisions||1,c=i.hasRings,l=i.enclose,u=i.arc<=0||i.arc>1?1:i.arc||1,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,f=i.faceUV||new Array(3),p=i.faceColors,m=1!==u&&l?2:0,_=c?h:1,g=2+(1+m)*_;for(r=0;r<g;r++)p&&void 0===p[r]&&(p[r]=new e.Color4(1,1,1,1));for(r=0;r<g;r++)f&&void 0===f[r]&&(f[r]=new e.Vector4(0,0,1,1));var v,y,x,b,T,A,E=[],P=[],M=[],S=[],C=[],R=2*Math.PI*u/a,O=(s-o)/2/n,D=e.Vector3.Zero(),I=e.Vector3.Zero(),w=e.Vector3.Zero(),L=e.Vector3.Zero(),B=e.Vector3.Zero(),F=e.Axis.Y,V=1,N=1,z=0,U=0;for(b=0;b<=h;b++)for(y=b/h,x=(y*(o-s)+s)/2,V=c&&0!==b&&b!==h?2:1,A=0;A<V;A++){for(c&&(N+=A),l&&(N+=2*A),T=0;T<=a;T++)v=T*R,D.x=Math.cos(-v)*x,D.y=-n/2+y*n,D.z=Math.sin(-v)*x,0===o&&b===h?(I.x=M[M.length-3*(a+1)],I.y=M[M.length-3*(a+1)+1],I.z=M[M.length-3*(a+1)+2]):(I.x=D.x,I.z=D.z,I.y=Math.sqrt(I.x*I.x+I.z*I.z)*O,I.normalize()),0===T&&(w.copyFrom(D),L.copyFrom(I)),P.push(D.x,D.y,D.z),M.push(I.x,I.y,I.z),U=c?z!==N?f[N].y:f[N].w:f[N].y+(f[N].w-f[N].y)*y,S.push(f[N].x+(f[N].z-f[N].x)*T/a,U),p&&C.push(p[N].r,p[N].g,p[N].b,p[N].a);1!==u&&l&&(P.push(D.x,D.y,D.z),P.push(0,D.y,0),P.push(0,D.y,0),P.push(w.x,w.y,w.z),e.Vector3.CrossToRef(F,I,B),B.normalize(),M.push(B.x,B.y,B.z,B.x,B.y,B.z),e.Vector3.CrossToRef(L,F,B),B.normalize(),M.push(B.x,B.y,B.z,B.x,B.y,B.z),U=c?z!==N?f[N+1].y:f[N+1].w:f[N+1].y+(f[N+1].w-f[N+1].y)*y,S.push(f[N+1].x,U),S.push(f[N+1].z,U),U=c?z!==N?f[N+2].y:f[N+2].w:f[N+2].y+(f[N+2].w-f[N+2].y)*y,S.push(f[N+2].x,U),S.push(f[N+2].z,U),p&&(C.push(p[N+1].r,p[N+1].g,p[N+1].b,p[N+1].a),C.push(p[N+1].r,p[N+1].g,p[N+1].b,p[N+1].a),C.push(p[N+2].r,p[N+2].g,p[N+2].b,p[N+2].a),C.push(p[N+2].r,p[N+2].g,p[N+2].b,p[N+2].a))),z!==N&&(z=N)}var N,k=1!==u&&l?a+4:a;for(b=0,N=0;N<h;N++){for(T=0;T<a;T++){var G=b*(k+1)+T,W=(b+1)*(k+1)+T,Y=b*(k+1)+(T+1),H=(b+1)*(k+1)+(T+1);E.push(G,W,Y),E.push(H,Y,W)}1!==u&&l&&(E.push(G+2,W+2,Y+2),E.push(H+2,Y+2,W+2),E.push(G+4,W+4,Y+4),E.push(H+4,Y+4,W+4)),b=c?b+2:b+1}var j=function(t){var i=t?o/2:s/2;if(0!==i){var r,h,c,l,d=t?f[g-1]:f[0];p&&(l=t?p[g-1]:p[0]);var m=P.length/3,_=t?n/2:-n/2,v=new e.Vector3(0,_,0);P.push(v.x,v.y,v.z),M.push(0,t?1:-1,0),S.push(d.x+.5*(d.z-d.x),d.y+.5*(d.w-d.y)),p&&C.push(l.r,l.g,l.b,l.a);var y=new e.Vector2(.5,.5);for(c=0;c<=a;c++){r=2*Math.PI*c*u/a;var x=Math.cos(-r),b=Math.sin(-r);h=new e.Vector3(x*i,_,b*i);var T=new e.Vector2(x*y.x+.5,b*y.y+.5);P.push(h.x,h.y,h.z),M.push(0,t?1:-1,0),S.push(d.x+(d.z-d.x)*T.x,d.y+(d.w-d.y)*T.y),p&&C.push(l.r,l.g,l.b,l.a)}for(c=0;c<a;c++)t?(E.push(m),E.push(m+(c+2)),E.push(m+(c+1))):(E.push(m),E.push(m+(c+1)),E.push(m+(c+2)))}};j(!1),j(!0),t._ComputeSides(d,P,E,M,S);var X=new t;return X.indices=E,X.positions=P,X.normals=M,X.uvs=S,p&&(X.colors=C),X},t.CreateTorus=function(i){for(var r=[],n=[],o=[],s=[],a=i.diameter||1,h=i.thickness||.5,c=i.tessellation||16,l=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,u=c+1,d=0;d<=c;d++)for(var f=d/c,p=d*Math.PI*2/c-Math.PI/2,m=e.Matrix.Translation(a/2,0,0).multiply(e.Matrix.RotationY(p)),_=0;_<=c;_++){var g=1-_/c,v=_*Math.PI*2/c+Math.PI,y=Math.cos(v),x=Math.sin(v),b=new e.Vector3(y,x,0),T=b.scale(h/2),A=new e.Vector2(f,g);T=e.Vector3.TransformCoordinates(T,m),b=e.Vector3.TransformNormal(b,m),n.push(T.x,T.y,T.z),o.push(b.x,b.y,b.z),s.push(A.x,A.y);var E=(d+1)%u,P=(_+1)%u;r.push(d*u+_),r.push(d*u+P),r.push(E*u+_),r.push(d*u+P),r.push(E*u+P),r.push(E*u+_)}t._ComputeSides(l,n,r,o,s);var M=new t;return M.indices=r,M.positions=n,M.normals=o,M.uvs=s,M},t.CreateLineSystem=function(e){for(var i=[],r=[],n=e.lines,o=0,s=0;s<n.length;s++)for(var a=n[s],h=0;h<a.length;h++)r.push(a[h].x,a[h].y,a[h].z),h>0&&(i.push(o-1),i.push(o)),o++;var c=new t;return c.indices=i,c.positions=r,c},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,h=new Array,c=e.Vector3.Zero(),l=0,u=0,d=0,f=0,p=0,m=0,_=0;for(_=0;_<s.length-1;_++)s[_+1].subtractToRef(s[_],c),l+=c.length();for(d=l/o,f=r*d/(r+n),_=0;_<s.length-1;_++){s[_+1].subtractToRef(s[_],c),u=Math.floor(c.length()/d),c.normalize();for(var g=0;g<u;g++)p=d*g,a.push(s[_].x+p*c.x,s[_].y+p*c.y,s[_].z+p*c.z),a.push(s[_].x+(p+f)*c.x,s[_].y+(p+f)*c.y,s[_].z+(p+f)*c.z),h.push(m,m+1),m+=2}var v=new t;return v.positions=a,v.indices=h,v},t.CreateGround=function(i){var r,n,o=[],s=[],a=[],h=[],c=i.width||1,l=i.height||1,u=i.subdivisionsX||i.subdivisions||1,d=i.subdivisionsY||i.subdivisions||1;for(r=0;r<=d;r++)for(n=0;n<=u;n++){var f=new e.Vector3(n*c/u-c/2,0,(d-r)*l/d-l/2),p=new e.Vector3(0,1,0);s.push(f.x,f.y,f.z),a.push(p.x,p.y,p.z),h.push(n/u,1-r/u)}for(r=0;r<d;r++)for(n=0;n<u;n++)o.push(n+1+(r+1)*(u+1)),o.push(n+1+r*(u+1)),o.push(n+r*(u+1)),o.push(n+(r+1)*(u+1)),o.push(n+1+(r+1)*(u+1)),o.push(n+r*(u+1));var m=new t;return m.indices=o,m.positions=s,m.normals=a,m.uvs=h,m},t.CreateTiledGround=function(i){function r(t,i,r,s){var a=m.length/3,h=f.w+1;for(n=0;n<f.h;n++)for(o=0;o<f.w;o++){var c=[a+o+n*h,a+(o+1)+n*h,a+(o+1)+(n+1)*h,a+o+(n+1)*h];p.push(c[1]),p.push(c[2]),p.push(c[3]),p.push(c[0]),p.push(c[1]),p.push(c[3])}var l=e.Vector3.Zero(),u=new e.Vector3(0,1,0);for(n=0;n<=f.h;n++)for(l.z=n*(s-i)/f.h+i,o=0;o<=f.w;o++)l.x=o*(r-t)/f.w+t,l.y=0,m.push(l.x,l.y,l.z),_.push(u.x,u.y,u.z),g.push(o/f.w,n/f.h)}var n,o,s,a,h=i.xmin||-1,c=i.zmin||-1,l=i.xmax||1,u=i.zmax||1,d=i.subdivisions||{w:1,h:1},f=i.precision||{w:1,h:1},p=[],m=[],_=[],g=[];d.h=d.h<1?1:d.h,d.w=d.w<1?1:d.w,f.w=f.w<1?1:f.w,f.h=f.h<1?1:f.h;var v={w:(l-h)/d.w,h:(u-c)/d.h};for(s=0;s<d.h;s++)for(a=0;a<d.w;a++)r(h+a*v.w,c+s*v.h,h+(a+1)*v.w,c+(s+1)*v.h);var y=new t;return y.indices=p,y.positions=m,y.normals=_,y.uvs=g,y},t.CreateGroundFromHeightMap=function(i){var r,n,o=[],s=[],a=[],h=[];for(r=0;r<=i.subdivisions;r++)for(n=0;n<=i.subdivisions;n++){var c=new e.Vector3(n*i.width/i.subdivisions-i.width/2,0,(i.subdivisions-r)*i.height/i.subdivisions-i.height/2),l=(c.x+i.width/2)/i.width*(i.bufferWidth-1)|0,u=(1-(c.z+i.height/2)/i.height)*(i.bufferHeight-1)|0,d=4*(l+u*i.bufferWidth),f=i.buffer[d]/255,p=i.buffer[d+1]/255,m=i.buffer[d+2]/255,_=.3*f+.59*p+.11*m;c.y=i.minHeight+(i.maxHeight-i.minHeight)*_,s.push(c.x,c.y,c.z),a.push(0,0,0),h.push(n/i.subdivisions,1-r/i.subdivisions)}for(r=0;r<i.subdivisions;r++)for(n=0;n<i.subdivisions;n++)o.push(n+1+(r+1)*(i.subdivisions+1)),o.push(n+1+r*(i.subdivisions+1)),o.push(n+r*(i.subdivisions+1)),o.push(n+(r+1)*(i.subdivisions+1)),o.push(n+1+(r+1)*(i.subdivisions+1)),o.push(n+r*(i.subdivisions+1));t.ComputeNormals(s,o,a);var g=new t;return g.indices=o,g.positions=s,g.normals=a,g.uvs=h,g},t.CreatePlane=function(i){var r=[],n=[],o=[],s=[],a=i.width||i.size||1,h=i.height||i.size||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,l=a/2,u=h/2;n.push(-l,-u,0),o.push(0,0,-1),s.push(0,0),n.push(l,-u,0),o.push(0,0,-1),s.push(1,0),n.push(l,u,0),o.push(0,0,-1),s.push(1,1),n.push(-l,u,0),o.push(0,0,-1),s.push(0,1),r.push(0),r.push(1),r.push(2),r.push(0),r.push(2),r.push(3),t._ComputeSides(c,n,r,o,s);var d=new t;return d.indices=r,d.positions=n,d.normals=o,d.uvs=s,d},t.CreateDisc=function(i){var r=[],n=[],o=[],s=[],a=i.radius||.5,h=i.tessellation||64,c=i.arc<=0||i.arc>1?1:i.arc||1,l=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*c,d=u/h,f=0;f<u;f+=d){var p=Math.cos(f),m=Math.sin(f),_=(p+1)/2,g=(1-m)/2;r.push(a*p,a*m,0),s.push(_,g)}1===c&&(r.push(r[3],r[4],r[5]),s.push(s[2],s[3]));for(var v=r.length/3,y=1;y<v-1;y++)n.push(y+1,0,y);t.ComputeNormals(r,n,o),t._ComputeSides(l,r,n,o,s);var x=new t;return x.indices=n,x.positions=r,x.normals=o,x.uvs=s,x},t.CreateIcoSphere=function(i){var r,n=i.sideOrientation||e.Mesh.DEFAULTSIDE,o=i.radius||1,s=void 0===i.flat||i.flat,a=i.subdivisions||4,h=i.radiusX||o,c=i.radiusY||o,l=i.radiusZ||o,u=(1+Math.sqrt(5))/2,d=[-1,u,-0,1,u,0,-1,-u,0,1,-u,0,0,-1,-u,0,1,-u,0,-1,u,0,1,u,u,0,1,u,0,-1,-u,0,1,-u,0,-1],f=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],p=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],m=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=138/1024,g=239/1024,v=60/1024,y=26/1024,x=-40/1024,b=20/1024,T=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],A=[],E=[],P=[],M=[],S=0,C=new Array(3),R=new Array(3);for(r=0;r<3;r++)C[r]=e.Vector3.Zero(),R[r]=e.Vector2.Zero();for(var O=0;O<20;O++){for(r=0;r<3;r++){var D=f[3*O+r];C[r].copyFromFloats(d[3*p[D]],d[3*p[D]+1],d[3*p[D]+2]),C[r].normalize().scaleInPlace(o),R[r].copyFromFloats(m[2*D]*_+v+T[O]*x,m[2*D+1]*g+y+T[O]*b)}for(var I=function(t,i,r,n){var o=e.Vector3.Lerp(C[0],C[2],i/a),u=e.Vector3.Lerp(C[1],C[2],i/a),d=a===i?C[2]:e.Vector3.Lerp(o,u,t/(a-i));d.normalize();var f;if(s){var p=e.Vector3.Lerp(C[0],C[2],n/a),m=e.Vector3.Lerp(C[1],C[2],n/a);f=e.Vector3.Lerp(p,m,r/(a-n))}else f=new e.Vector3(d.x,d.y,d.z);f.x/=h,f.y/=c,f.z/=l,f.normalize();var _=e.Vector2.Lerp(R[0],R[2],i/a),g=e.Vector2.Lerp(R[1],R[2],i/a),v=a===i?R[2]:e.Vector2.Lerp(_,g,t/(a-i));E.push(d.x*h,d.y*c,d.z*l),P.push(f.x,f.y,f.z),M.push(v.x,v.y),A.push(S),S++},w=0;w<a;w++)for(var L=0;L+w<a;L++)I(L,w,L+1/3,w+1/3),I(L+1,w,L+1/3,w+1/3),I(L,w+1,L+1/3,w+1/3),L+w+1<a&&(I(L+1,w,L+2/3,w+2/3),I(L+1,w+1,L+2/3,w+2/3),I(L,w+1,L+2/3,w+2/3))}t._ComputeSides(n,E,A,P,M);var B=new t;return B.indices=A,B.positions=E,B.normals=P,B.uvs=M,B},t.CreatePolyhedron=function(i){var r=[];r[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},r[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},r[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},r[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},r[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},r[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},r[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],
face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},r[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},r[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},r[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},r[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},r[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},r[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},r[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},r[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};var n,o,s,a,h,c,l=i.type<0||i.type>=r.length?0:i.type||0,u=i.size,d=i.sizeX||u||1,f=i.sizeY||u||1,p=i.sizeZ||u||1,m=i.custom||r[l],_=m.face.length,g=i.faceUV||new Array(_),v=i.faceColors,y=void 0===i.flat||i.flat,x=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,b=[],T=[],A=[],E=[],P=[],M=0,S=0,C=[],R=0,O=0;if(y)for(O=0;O<_;O++)v&&void 0===v[O]&&(v[O]=new e.Color4(1,1,1,1)),g&&void 0===g[O]&&(g[O]=new e.Vector4(0,0,1,1));if(y)for(O=0;O<_;O++){var D=m.face[O].length;for(s=2*Math.PI/D,a=.5*Math.tan(s/2),h=.5,R=0;R<D;R++)b.push(m.vertex[m.face[O][R]][0]*d,m.vertex[m.face[O][R]][1]*f,m.vertex[m.face[O][R]][2]*p),C.push(M),M++,n=g[O].x+(g[O].z-g[O].x)*(.5+a),o=g[O].y+(g[O].w-g[O].y)*(h-.5),E.push(n,o),c=a*Math.cos(s)-h*Math.sin(s),h=a*Math.sin(s)+h*Math.cos(s),a=c,v&&P.push(v[O].r,v[O].g,v[O].b,v[O].a);for(R=0;R<D-2;R++)T.push(C[0+S],C[R+2+S],C[R+1+S]);S+=D}else{for(R=0;R<m.vertex.length;R++)b.push(m.vertex[R][0]*d,m.vertex[R][1]*f,m.vertex[R][2]*p),E.push(0,0);for(O=0;O<_;O++)for(R=0;R<m.face[O].length-2;R++)T.push(m.face[O][0],m.face[O][R+2],m.face[O][R+1])}t.ComputeNormals(b,T,A),t._ComputeSides(x,b,T,A,E);var I=new t;return I.positions=b,I.indices=T,I.normals=A,I.uvs=E,v&&y&&(I.colors=P),I},t.CreateTorusKnot=function(i){var r,n,o=[],s=[],a=[],h=[],c=i.radius||2,l=i.tube||.5,u=i.radialSegments||32,d=i.tubularSegments||32,f=i.p||2,p=i.q||3,m=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,_=function(t){var i=Math.cos(t),r=Math.sin(t),n=p/f*t,o=Math.cos(n),s=c*(2+o)*.5*i,a=c*(2+o)*r*.5,h=c*Math.sin(n)*.5;return new e.Vector3(s,a,h)};for(r=0;r<=u;r++){var g=r%u,v=g/u*2*f*Math.PI,y=_(v),x=_(v+.01),b=x.subtract(y),T=x.add(y),A=e.Vector3.Cross(b,T);for(T=e.Vector3.Cross(A,b),A.normalize(),T.normalize(),n=0;n<d;n++){var E=n%d,P=E/d*2*Math.PI,M=-l*Math.cos(P),S=l*Math.sin(P);s.push(y.x+M*T.x+S*A.x),s.push(y.y+M*T.y+S*A.y),s.push(y.z+M*T.z+S*A.z),h.push(r/u),h.push(n/d)}}for(r=0;r<u;r++)for(n=0;n<d;n++){var C=(n+1)%d,R=r*d+n,O=(r+1)*d+n,D=(r+1)*d+C,I=r*d+C;o.push(I),o.push(O),o.push(R),o.push(I),o.push(D),o.push(O)}t.ComputeNormals(s,o,a),t._ComputeSides(m,s,o,a,h);var w=new t;return w.indices=o,w.positions=s,w.normals=a,w.uvs=h,w},t.ComputeNormals=function(e,t,i){var r=0,n=0,o=0,s=0,a=0,h=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0,_=0;for(r=0;r<e.length;r++)i[r]=0;var g=t.length/3;for(r=0;r<g;r++)p=t[3*r],m=t[3*r+1],_=t[3*r+2],n=e[3*p]-e[3*m],o=e[3*p+1]-e[3*m+1],s=e[3*p+2]-e[3*m+2],a=e[3*_]-e[3*m],h=e[3*_+1]-e[3*m+1],c=e[3*_+2]-e[3*m+2],l=o*c-s*h,u=s*a-n*c,d=n*h-o*a,f=Math.sqrt(l*l+u*u+d*d),f=0===f?1:f,l/=f,u/=f,d/=f,i[3*p]+=l,i[3*p+1]+=u,i[3*p+2]+=d,i[3*m]+=l,i[3*m+1]+=u,i[3*m+2]+=d,i[3*_]+=l,i[3*_+1]+=u,i[3*_+2]+=d;for(r=0;r<i.length/3;r++)l=i[3*r],u=i[3*r+1],d=i[3*r+2],f=Math.sqrt(l*l+u*u+d*d),f=0===f?1:f,l/=f,u/=f,d/=f,i[3*r]=l,i[3*r+1]=u,i[3*r+2]=d},t._ComputeSides=function(t,i,r,n,o){var s,a,h=r.length,c=n.length;switch(t=t||e.Mesh.DEFAULTSIDE){case e.Mesh.FRONTSIDE:break;case e.Mesh.BACKSIDE:var l;for(s=0;s<h;s+=3)l=r[s],r[s]=r[s+2],r[s+2]=l;for(a=0;a<c;a++)n[a]=-n[a];break;case e.Mesh.DOUBLESIDE:for(var u=i.length,d=u/3,f=0;f<u;f++)i[u+f]=i[f];for(s=0;s<h;s+=3)r[s+h]=r[s+2]+d,r[s+1+h]=r[s+1]+d,r[s+2+h]=r[s]+d;for(a=0;a<c;a++)n[c+a]=-n[a];for(var p=o.length,m=0;m<p;m++)o[m+p]=o[m]}},t.ImportVertexData=function(i,r){var n=new t,o=i.positions;o&&n.set(o,e.VertexBuffer.PositionKind);var s=i.normals;s&&n.set(s,e.VertexBuffer.NormalKind);var a=i.uvs;a&&n.set(a,e.VertexBuffer.UVKind);var h=i.uv2s;h&&n.set(h,e.VertexBuffer.UV2Kind);var c=i.uv3s;c&&n.set(c,e.VertexBuffer.UV3Kind);var l=i.uv4s;l&&n.set(l,e.VertexBuffer.UV4Kind);var u=i.uv5s;u&&n.set(u,e.VertexBuffer.UV5Kind);var d=i.uv6s;d&&n.set(d,e.VertexBuffer.UV6Kind);var f=i.colors;f&&n.set(e.Color4.CheckColors4(f,o.length/3),e.VertexBuffer.ColorKind);var p=i.matricesIndices;p&&n.set(p,e.VertexBuffer.MatricesIndicesKind);var m=i.matricesWeights;m&&n.set(m,e.VertexBuffer.MatricesWeightsKind);var _=i.indices;_&&(n.indices=_),r.setAllVerticesData(n,i.updatable)},t})();e.VertexData=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){var r=i.split(" ");r.forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){i=i.trim(),""!==i&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.Internals.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i),"true"===t||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var h=0;h<a.length;++h){var c=e._SimplifyNegation(a[h].trim());if(r="true"!==c&&"false"!==c?"!"===c[0]?!i(c.substring(1)):i(c):"true"===c,!r){s="false";break}}if(r||"true"===s){r=!0;break}r="true"!==s&&"false"!==s?"!"===s[0]?!i(s.substring(1)):i(s):"true"===s}return r?"true":"false"},e._SimplifyNegation=function(e){return e=e.replace(/^[\s!]+/,(function(e){return e=e.replace(/[\s]/g,(function(){return""})),e.length%2?"!":""})),e=e.trim(),"!true"===e?e="false":"!false"===e&&(e="true"),e},e})();e.AndOrNotEvaluator=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s){this._enabled=!0,this._refCount=0,this._name=i,this._renderTexture=new e.RenderTargetTexture(i,r,t),this.setRenderList(n),this._renderTexture.onBeforeRenderObservable.add(o),this._renderTexture.onAfterRenderObservable.add(s),this._scene=t,this._renderList=n}return t.prototype._incRefCount=function(){return 0===this._refCount&&this._scene.customRenderTargets.push(this._renderTexture),++this._refCount},t.prototype._decRefCount=function(){return this._refCount--,this._refCount<=0&&this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture),1),this._refCount},t.prototype._update=function(){this.setRenderList(this._renderList)},t.prototype.setRenderList=function(e){this._renderTexture.renderList=e},t.prototype.getRenderTexture=function(){return this._renderTexture},t})();e.PostProcessRenderPass=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this._engine=e,this._name=t,this._singleInstance=r||!0,this._getPostProcess=i,this._cameras=[],this._indicesForCamera=[],this._postProcesses={},this._renderPasses={},this._renderEffectAsPasses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(!this._postProcesses[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype._update=function(){for(var e in this._renderPasses)this._renderPasses[e]._update()},t.prototype.addPass=function(e){this._renderPasses[e._name]=e,this._linkParameters()},t.prototype.removePass=function(e){delete this._renderPasses[e._name],this._linkParameters()},t.prototype.addRenderEffectAsPass=function(e){this._renderEffectAsPasses[e._name]=e,this._linkParameters()},t.prototype.getPass=function(e){for(var t in this._renderPasses)if(t===e)return this._renderPasses[e]},t.prototype.emptyPasses=function(){this._renderPasses={},this._linkParameters()},t.prototype._attachCameras=function(t){for(var i,r=e.Tools.MakeArray(t||this._cameras),n=0;n<r.length;n++){var o=r[n],s=o.name;i=this._singleInstance?0:s,this._postProcesses[i]=this._postProcesses[i]||this._getPostProcess();var a=o.attachPostProcess(this._postProcesses[i]);this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._indicesForCamera[s].push(a),this._cameras.indexOf(o)===-1&&(this._cameras[s]=o);for(var h in this._renderPasses)this._renderPasses[h]._incRefCount()}this._linkParameters()},t.prototype._detachCameras=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){var n=i[r],o=n.name;n.detachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o]);var s=this._cameras.indexOf(o);this._indicesForCamera.splice(s,1),this._cameras.splice(s,1);for(var a in this._renderPasses)this._renderPasses[a]._decRefCount()}},t.prototype._enable=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){for(var n=i[r],o=n.name,s=0;s<this._indicesForCamera[o].length;s++)void 0===n._postProcesses[this._indicesForCamera[o][s]]&&t[r].attachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o][s]);for(var a in this._renderPasses)this._renderPasses[a]._incRefCount()}},t.prototype._disable=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){var n=i[r],o=n.Name;n.detachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o]);for(var s in this._renderPasses)this._renderPasses[s]._decRefCount()}},t.prototype.getPostProcess=function(e){return this._singleInstance?this._postProcesses[0]:this._postProcesses[e.name]},t.prototype._linkParameters=function(){var e=this;for(var t in this._postProcesses)this.applyParameters&&this.applyParameters(this._postProcesses[t]),this._postProcesses[t].onBeforeRenderObservable.add((function(t){e._linkTextures(t)}))},t.prototype._linkTextures=function(e){for(var t in this._renderPasses)e.setTexture(t,this._renderPasses[t].getRenderTexture());for(var i in this._renderEffectAsPasses)e.setTextureFromPostProcess(i+"Sampler",this._renderEffectAsPasses[i].getPostProcess())},t})();e.PostProcessRenderEffect=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass={},this._cameras=[]}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._renderEffects)if(!this._renderEffects[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype.addEffect=function(e){this._renderEffects[e._name]=e},t.prototype._enableEffect=function(t,i){var r=this._renderEffects[t];r&&r._enable(e.Tools.MakeArray(i||this._cameras))},t.prototype._disableEffect=function(t,i){var r=this._renderEffects[t];r&&r._disable(e.Tools.MakeArray(i||this._cameras))},t.prototype._attachCameras=function(t,i){var r,n=e.Tools.MakeArray(t||this._cameras),o=[];for(r=0;r<n.length;r++){var s=n[r],a=s.name;this._cameras.indexOf(s)===-1?this._cameras[a]=s:i&&o.push(r)}for(r=0;r<o.length;r++)t.splice(o[r],1);for(var h in this._renderEffects)this._renderEffects[h]._attachCameras(n)},t.prototype._detachCameras=function(t){var i=e.Tools.MakeArray(t||this._cameras);for(var r in this._renderEffects)this._renderEffects[r]._detachCameras(i);for(var n=0;n<i.length;n++)this._cameras.splice(this._cameras.indexOf(i[n]),1)},t.prototype._enableDisplayOnlyPass=function(i,r){var n,o=this,s=e.Tools.MakeArray(r||this._cameras),a=null;for(n in this._renderEffects)if(a=this._renderEffects[n].getPass(i),null!=a)break;if(null!==a){for(n in this._renderEffects)this._renderEffects[n]._disable(s);a._name=t.PASS_SAMPLER_NAME;for(var h=0;h<s.length;h++){var c=s[h],l=c.name;this._renderEffectsForIsolatedPass[l]=this._renderEffectsForIsolatedPass[l]||new e.PostProcessRenderEffect(this._engine,t.PASS_EFFECT_NAME,function(){return new e.DisplayPassPostProcess(t.PASS_EFFECT_NAME,1,null,null,o._engine,(!0))}),this._renderEffectsForIsolatedPass[l].emptyPasses(),this._renderEffectsForIsolatedPass[l].addPass(a),this._renderEffectsForIsolatedPass[l]._attachCameras(c)}}},t.prototype._disableDisplayOnlyPass=function(i){for(var r=this,n=e.Tools.MakeArray(i||this._cameras),o=0;o<n.length;o++){var s=n[o],a=s.name;this._renderEffectsForIsolatedPass[a]=this._renderEffectsForIsolatedPass[a]||new e.PostProcessRenderEffect(this._engine,t.PASS_EFFECT_NAME,function(){return new e.DisplayPassPostProcess(t.PASS_EFFECT_NAME,1,null,null,r._engine,(!0))}),this._renderEffectsForIsolatedPass[a]._disable(s)}for(var h in this._renderEffects)this._renderEffects[h]._enable(n)},t.prototype._update=function(){for(var e in this._renderEffects)this._renderEffects[e]._update();for(var t=0;t<this._cameras.length;t++){var i=this._cameras[t].name;this._renderEffectsForIsolatedPass[i]&&this._renderEffectsForIsolatedPass[i]._update()}},t.prototype.dispose=function(){},t.PASS_EFFECT_NAME="passEffect",t.PASS_SAMPLER_NAME="passSampler",t})();e.PostProcessRenderPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.enableDisplayOnlyPassInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableDisplayOnlyPass(t,i)},e.prototype.disableDisplayOnlyPassInPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._disableDisplayOnlyPass(t)},e.prototype.update=function(){for(var e in this._renderPipelines){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e})();e.PostProcessRenderPipelineManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.frontColor=new e.Color3(1,1,1),this.backColor=new e.Color3(.1,.1,.1),this.showBackLines=!0,this.renderList=new e.SmartArray(32),this._vertexBuffers={},this._scene=t}return t.prototype._prepareRessources=function(){if(!this._colorShader){this._colorShader=new e.ShaderMaterial("colorShader",this._scene,"color",{attributes:[e.VertexBuffer.PositionKind],uniforms:["worldViewProjection","color"]});var t=this._scene.getEngine(),i=e.VertexData.CreateBox(1);this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(t,i.positions,e.VertexBuffer.PositionKind,(!1)),this._indexBuffer=t.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}},t.prototype.reset=function(){this.renderList.reset()},t.prototype.render=function(){if(0!==this.renderList.length&&(this._prepareRessources(),this._colorShader.isReady())){var t=this._scene.getEngine();t.setDepthWrite(!1),this._colorShader._preBind();for(var i=0;i<this.renderList.length;i++){var r=this.renderList.data[i],n=r.minimum,o=r.maximum,s=o.subtract(n),a=n.add(s.scale(.5)),h=e.Matrix.Scaling(s.x,s.y,s.z).multiply(e.Matrix.Translation(a.x,a.y,a.z)).multiply(r.getWorldMatrix());t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),this.showBackLines&&(t.setDepthFunctionToGreaterOrEqual(),this._scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.backColor.toColor4()),this._colorShader.bind(h),t.draw(!1,0,24)),t.setDepthFunctionToLess(),this._scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.frontColor.toColor4()),this._colorShader.bind(h),t.draw(!1,0,24)}this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0)}},t.prototype.dispose=function(){if(this._colorShader){this._colorShader.dispose();var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._scene.getEngine()._releaseBuffer(this._indexBuffer)}},t})();e.BoundingBoxRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual),t.call(this,e),this.propertyPath=n,this.value=o,this.operator=s,this._target=r,this._effectiveTarget=this._getEffectiveTarget(r,this.propertyPath),this._property=this._getProperty(this.propertyPath)}return __extends(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]<this.value;case i.IsEqual:case i.IsDifferent:var e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===i.IsEqual?e:!e}return!1},i.prototype.serialize=function(){return this._serialize({name:"ValueCondition",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)},{name:"operator",value:i.GetOperatorName(this.operator)}]})},i.GetOperatorName=function(e){switch(e){case i._IsEqual:return"IsEqual";case i._IsDifferent:return"IsDifferent";case i._IsGreater:return"IsGreater";case i._IsLesser:return"IsLesser";default:return""}},i._IsEqual=0,i._IsDifferent=1,i._IsGreater=2,i._IsLesser=3,i})(t);e.ValueCondition=i;var r=(function(e){function t(t,i){e.call(this,t),this.predicate=i}return __extends(t,e),t.prototype.isValid=function(){return this.predicate()},t})(t);e.PredicateCondition=r;var n=(function(t){function i(e,i,r){t.call(this,e),this.value=r,this._target=i}return __extends(i,t),i.prototype.isValid=function(){return this._target.state===this.value},i.prototype.serialize=function(){return this._serialize({name:"StateCondition",properties:[e.Action._GetTargetProperty(this._target),{name:"value",value:this.value}]})},i})(t);e.StateCondition=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this.triggerOptions=e,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):this.trigger=e,this._nextActiveAction=this,this._condition=t}return t.prototype._prepare=function(){},t.prototype.getTriggerParameter=function(){return this._triggerParameter},t.prototype._executeCurrent=function(e){if(this._nextActiveAction._condition){var t=this._nextActiveAction._condition,i=this._actionManager.getScene().getRenderId();if(t._evaluationId===i){if(!t._currentResult)return}else{if(t._evaluationId=i,!t.isValid())return void(t._currentResult=!1);t._currentResult=!0}}this._nextActiveAction.execute(e),this.skipToNextActiveAction()},t.prototype.execute=function(e){},t.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},t.prototype.then=function(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e},t.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},t.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},t.prototype.serialize=function(e){},t.prototype._serialize=function(e,t){var i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){var r=this._condition.serialize();return r.children.push(i),t&&t.children.push(r),r}return t&&t.children.push(i),i},t._SerializeValueAsString=function(t){return"number"==typeof t?t.toString():"boolean"==typeof t?t?"true":"false":t instanceof e.Vector2?t.x+", "+t.y:t instanceof e.Vector3?t.x+", "+t.y+", "+t.z:t instanceof e.Color3?t.r+", "+t.g+", "+t.b:t instanceof e.Color4?t.r+", "+t.g+", "+t.b+", "+t.a:t},t._GetTargetProperty=function(t){return{name:"target",targetType:t instanceof e.Mesh?"MeshProperties":t instanceof e.Light?"LightProperties":t instanceof e.Camera?"CameraProperties":"SceneProperties",value:t instanceof e.Scene?"Scene":t.name}},t})();e.Action=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i,r,n,o){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=n,this.additionalData=o}return e.CreateNew=function(t,i,r){var n=t.getScene();return new e(t,n.pointerX,n.pointerY,n.meshUnderPointer,i,r)},e.CreateNewFromSprite=function(t,i,r,n){return new e(t,i.pointerX,i.pointerY,i.meshUnderPointer,r,n)},e.CreateNewFromScene=function(t,i){return new e(null,t.pointerX,t.pointerY,t.meshUnderPointer,i)},e.CreateNewFromPrimitive=function(t,i,r,n){return new e(t,i.x,i.y,null,r,n)},e})();e.ActionEvent=t;var i=(function(){function t(e){this.actions=new Array,this.hoverCursor="",this._scene=e,e._actionManagers.push(this)}return Object.defineProperty(t,"NothingTrigger",{get:function(){return t._NothingTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickTrigger",{get:function(){return t._OnPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnLeftPickTrigger",{get:function(){return t._OnLeftPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnRightPickTrigger",{get:function(){return t._OnRightPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnCenterPickTrigger",{get:function(){return t._OnCenterPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickDownTrigger",{get:function(){return t._OnPickDownTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickUpTrigger",{get:function(){return t._OnPickUpTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickOutTrigger",{get:function(){return t._OnPickOutTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnLongPressTrigger",{get:function(){return t._OnLongPressTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPointerOverTrigger",{get:function(){return t._OnPointerOverTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPointerOutTrigger",{get:function(){return t._OnPointerOutTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnEveryFrameTrigger",{get:function(){return t._OnEveryFrameTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnIntersectionEnterTrigger",{get:function(){return t._OnIntersectionEnterTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnIntersectionExitTrigger",{get:function(){return t._OnIntersectionExitTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnKeyDownTrigger",{get:function(){return t._OnKeyDownTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnKeyUpTrigger",{get:function(){return t._OnKeyUpTrigger},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var e=this._scene._actionManagers.indexOf(this);e>-1&&this._scene._actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(i.trigger===e)return!0}return!1},Object.defineProperty(t.prototype,"hasPointerTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),i._actionManager=this,i._prepare(),i)},t.prototype.processTrigger=function(e,i){for(var r=0;r<this.actions.length;r++){var n=this.actions[r];if(n.trigger===e){if(e===t.OnKeyUpTrigger||e===t.OnKeyDownTrigger){var o=n.getTriggerParameter();if(o){var s=i.sourceEvent.charCode?i.sourceEvent.charCode:i.sourceEvent.keyCode,a=String.fromCharCode(s).toLowerCase();if(a!==o.toLowerCase())continue}}n._executeCurrent(i)}}},t.prototype._getEffectiveTarget=function(e,t){for(var i=t.split("."),r=0;r<i.length-1;r++)e=e[i[r]];return e},t.prototype._getProperty=function(e){var t=e.split(".");return t[t.length-1]},t.prototype.serialize=function(i){for(var r={children:[],name:i,type:3,properties:[]},n=0;n<this.actions.length;n++){var o={type:0,children:[],name:t.GetTriggerName(this.actions[n].trigger),properties:[]},s=this.actions[n].triggerOptions;if(s&&"number"!=typeof s)if(s.parameter instanceof e.Node)o.properties.push(e.Action._GetTargetProperty(s.parameter));else{var a={};e.Tools.DeepCopy(s.parameter,a,["mesh"]),s.parameter.mesh&&(a._meshId=s.parameter.mesh.id),o.properties.push({name:"parameter",targetType:null,value:a})}this.actions[n].serialize(o),r.children.push(o)}return r},t.Parse=function(i,r,n){var o=new e.ActionManager(n);null===r?n.actionManager=o:r.actionManager=o;for(var s=function(t,i){var r=Object.create(e[t].prototype);return r.constructor.apply(r,i),r},a=function(t,i,r,n){if(null===n){var o=parseFloat(i);return"true"===i||"false"===i?"true"===i:isNaN(o)?i:o}for(var s=n.split("."),a=i.split(","),h=0;h<s.length;h++)r=r[s[h]];if("boolean"==typeof r)return"true"===a[0];if("string"==typeof r)return a[0];for(var c=new Array,h=0;h<a.length;h++)c.push(parseFloat(a[h]));return r instanceof e.Vector3?e.Vector3.FromArray(c):r instanceof e.Vector4?e.Vector4.FromArray(c):r instanceof e.Color3?e.Color3.FromArray(c):r instanceof e.Color4?e.Color4.FromArray(c):parseFloat(a[0])},h=function(i,r,c,l,u){if(void 0===u&&(u=null),!i.detached){var d=new Array,f=null,p=null,m=i.combine&&i.combine.length>0;if(2===i.type?d.push(o):d.push(r),m){for(var _=new Array,g=0;g<i.combine.length;g++)h(i.combine[g],t.NothingTrigger,c,l,_);d.push(_)}else for(var v=0;v<i.properties.length;v++){var y=i.properties[v].value,x=i.properties[v].name,b=i.properties[v].targetType;"target"===x?y=f=null!==b&&"SceneProperties"===b?n:n.getNodeByName(y):"parent"===x?y=n.getNodeByName(y):"sound"===x?y=n.getSoundByName(y):"propertyPath"!==x?y=2===i.type&&"operator"===x?e.ValueCondition[y]:a(x,y,f,"value"===x?p:null):p=y,d.push(y)}if(null===u?d.push(c):d.push(null),"InterpolateValueAction"===i.name){var T=d[d.length-2];d[d.length-1]=T,d[d.length-2]=c}var A=s(i.name,d);if(A instanceof e.Condition&&null!==c){var E=new e.DoNothingAction(r,c);l?l.then(E):o.registerAction(E),l=E}null===u?A instanceof e.Condition?(c=A,A=l):(c=null,l?l.then(A):o.registerAction(A)):u.push(A);for(var v=0;v<i.children.length;v++)h(i.children[v],r,c,A,null)}},c=0;c<i.children.length;c++){var l,u=i.children[c];if(u.properties.length>0){var d=u.properties[0].value,f=null===u.properties[0].targetType?d:n.getMeshByName(d);f._meshId&&(f.mesh=n.getMeshByID(f._meshId)),l={trigger:e.ActionManager[u.name],parameter:f}}else l=e.ActionManager[u.name];for(var p=0;p<u.children.length;p++)u.detached||h(u.children[p],l,null,null);
}},t.GetTriggerName=function(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnPickUpTrigger";case 7:return"OnLongPressTrigger";case 8:return"OnPointerOverTrigger";case 9:return"OnPointerOutTrigger";case 10:return"OnEveryFrameTrigger";case 11:return"OnIntersectionEnterTrigger";case 12:return"OnIntersectionExitTrigger";case 13:return"OnKeyDownTrigger";case 14:return"OnKeyUpTrigger";case 15:return"OnPickOutTrigger";default:return""}},t._NothingTrigger=0,t._OnPickTrigger=1,t._OnLeftPickTrigger=2,t._OnRightPickTrigger=3,t._OnCenterPickTrigger=4,t._OnPickDownTrigger=5,t._OnPickUpTrigger=6,t._OnLongPressTrigger=7,t._OnPointerOverTrigger=8,t._OnPointerOutTrigger=9,t._OnEveryFrameTrigger=10,t._OnIntersectionEnterTrigger=11,t._OnIntersectionExitTrigger=12,t._OnKeyDownTrigger=13,t._OnKeyUpTrigger=14,t._OnPickOutTrigger=15,t.DragMovementThreshold=10,t.LongPressDelay=500,t})();e.ActionManager=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s,a,h){void 0===o&&(o=1e3),t.call(this,e,s),this.propertyPath=r,this.value=n,this.duration=o,this.stopOtherAnimations=a,this.onInterpolationDone=h,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){var t,i=this._actionManager.getScene(),r=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)t=e.Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof e.Color3)t=e.Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof e.Vector3)t=e.Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof e.Matrix)t=e.Animation.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof e.Quaternion))return void e.Tools.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");t=e.Animation.ANIMATIONTYPE_QUATERNION}var n=new e.Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),t,e.Animation.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(r),this.stopOtherAnimations&&i.stopAnimation(this._effectiveTarget),i.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,this.onInterpolationDone)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"InterpolateValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)},{name:"duration",value:e.Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:e.Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},i)},i})(e.Action);e.InterpolateValueAction=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n){t.call(this,e,n),this.propertyPath=r,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SwitchBooleanAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},i)},i})(e.Action);e.SwitchBooleanAction=t;var i=(function(t){function i(e,i,r,n){t.call(this,e,n),this.value=r,this._target=i}return __extends(i,t),i.prototype.execute=function(){this._target.state=this.value},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetStateAction",properties:[e.Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},i)},i})(e.Action);e.SetStateAction=i;var r=(function(t){function i(e,i,r,n,o){t.call(this,e,o),this.propertyPath=r,this.value=n,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)}]},i)},i})(e.Action);e.SetValueAction=r;var n=(function(t){function i(e,i,r,n,o){t.call(this,e,o),this.propertyPath=r,this.value=n,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&e.Tools.Warn("Warning: IncrementValueAction can only be used with number values")},i.prototype.execute=function(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"IncrementValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)}]},i)},i})(e.Action);e.IncrementValueAction=n;var o=(function(t){function i(e,i,r,n,o,s){t.call(this,e,s),this.from=r,this.to=n,this.loop=o,this._target=i}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"PlayAnimationAction",properties:[e.Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:e.Action._SerializeValueAsString(this.loop)||!1}]},i)},i})(e.Action);e.PlayAnimationAction=o;var s=(function(t){function i(e,i,r){t.call(this,e,r),this._target=i}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.stopAnimation(this._target)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"StopAnimationAction",properties:[e.Action._GetTargetProperty(this._target)]},i)},i})(e.Action);e.StopAnimationAction=s;var a=(function(t){function i(i,r){void 0===i&&(i=e.ActionManager.NothingTrigger),t.call(this,i,r)}return __extends(i,t),i.prototype.execute=function(){},i.prototype.serialize=function(e){return t.prototype._serialize.call(this,{name:"DoNothingAction",properties:[]},e)},i})(e.Action);e.DoNothingAction=a;var h=(function(e){function t(t,i,r){e.call(this,t,r),this.children=i}return __extends(t,e),t.prototype._prepare=function(){for(var e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()},t.prototype.execute=function(e){for(var t=0;t<this.children.length;t++)this.children[t].execute(e)},t.prototype.serialize=function(t){for(var i=e.prototype._serialize.call(this,{name:"CombineAction",properties:[],combine:[]},t),r=0;r<this.children.length;r++)i.combine.push(this.children[r].serialize(null));return i},t})(e.Action);e.CombineAction=h;var c=(function(e){function t(t,i,r){e.call(this,t,r),this.func=i}return __extends(t,e),t.prototype.execute=function(e){this.func(e)},t})(e.Action);e.ExecuteCodeAction=c;var l=(function(t){function i(e,i,r,n){t.call(this,e,n),this._target=i,this._parent=r}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){if(this._target.parent!==this._parent){var t=this._parent.getWorldMatrix().clone();t.invert(),this._target.position=e.Vector3.TransformCoordinates(this._target.position,t),this._target.parent=this._parent}},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetParentAction",properties:[e.Action._GetTargetProperty(this._target),e.Action._GetTargetProperty(this._parent)]},i)},i})(e.Action);e.SetParentAction=l;var u=(function(e){function t(t,i,r){e.call(this,t,r),this._sound=i}return __extends(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.play()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t})(e.Action);e.PlaySoundAction=u;var d=(function(e){function t(t,i,r){e.call(this,t,r),this._sound=i}return __extends(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.stop()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t})(e.Action);e.StopSoundAction=d})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this.id=t,this._engine=i.getEngine(),this._meshes=[],this._scene=i,this._vertexBuffers={},this._indices=[],r?this.setAllVerticesData(r,n):(this._totalVertices=0,this._indices=[]),o&&(o instanceof e.LinesMesh&&(this.boundingBias=new e.Vector2(0,o.intersectionThreshold),this.updateExtend()),this.applyToMesh(o),o.computeWorldMatrix(!0))}return Object.defineProperty(t.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(e){this._boundingBias&&this._boundingBias.equals(e)||(this._boundingBias=e.clone(),this.updateBoundingInfo(!0,null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extend",{get:function(){return this._extend},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._engine},t.prototype.isReady=function(){return this.delayLoadState===e.Engine.DELAYLOADSTATE_LOADED||this.delayLoadState===e.Engine.DELAYLOADSTATE_NONE},Object.defineProperty(t.prototype,"doNotSerialize",{get:function(){for(var e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype.setAllVerticesData=function(e,t){e.applyToGeometry(this,t),this.notifyUpdate()},t.prototype.setVerticesData=function(t,i,r,n){var o=new e.VertexBuffer(this._engine,i,t,r,0===this._meshes.length,n);this.setVerticesBuffer(o)},t.prototype.setVerticesBuffer=function(t){var i=t.getKind();if(this._vertexBuffers[i]&&this._vertexBuffers[i].dispose(),this._vertexBuffers[i]=t,i===e.VertexBuffer.PositionKind){var r=t.getData(),n=t.getStrideSize();this._totalVertices=r.length/n,this.updateExtend(r,n);for(var o=this._meshes,s=o.length,a=0;a<s;a++){var h=o[a];h._resetPointsArrayCache(),h._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),h._createGlobalSubMesh(),h.computeWorldMatrix(!0)}}this.notifyUpdate(i)},t.prototype.updateVerticesDataDirectly=function(e,t,i){var r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i),this.notifyUpdate(e))},t.prototype.updateVerticesData=function(t,i,r){var n=this.getVertexBuffer(t);if(n){if(n.update(i),t===e.VertexBuffer.PositionKind){var o=n.getStrideSize();this._totalVertices=i.length/o,this.updateBoundingInfo(r,i)}this.notifyUpdate(t)}},t.prototype.updateBoundingInfo=function(t,i){t&&this.updateExtend(i);for(var r=this._meshes,n=r.length,o=0;o<n;o++){var s=r[o];if(s._resetPointsArrayCache(),t){s._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum);for(var a=0;a<s.subMeshes.length;a++){var h=s.subMeshes[a];h.refreshBoundingInfo()}}}},t.prototype.getTotalVertices=function(){return this.isReady()?this._totalVertices:0},t.prototype.getVerticesData=function(e,t){var i=this.getVertexBuffer(e);if(!i)return null;var r=i.getData();if(t&&1!==this._meshes.length){for(var n=r.length,o=[],s=0;s<n;s++)o.push(r[s]);return o}return r},t.prototype.getVertexBuffer=function(e){return this.isReady()?this._vertexBuffers[e]:null},t.prototype.getVertexBuffers=function(){return this.isReady()?this._vertexBuffers:null},t.prototype.isVerticesDataPresent=function(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&this._delayInfo.indexOf(e)!==-1},t.prototype.getVerticesDataKinds=function(){var e,t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t},t.prototype.setIndices=function(e,t){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),void 0!==t&&(this._totalVertices=t);for(var i=this._meshes,r=i.length,n=0;n<r;n++)i[n]._createGlobalSubMesh();this.notifyUpdate()},t.prototype.getTotalIndices=function(){return this.isReady()?this._indices.length:0},t.prototype.getIndices=function(e){if(!this.isReady())return null;var t=this._indices;if(e&&1!==this._meshes.length){for(var i=t.length,r=[],n=0;n<i;n++)r.push(t[n]);return r}return t},t.prototype.getIndexBuffer=function(){return this.isReady()?this._indexBuffer:null},t.prototype.releaseForMesh=function(e,t){var i=this._meshes,r=i.indexOf(e);if(r!==-1){for(var n in this._vertexBuffers)this._vertexBuffers[n].dispose();this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),i.splice(r,1),e._geometry=null,0===i.length&&t&&this.dispose()}},t.prototype.applyToMesh=function(e){if(e._geometry!==this){var t=e._geometry;t&&t.releaseForMesh(e);var i=this._meshes;e._geometry=this,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):e._boundingInfo=this._boundingInfo}},t.prototype.updateExtend=function(t,i){void 0===t&&(t=null),t||(t=this._vertexBuffers[e.VertexBuffer.PositionKind].getData()),this._extend=e.Tools.ExtractMinAndMax(t,0,this._totalVertices,this.boundingBias,i)},t.prototype._applyToMesh=function(t){var i=this._meshes.length;for(var r in this._vertexBuffers)1===i&&this._vertexBuffers[r].create(),this._vertexBuffers[r].getBuffer().references=i,r===e.VertexBuffer.PositionKind&&(t._resetPointsArrayCache(),this._extend||this.updateExtend(this._vertexBuffers[r].getData()),t._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),t._createGlobalSubMesh(),t._updateBoundingInfo());1===i&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e)},t.prototype.load=function(t,i){if(this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING){if(this.isReady())return void(i&&i());this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t,i)}},t.prototype._queueLoad=function(t,i){var r=this;t._addPendingData(this),e.Tools.LoadFile(this.delayLoadingFile,(function(n){r._delayLoadingFunction(JSON.parse(n),r),r.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,r._delayInfo=[],t._removePendingData(r);for(var o=r._meshes,s=o.length,a=0;a<s;a++)r._applyToMesh(o[a]);i&&i()}),(function(){}),t.database)},t.prototype.toLeftHanded=function(){var t=this.getIndices(!1);if(null!=t&&t.length>0){for(var i=0;i<t.length;i+=3){var r=t[i+0];t[i+0]=t[i+2],t[i+2]=r}this.setIndices(t)}var n=this.getVerticesData(e.VertexBuffer.PositionKind,!1);if(null!=n&&n.length>0){for(var i=0;i<n.length;i+=3)n[i+2]=-n[i+2];this.setVerticesData(e.VertexBuffer.PositionKind,n,!1)}var o=this.getVerticesData(e.VertexBuffer.NormalKind,!1);if(null!=o&&o.length>0){for(var i=0;i<o.length;i+=3)o[i+2]=-o[i+2];this.setVerticesData(e.VertexBuffer.NormalKind,o,!1)}},t.prototype.isDisposed=function(){return this._isDisposed},t.prototype.dispose=function(){var t,i=this._meshes,r=i.length;for(t=0;t<r;t++)this.releaseForMesh(i[t]);this._meshes=[];for(var n in this._vertexBuffers)this._vertexBuffers[n].dispose();this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._isDisposed=!0},t.prototype.copy=function(i){var r=new e.VertexData;r.indices=[];for(var n=this.getIndices(),o=0;o<n.length;o++)r.indices.push(n[o]);var s,a=!1,h=!1;for(s in this._vertexBuffers){var c=this.getVerticesData(s);c instanceof Float32Array?r.set(new Float32Array(c),s):r.set(c.slice(0),s),h||(a=this.getVertexBuffer(s).isUpdatable(),h=!a)}var l=new t(i,this._scene,r,a,null);l.delayLoadState=this.delayLoadState,l.delayLoadingFile=this.delayLoadingFile,l._delayLoadingFunction=this._delayLoadingFunction;for(s in this._delayInfo)l._delayInfo=l._delayInfo||[],l._delayInfo.push(s);return l._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),l},t.prototype.serialize=function(){var t={};return t.id=this.id,e.Tags.HasTags(this)&&(t.tags=e.Tags.GetTags(this)),t},t.prototype.serializeVerticeData=function(){var t=this.serialize();return this.isVerticesDataPresent(e.VertexBuffer.PositionKind)&&(t.positions=this.getVerticesData(e.VertexBuffer.PositionKind)),this.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(t.normals=this.getVerticesData(e.VertexBuffer.NormalKind)),this.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(t.uvs=this.getVerticesData(e.VertexBuffer.UVKind)),this.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(t.uv2s=this.getVerticesData(e.VertexBuffer.UV2Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV3Kind)&&(t.uv3s=this.getVerticesData(e.VertexBuffer.UV3Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV4Kind)&&(t.uv4s=this.getVerticesData(e.VertexBuffer.UV4Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV5Kind)&&(t.uv5s=this.getVerticesData(e.VertexBuffer.UV5Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV6Kind)&&(t.uv6s=this.getVerticesData(e.VertexBuffer.UV6Kind)),this.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(t.colors=this.getVerticesData(e.VertexBuffer.ColorKind)),this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&(t.matricesIndices=this.getVerticesData(e.VertexBuffer.MatricesIndicesKind),t.matricesIndices._isExpanded=!0),this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)&&(t.matricesWeights=this.getVerticesData(e.VertexBuffer.MatricesWeightsKind)),t.indices=this.getIndices(),t},t.ExtractFromMesh=function(e,t){var i=e._geometry;return i?i.copy(t):null},t.RandomId=function(){return e.Tools.RandomId()},t.ImportGeometry=function(t,i){var r=i.getScene(),n=t.geometryId;if(n){var o=r.getGeometryByID(n);o&&o.applyToMesh(i)}else if(t instanceof ArrayBuffer){var s=i._binaryInfo;if(s.positionsAttrDesc&&s.positionsAttrDesc.count>0){var a=new Float32Array(t,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);i.setVerticesData(e.VertexBuffer.PositionKind,a,!1)}if(s.normalsAttrDesc&&s.normalsAttrDesc.count>0){var h=new Float32Array(t,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);i.setVerticesData(e.VertexBuffer.NormalKind,h,!1)}if(s.uvsAttrDesc&&s.uvsAttrDesc.count>0){var c=new Float32Array(t,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);i.setVerticesData(e.VertexBuffer.UVKind,c,!1)}if(s.uvs2AttrDesc&&s.uvs2AttrDesc.count>0){var l=new Float32Array(t,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV2Kind,l,!1)}if(s.uvs3AttrDesc&&s.uvs3AttrDesc.count>0){var u=new Float32Array(t,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV3Kind,u,!1)}if(s.uvs4AttrDesc&&s.uvs4AttrDesc.count>0){var d=new Float32Array(t,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV4Kind,d,!1)}if(s.uvs5AttrDesc&&s.uvs5AttrDesc.count>0){var f=new Float32Array(t,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV5Kind,f,!1)}if(s.uvs6AttrDesc&&s.uvs6AttrDesc.count>0){var p=new Float32Array(t,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV6Kind,p,!1)}if(s.colorsAttrDesc&&s.colorsAttrDesc.count>0){var m=new Float32Array(t,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);i.setVerticesData(e.VertexBuffer.ColorKind,m,!1,s.colorsAttrDesc.stride)}if(s.matricesIndicesAttrDesc&&s.matricesIndicesAttrDesc.count>0){var _=new Int32Array(t,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count);i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,_,!1)}if(s.matricesWeightsAttrDesc&&s.matricesWeightsAttrDesc.count>0){var g=new Float32Array(t,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);i.setVerticesData(e.VertexBuffer.MatricesWeightsKind,g,!1)}if(s.indicesAttrDesc&&s.indicesAttrDesc.count>0){var v=new Int32Array(t,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);i.setIndices(v)}if(s.subMeshesAttrDesc&&s.subMeshesAttrDesc.count>0){var y=new Int32Array(t,s.subMeshesAttrDesc.offset,5*s.subMeshesAttrDesc.count);i.subMeshes=[];for(var x=0;x<s.subMeshesAttrDesc.count;x++){var b=y[5*x+0],T=y[5*x+1],A=y[5*x+2],E=y[5*x+3],P=y[5*x+4];new e.SubMesh(b,T,A,E,P,i)}}}else if(t.positions&&t.normals&&t.indices){if(i.setVerticesData(e.VertexBuffer.PositionKind,t.positions,!1),i.setVerticesData(e.VertexBuffer.NormalKind,t.normals,!1),t.uvs&&i.setVerticesData(e.VertexBuffer.UVKind,t.uvs,!1),t.uvs2&&i.setVerticesData(e.VertexBuffer.UV2Kind,t.uvs2,!1),t.uvs3&&i.setVerticesData(e.VertexBuffer.UV3Kind,t.uvs3,!1),t.uvs4&&i.setVerticesData(e.VertexBuffer.UV4Kind,t.uvs4,!1),t.uvs5&&i.setVerticesData(e.VertexBuffer.UV5Kind,t.uvs5,!1),t.uvs6&&i.setVerticesData(e.VertexBuffer.UV6Kind,t.uvs6,!1),t.colors&&i.setVerticesData(e.VertexBuffer.ColorKind,e.Color4.CheckColors4(t.colors,t.positions.length/3),!1),t.matricesIndices)if(t.matricesIndices._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,t.matricesIndices,!1);else{for(var M=[],x=0;x<t.matricesIndices.length;x++){var S=t.matricesIndices[x];M.push(255&S),M.push((65280&S)>>8),M.push((16711680&S)>>16),M.push(S>>24)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,M,!1)}if(t.matricesIndicesExtra)if(t.matricesIndicesExtra._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,t.matricesIndicesExtra,!1);else{for(var M=[],x=0;x<t.matricesIndicesExtra.length;x++){var S=t.matricesIndicesExtra[x];M.push(255&S),M.push((65280&S)>>8),M.push((16711680&S)>>16),M.push(S>>24)}i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,M,!1)}t.matricesWeights&&i.setVerticesData(e.VertexBuffer.MatricesWeightsKind,t.matricesWeights,!1),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,t.matricesWeightsExtra,!1),i.setIndices(t.indices)}if(t.subMeshes){i.subMeshes=[];for(var C=0;C<t.subMeshes.length;C++){var R=t.subMeshes[C];new e.SubMesh(R.materialIndex,R.verticesStart,R.verticesCount,R.indexStart,R.indexCount,i)}}i._shouldGenerateFlatShading&&(i.convertToFlatShadedMesh(),delete i._shouldGenerateFlatShading),i.computeWorldMatrix(!0),r._selectionOctree&&r._selectionOctree.addMesh(i)},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r);return e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var t;!(function(t){var i;!(function(i){var r=(function(e){function t(t,i,r,n){e.call(this,t,i,null,!1,n),this._canBeRegenerated=r,this._beingRegenerated=!0,this.regenerate(),this._beingRegenerated=!1}return __extends(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);i._Primitive=r;var n=(function(t){function i(i,r,n,o,s,a,h,c,l){void 0===l&&(l=e.Mesh.DEFAULTSIDE),t.call(this,i,r,h,c),this.pathArray=n,this.closeArray=o,this.closePath=s,this.offset=a,this.side=l}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),null,this.side)},i})(r);i.Ribbon=n;var o=(function(i){function r(t,r,n,o,s,a){void 0===a&&(a=e.Mesh.DEFAULTSIDE),i.call(this,t,r,o,s),this.size=n,this.side=a}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.size=this.size,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Box(i.id,r,i.size,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Box=o;var s=(function(i){function r(t,r,n,o,s,a,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE),i.call(this,t,r,s,a),this.segments=n,this.diameter=o,this.side=h}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Sphere(i.id,r,i.segments,i.diameter,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Sphere=s;var a=(function(t){function i(i,r,n,o,s,a,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE),t.call(this,i,r,s,a),this.radius=n,this.tessellation=o,this.side=h}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(r);i.Disc=a;var h=(function(i){function r(t,r,n,o,s,a,h,c,l,u){void 0===h&&(h=1),void 0===u&&(u=e.Mesh.DEFAULTSIDE),i.call(this,t,r,c,l),this.height=n,this.diameterTop=o,this.diameterBottom=s,this.tessellation=a,this.subdivisions=h,this.side=u}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Cylinder(i.id,r,i.height,i.diameterTop,i.diameterBottom,i.tessellation,i.subdivisions,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Cylinder=h;var c=(function(i){function r(t,r,n,o,s,a,h,c){void 0===c&&(c=e.Mesh.DEFAULTSIDE),i.call(this,t,r,a,h),this.diameter=n,this.thickness=o,this.tessellation=s,this.side=c}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Torus(i.id,r,i.diameter,i.thickness,i.tessellation,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Torus=c;var l=(function(i){function r(e,t,r,n,o,s,a){i.call(this,e,t,s,a),this.width=r,this.height=n,this.subdivisions=o}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Ground(i.id,r,i.width,i.height,i.subdivisions,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Ground=l;var u=(function(t){function i(e,i,r,n,o,s,a,h,c,l){t.call(this,e,i,c,l),this.xmin=r,this.zmin=n,this.xmax=o,this.zmax=s,this.subdivisions=a,this.precision=h}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(r);i.TiledGround=u;var d=(function(i){function r(t,r,n,o,s,a){void 0===a&&(a=e.Mesh.DEFAULTSIDE),i.call(this,t,r,o,s),this.size=n,this.side=a}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);
return e.size=this.size,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Plane(i.id,r,i.size,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Plane=d;var f=(function(i){function r(t,r,n,o,s,a,h,c,l,u,d){void 0===d&&(d=e.Mesh.DEFAULTSIDE),i.call(this,t,r,l,u),this.radius=n,this.tube=o,this.radialSegments=s,this.tubularSegments=a,this.p=h,this.q=c,this.side=d}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.TorusKnot(i.id,r,i.radius,i.tube,i.radialSegments,i.tubularSegments,i.p,i.q,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.TorusKnot=f})(i=t.Primitives||(t.Primitives={}))})(t=e.Geometry||(e.Geometry={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,i,r),this.generateOctree=!1,this._worldInverse=new e.Matrix}return __extends(i,t),Object.defineProperty(i.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!0,configurable:!0}),i.prototype.optimize=function(e,t){void 0===t&&(t=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e),this.createOrUpdateSubmeshesOctree(t)},i.prototype.getHeightAtCoordinates=function(e,t){if(e-=this.position.x,t-=this.position.z,e/=this.scaling.x,t/=this.scaling.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var i=this._getFacetAt(e,t),r=-(i.x*e+i.z*t+i.w)/i.y;return r*this.scaling.y+this.position.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(e,t,i){if(e-=this.position.x,t-=this.position.z,e/=this.scaling.x,t/=this.scaling.z,!(e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)){this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var r=this._getFacetAt(e,t);i.x=r.x,i.y=r.y,i.z=r.z}},i.prototype.updateCoordinateHeights=function(){this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads()},i.prototype._getFacetAt=function(e,t){var i,r=(this._subdivisionsX,this._subdivisionsY,Math.floor((e+this._maxX)*this._subdivisionsX/this._width)),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),o=this._heightQuads[n*this._subdivisionsX+r];return i=t<o.slope.x*e+o.slope.y?o.facet1:o.facet2},i.prototype._initHeightQuads=function(){var t=this._subdivisionsX,i=this._subdivisionsY;this._heightQuads=new Array;for(var r=0;r<i;r++)for(var n=0;n<t;n++){var o={slope:e.Vector2.Zero(),facet1:new e.Vector4(0,0,0,0),facet2:new e.Vector4(0,0,0,0)};this._heightQuads[r*t+n]=o}},i.prototype._computeHeightQuads=function(){for(var t=this.getVerticesData(e.VertexBuffer.PositionKind),i=e.Tmp.Vector3[3],r=e.Tmp.Vector3[2],n=e.Tmp.Vector3[1],o=e.Tmp.Vector3[0],s=e.Tmp.Vector3[4],a=e.Tmp.Vector3[5],h=e.Tmp.Vector3[6],c=e.Tmp.Vector3[7],l=e.Tmp.Vector3[8],u=0,d=0,f=0,p=0,m=0,_=0,g=0,v=this._subdivisionsX,y=this._subdivisionsY,x=0;x<y;x++)for(var b=0;b<v;b++){u=3*b,d=x*(v+1)*3,f=(x+1)*(v+1)*3,i.x=t[d+u],i.y=t[d+u+1],i.z=t[d+u+2],r.x=t[d+u+3],r.y=t[d+u+4],r.z=t[d+u+5],n.x=t[f+u],n.y=t[f+u+1],n.z=t[f+u+2],o.x=t[f+u+3],o.y=t[f+u+4],o.z=t[f+u+5],p=(o.z-i.z)/(o.x-i.x),m=i.z-p*i.x,r.subtractToRef(i,s),n.subtractToRef(i,a),o.subtractToRef(i,h),e.Vector3.CrossToRef(h,a,c),e.Vector3.CrossToRef(s,h,l),c.normalize(),l.normalize(),_=-(c.x*i.x+c.y*i.y+c.z*i.z),g=-(l.x*r.x+l.y*r.y+l.z*r.z);var T=this._heightQuads[x*v+b];T.slope.copyFromFloats(p,m),T.facet1.copyFromFloats(c.x,c.y,c.z,_),T.facet2.copyFromFloats(l.x,l.y,l.z,g)}},i})(e.Mesh);e.GroundMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===n&&(n=null),t.call(this,i,r,n,o,s),this.color=new e.Color3(1,1,1),this.alpha=1,this._positionBuffer={},o&&(this.color=o.color.clone(),this.alpha=o.alpha),this._intersectionThreshold=.1,this._colorShader=new e.ShaderMaterial("colorShader",r,"color",{attributes:[e.VertexBuffer.PositionKind],uniforms:["worldViewProjection","color"],needAlphaBlending:!0}),this._positionBuffer[e.VertexBuffer.PositionKind]=null}return __extends(i,t),Object.defineProperty(i.prototype,"intersectionThreshold",{get:function(){return this._intersectionThreshold},set:function(t){this._intersectionThreshold!==t&&(this._intersectionThreshold=t,this.geometry&&(this.geometry.boundingBias=new e.Vector2(0,t)))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._colorShader},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.createInstance=function(t){return e.Tools.Log("LinesMeshes do not support createInstance."),null},i.prototype._bind=function(t,i,r){var n=this.getScene().getEngine();this._positionBuffer[e.VertexBuffer.PositionKind]=this._geometry.getVertexBuffer(e.VertexBuffer.PositionKind),n.bindBuffers(this._positionBuffer,this._geometry.getIndexBuffer(),this._colorShader.getEffect()),this._colorShader.setColor4("color",this.color.toColor4(this.alpha))},i.prototype._draw=function(e,t,i){if(this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){var r=this.getScene().getEngine();r.draw(!1,e.indexStart,e.indexCount)}},i.prototype.dispose=function(e){this._colorShader.dispose(),t.prototype.dispose.call(this,e)},i.prototype.clone=function(e,t,r){return new i(e,this.getScene(),t,this,r)},i})(e.Mesh);e.LinesMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){var r=this;void 0===t&&(t=""),void 0===i&&(i="black"),this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=function(){var e=r._renderingCanvas.getBoundingClientRect();r._loadingDiv.style.position="absolute",r._loadingDiv.style.left=e.left+"px",r._loadingDiv.style.top=e.top+"px",r._loadingDiv.style.width=e.width+"px",r._loadingDiv.style.height=e.height+"px"}}return e.prototype.displayLoadingUI=function(){var e=this;if(!this._loadingDiv){this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText;var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==",t.style.position="absolute",t.style.left="50%",t.style.top="50%",t.style.marginLeft="-50px",t.style.marginTop="-50px",t.style.transition="transform 1.0s ease",t.style.webkitTransition="-webkit-transform 1.0s ease";var i=360,r=function(){i+=360,t.style.transform="rotateZ("+i+"deg)",t.style.webkitTransform="rotateZ("+i+"deg)"};t.addEventListener("transitionend",r),t.addEventListener("webkitTransitionEnd",r),this._loadingDiv.appendChild(t);var n=new Image;n.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=",n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.marginLeft="-50px",n.style.marginTop="-50px",this._loadingDiv.appendChild(n),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),setTimeout((function(){e._loadingDiv.style.opacity="1",t.style.transform="rotateZ(360deg)",t.style.webkitTransform="rotateZ(360deg)"}),0)}},e.prototype.hideLoadingUI=function(){var e=this;if(this._loadingDiv){var t=function(){e._loadingDiv&&(document.body.removeChild(e._loadingDiv),window.removeEventListener("resize",e._resizeLoadingUI),e._loadingDiv=null)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",t)}},Object.defineProperty(e.prototype,"loadingUIText",{set:function(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loadingUIBackgroundColor",{get:function(){return this._loadingDivBackgroundColor},set:function(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)},enumerable:!0,configurable:!0}),e})();e.DefaultLoadingScreen=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._audioContext=null,this._audioContextInitialized=!1,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.unlocked=!1,this.isMP3supported=!1,this.isOGGsupported=!1,"undefined"==typeof window.AudioContext&&"undefined"==typeof window.webkitAudioContext||(window.AudioContext=window.AudioContext||window.webkitAudioContext,this.canUseWebAudio=!0);var e=document.createElement("audio");e&&e.canPlayType&&e.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")&&(this.isMP3supported=!0),e&&e.canPlayType&&e.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0),/iPad|iPhone|iPod/.test(navigator.platform)?this._unlockiOSaudio():this.unlocked=!0}return Object.defineProperty(t.prototype,"audioContext",{get:function(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext},enumerable:!0,configurable:!0}),t.prototype._unlockiOSaudio=function(){var e=this,t=function(){var i=e.audioContext.createBuffer(1,1,22050),r=e.audioContext.createBufferSource();r.buffer=i,r.connect(e.audioContext.destination),r.start(0),setTimeout((function(){r.playbackState!==r.PLAYING_STATE&&r.playbackState!==r.FINISHED_STATE||(e.unlocked=!0,window.removeEventListener("touchend",t,!1),e.onAudioUnlocked&&e.onAudioUnlocked())}),0)};window.addEventListener("touchend",t,!1)},t.prototype._initializeAudioContext=function(){try{this.canUseWebAudio&&(this._audioContext=new AudioContext,this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this._audioContext.destination),this._audioContextInitialized=!0)}catch(t){this.canUseWebAudio=!1,e.Tools.Error("Web Audio: "+t.message)}},t.prototype.dispose=function(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1},t.prototype.getGlobalVolume=function(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1},t.prototype.setGlobalVolume=function(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)},t.prototype.connectToAnalyser=function(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))},t})();e.AudioEngine=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){var s=this;if(this.autoplay=!1,this.loop=!1,this.useCustomAttenuation=!1,this.spatialSound=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._startOffset=0,this._position=e.Vector3.Zero(),this._localDirection=new e.Vector3(1,0,0),this._volume=1,this._isLoaded=!1,this._isReadyToPlay=!1,this.isPlaying=!1,this.isPaused=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=t,this._scene=r,this._readyToPlayCallback=n,this._customAttenuationFunction=function(e,t,i,r,n){return t<i?e*(1-t/i):0},o&&(this.autoplay=o.autoplay||!1,this.loop=o.loop||!1,void 0!==o.volume&&(this._volume=o.volume),this.spatialSound=o.spatialSound||!1,this.maxDistance=o.maxDistance||100,this.useCustomAttenuation=o.useCustomAttenuation||!1,this.rolloffFactor=o.rolloffFactor||1,this.refDistance=o.refDistance||1,this.distanceModel=o.distanceModel||"linear",this._playbackRate=o.playbackRate||1,this._streaming=o.streaming||!1),e.Engine.audioEngine.canUseWebAudio){this._soundGain=e.Engine.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._ouputAudioNode=this._soundGain,this.spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.AddSound(this);var a=!0;if(i){"string"==typeof i&&(this._urlType="String"),Array.isArray(i)&&(this._urlType="Array"),i instanceof ArrayBuffer&&(this._urlType="ArrayBuffer");var h=[],c=!1;switch(this._urlType){case"ArrayBuffer":i.byteLength>0&&(c=!0,this._soundLoaded(i));break;case"String":h.push(i);case"Array":0===h.length&&(h=i);for(var l=0;l<h.length;l++){var u=h[l];if(u.indexOf(".mp3",u.length-4)!==-1&&e.Engine.audioEngine.isMP3supported&&(c=!0),u.indexOf(".ogg",u.length-4)!==-1&&e.Engine.audioEngine.isOGGsupported&&(c=!0),u.indexOf(".wav",u.length-4)!==-1&&(c=!0),c){this._streaming?(this._htmlAudioElement=new Audio(u),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,this._htmlAudioElement.crossOrigin="anonymous",this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(function(){s._isReadyToPlay=!0,s.autoplay&&s.play(),s._readyToPlayCallback&&s._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement)):e.Tools.LoadFile(u,(function(e){s._soundLoaded(e)}),null,this._scene.database,!0);break}}break;default:a=!1}a?c||(this._isReadyToPlay=!0,this._readyToPlayCallback&&window.setTimeout((function(){s._readyToPlayCallback()}),1e3)):e.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}}else this._scene.mainSoundTrack.AddSound(this),e.Engine.audioEngine.WarnedWebAudioUnsupported||(e.Tools.Error("Web Audio is not supported by your browser."),e.Engine.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&window.setTimeout((function(){s._readyToPlayCallback()}),1e3)}return t.prototype.dispose=function(){e.Engine.audioEngine.canUseWebAudio&&this._isReadyToPlay&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.RemoveSound(this):this._scene.soundTracks[this.soundTrackId].RemoveSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedMesh=null))},t.prototype._soundLoaded=function(t){var i=this;this._isLoaded=!0,e.Engine.audioEngine.audioContext.decodeAudioData(t,(function(e){i._audioBuffer=e,i._isReadyToPlay=!0,i.autoplay&&i.play(),i._readyToPlayCallback&&i._readyToPlayCallback()}),(function(t){e.Tools.Error("Error while decoding audio data for: "+i.name+" / Error: "+t)}))},t.prototype.setAudioBuffer=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._audioBuffer=t,this._isReadyToPlay=!0)},t.prototype.updateOptions=function(e){e&&(this.loop=e.loop||this.loop,this.maxDistance=e.maxDistance||this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation||this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor||this.rolloffFactor,this.refDistance=e.refDistance||this.refDistance,this.distanceModel=e.distanceModel||this.distanceModel,this._playbackRate=e.playbackRate||this._playbackRate,this._updateSpatialParameters(),this.isPlaying&&(this._streaming?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource.playbackRate.value=this._playbackRate))},t.prototype._createSpatialParameters=function(){e.Engine.audioEngine.canUseWebAudio&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=e.Engine.audioEngine.audioContext.createPanner(),this._updateSpatialParameters(),this._soundPanner.connect(this._ouputAudioNode),this._inputAudioNode=this._soundPanner)},t.prototype._updateSpatialParameters=function(){this.spatialSound&&(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel))},t.prototype.switchPanningModelToHRTF=function(){this._panningModel="HRTF",this._switchPanningModel()},t.prototype.switchPanningModelToEqualPower=function(){this._panningModel="equalpower",this._switchPanningModel()},t.prototype._switchPanningModel=function(){e.Engine.audioEngine.canUseWebAudio&&this.spatialSound&&(this._soundPanner.panningModel=this._panningModel)},t.prototype.connectToSoundTrackAudioNode=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._isOutputConnected&&this._ouputAudioNode.disconnect(),this._ouputAudioNode.connect(t),this._isOutputConnected=!0)},t.prototype.setDirectionalCone=function(t,i,r){return i<t?void e.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=t,this._coneOuterAngle=i,this._coneOuterGain=r,this._isDirectional=!0,void(this.isPlaying&&this.loop&&(this.stop(),this.play())))},t.prototype.setPosition=function(t){this._position=t,e.Engine.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z)},t.prototype.setLocalDirectionToMesh=function(t){this._localDirection=t,e.Engine.audioEngine.canUseWebAudio&&this._connectedMesh&&this.isPlaying&&this._updateDirection()},t.prototype._updateDirection=function(){var t=this._connectedMesh.getWorldMatrix(),i=e.Vector3.TransformNormal(this._localDirection,t);i.normalize(),this._soundPanner.setOrientation(i.x,i.y,i.z)},t.prototype.updateDistanceFromListener=function(){if(e.Engine.audioEngine.canUseWebAudio&&this._connectedMesh&&this.useCustomAttenuation){var t=this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,t,this.maxDistance,this.refDistance,this.rolloffFactor)}},t.prototype.setAttenuationFunction=function(e){this._customAttenuationFunction=e},t.prototype.play=function(t,i){var r=this;if(this._isReadyToPlay&&this._scene.audioEnabled)try{this._startOffset<0&&(t=-this._startOffset,this._startOffset=0);var n=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource&&this._streamingSource||this.spatialSound&&(this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedMesh?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming?(this._streamingSource||(this._streamingSource=e.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=function(){r._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement.play()):(this._soundSource=e.Engine.audioEngine.audioContext.createBufferSource(),this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=function(){r._onended()},this._soundSource.start(n,this.isPaused?this._startOffset%this._soundSource.buffer.duration:i?i:0)),this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(o){e.Tools.Error("Error while trying to play audio: "+this.name+", "+o.message)}},t.prototype._onended=function(){this.isPlaying=!1,this.onended&&this.onended()},t.prototype.stop=function(t){if(this.isPlaying){if(this._streaming)this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0);else{var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=null,this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement.pause():(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&(i?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource.playbackRate.value=this._playbackRate)},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){this.setPosition(t.getBoundingInfo().boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var h,c={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var l=function(){o._isReadyToPlay?(h._audioBuffer=o.getAudioBuffer(),h._isReadyToPlay=!0,h.autoplay&&h.play()):window.setTimeout(l,300)};h=new t(a,new ArrayBuffer(0),r,null,c),l()}else h=new t(a,s,r,function(){r._removePendingData(h)},c),r._addPendingData(h);if(i.position){var u=e.Vector3.FromArray(i.position);h.setPosition(u)}if(i.isDirectional&&(h.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var d=e.Vector3.FromArray(i.localDirectionToMesh);h.setLocalDirectionToMesh(d)}if(i.connectedMeshId){var f=r.getMeshByID(i.connectedMeshId);f&&h.attachToMesh(f)}return h},t})();e.Sound=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(t.soundTrackId===-1?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),
t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);t!==-1&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToHRTF()},t.prototype.switchPanningModelToEqualPower=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToEqualPower()},t.prototype.connectToAnalyser=function(t){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=t,e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,e.Engine.audioEngine.masterGain))},t})();e.SoundTrack=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,i,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,o,s,a,h,c),this.direction=r,this.blurWidth=n,this.onApplyObservable.add((function(e){e.setFloat2("screenSize",l.width,l.height),e.setVector2("direction",l.direction),e.setFloat("blurWidth",l.blurWidth)}))}return __extends(i,t),i})(e.PostProcess),i=(function(){function i(t,r,n){this._vertexBuffers={},this._mainTextureDesiredSize={width:0,height:0},this._meshes={},this._maxSize=0,this._shouldRender=!1,this._instanceGlowingMeshStencilReference=i.glowingMeshStencilReference++,this._excludedMeshes={},this.innerGlow=!0,this.outerGlow=!0,this.isEnabled=!0,this.onDisposeObservable=new e.Observable,this.onBeforeRenderMainTextureObservable=new e.Observable,this.onBeforeBlurObservable=new e.Observable,this.onAfterBlurObservable=new e.Observable,this.onBeforeComposeObservable=new e.Observable,this.onAfterComposeObservable=new e.Observable,this.onSizeChangedObservable=new e.Observable,this._scene=r;var o=r.getEngine();this._engine=o,this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.highlightLayers.push(this),this._engine.isStencilEnable||e.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }"),this._options=n||{mainTextureRatio:.25,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:e.Engine.ALPHA_COMBINE},this._options.mainTextureRatio=this._options.mainTextureRatio||.25,this._options.blurTextureSizeRatio=this._options.blurTextureSizeRatio||.5,this._options.blurHorizontalSize=this._options.blurHorizontalSize||1,this._options.blurVerticalSize=this._options.blurVerticalSize||1,this._options.alphaBlendingMode=this._options.alphaBlendingMode||e.Engine.ALPHA_COMBINE;var s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1);var a=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,(!1),(!1),2);this._vertexBuffers[e.VertexBuffer.PositionKind]=a;var h=[];h.push(0),h.push(1),h.push(2),h.push(0),h.push(2),h.push(3),this._indexBuffer=o.createIndexBuffer(h),this._glowMapMergeEffect=o.createEffect("glowMapMerge",[e.VertexBuffer.PositionKind],["offset"],["textureSampler"],""),this.setMainTextureSize(),this.createTextureAndPostProcesses()}return Object.defineProperty(i.prototype,"blurHorizontalSize",{get:function(){return this._horizontalBlurPostprocess.blurWidth},set:function(e){this._horizontalBlurPostprocess.blurWidth=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurVerticalSize",{get:function(){return this._verticalBlurPostprocess.blurWidth},set:function(e){this._verticalBlurPostprocess.blurWidth=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"camera",{get:function(){return this._options.camera},enumerable:!0,configurable:!0}),i.prototype.createTextureAndPostProcesses=function(){var r=this,n=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,o=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;n=e.Tools.GetExponentOfTwo(n,this._maxSize),o=e.Tools.GetExponentOfTwo(o,this._maxSize),this._mainTexture=new e.RenderTargetTexture("HighlightLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._mainTexture.activeCamera=this._options.camera,this._mainTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._blurTexture=new e.RenderTargetTexture("HighlightLayerBlurRTT",{width:n,height:o},this._scene,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._blurTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(e.Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._downSamplePostprocess=new e.PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",r._mainTexture)})),this._options.alphaBlendingMode===e.Engine.ALPHA_COMBINE?(this._horizontalBlurPostprocess=new t("HighlightLayerHBP",new e.Vector2(1,0),this._options.blurHorizontalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)})),this._verticalBlurPostprocess=new t("HighlightLayerVBP",new e.Vector2(0,1),this._options.blurVerticalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)}))):(this._horizontalBlurPostprocess=new e.BlurPostProcess("HighlightLayerHBP",new e.Vector2(1,0),this._options.blurHorizontalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)})),this._verticalBlurPostprocess=new e.BlurPostProcess("HighlightLayerVBP",new e.Vector2(0,1),this._options.blurVerticalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)}))),this._mainTexture.onAfterUnbindObservable.add((function(){r.onBeforeBlurObservable.notifyObservers(r),r._scene.postProcessManager.directRender([r._downSamplePostprocess,r._horizontalBlurPostprocess,r._verticalBlurPostprocess],r._blurTexture.getInternalTexture()),r.onAfterBlurObservable.notifyObservers(r)}));var s=function(t){var n=t.getRenderingMesh(),o=r._scene,s=o.getEngine();s.setState(t.getMaterial().backFaceCulling);var a=n._getInstancesRenderList(t._id);if(!a.mustReturn&&!r._excludedMeshes[n.id]){var h=null!==s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id]&&void 0!==a.visibleInstances[t._id],c=r._meshes[n.id],l=t.getMaterial(),u=null;if(c&&c.glowEmissiveOnly&&l&&(u=l.emissiveTexture),r.isReady(t,h,u)){if(s.enableEffect(r._glowMapGenerationEffect),n._bind(t,r._glowMapGenerationEffect,e.Material.TriangleFillMode),r._glowMapGenerationEffect.setMatrix("viewProjection",o.getTransformMatrix()),c?r._glowMapGenerationEffect.setFloat4("color",c.color.r,c.color.g,c.color.b,1):r._glowMapGenerationEffect.setFloat4("color",i.neutralColor.r,i.neutralColor.g,i.neutralColor.b,i.neutralColor.a),l&&l.needAlphaTesting()){var d=l.getAlphaTestTexture();r._glowMapGenerationEffect.setTexture("diffuseSampler",d),r._glowMapGenerationEffect.setMatrix("diffuseMatrix",d.getTextureMatrix())}u&&(r._glowMapGenerationEffect.setTexture("emissiveSampler",u),r._glowMapGenerationEffect.setMatrix("emissiveMatrix",u.getTextureMatrix())),n.useBones&&n.computeBonesUsingShaders&&r._glowMapGenerationEffect.setMatrices("mBones",n.skeleton.getTransformMatrices(n)),n._processRendering(t,r._glowMapGenerationEffect,e.Material.TriangleFillMode,a,h,(function(e,t){return r._glowMapGenerationEffect.setMatrix("world",t)}))}else r._mainTexture.resetRefreshCounter()}};this._mainTexture.customRenderFunction=function(e,t,i){r.onBeforeRenderMainTextureObservable.notifyObservers(r);var n;for(n=0;n<e.length;n++)s(e.data[n]);for(n=0;n<t.length;n++)s(t.data[n]);for(n=0;n<i.length;n++)s(i.data[n])},this._mainTexture.onClearObservable.add((function(e){e.clear(i.neutralColor,!0,!0,!0)}))},i.prototype.isReady=function(t,i,r){if(!t.getMaterial().isReady(t.getMesh(),i))return!1;var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMesh(),a=t.getMaterial(),h=!1,c=!1;if(a&&a.needAlphaTesting()){var l=a.getAlphaTestTexture();l&&(n.push("#define ALPHATEST"),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===l.coordinatesIndex?(n.push("#define DIFFUSEUV2"),c=!0):s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push("#define DIFFUSEUV1"),h=!0))}r&&(n.push("#define EMISSIVE"),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===r.coordinatesIndex?(n.push("#define EMISSIVEUV2"),c=!0):s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push("#define EMISSIVEUV1"),h=!0)),h&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),c&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2")),s.useBones&&s.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),s.numBoneInfluencers>4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var u=n.join("\n");return this._cachedDefines!==u&&(this._cachedDefines=u,this._glowMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",o,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix"],["diffuseSampler","emissiveSampler"],u)),this._glowMapGenerationEffect.isReady()},i.prototype.render=function(){var t=this._glowMapMergeEffect;if(t.isReady()&&this._blurTexture.isReady()){var i=this._scene.getEngine();this.onBeforeComposeObservable.notifyObservers(this),i.enableEffect(t),i.setState(!1);var r=i.getStencilBuffer(),n=i.getStencilFunction(),o=i.getStencilMask(),s=i.getAlphaMode();t.setTexture("textureSampler",this._blurTexture),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t),i.setAlphaMode(this._options.alphaBlendingMode),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&(t.setFloat("offset",0),i.setStencilFunction(e.Engine.NOTEQUAL),i.draw(!0,0,6)),this.innerGlow&&(t.setFloat("offset",1),i.setStencilFunction(e.Engine.EQUAL),i.draw(!0,0,6)),i.setStencilFunction(n),i.setStencilMask(o),i.setAlphaMode(s),i.setStencilBuffer(r),this.onAfterComposeObservable.notifyObservers(this);var a=this._mainTexture.getSize();this.setMainTextureSize(),a.width===this._mainTextureDesiredSize.width&&a.height===this._mainTextureDesiredSize.height||(this.onSizeChangedObservable.notifyObservers(this),this.disposeTextureAndPostProcesses(),this.createTextureAndPostProcesses())}},i.prototype.addExcludedMesh=function(e){var t=this._excludedMeshes[e.id];t||(this._excludedMeshes[e.id]={mesh:e,beforeRender:e.onBeforeRenderObservable.add((function(e){e.getEngine().setStencilBuffer(!1)})),afterRender:e.onAfterRenderObservable.add((function(e){e.getEngine().setStencilBuffer(!0)}))})},i.prototype.removeExcludedMesh=function(e){var t=this._excludedMeshes[e.id];t&&(e.onBeforeRenderObservable.remove(t.beforeRender),e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.id]=void 0},i.prototype.addMesh=function(e,t,i){var r=this;void 0===i&&(i=!1);var n=this._meshes[e.id];n?n.color=t:this._meshes[e.id]={mesh:e,color:t,observerHighlight:e.onBeforeRenderObservable.add((function(e){r._excludedMeshes[e.id]?r.defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(r._instanceGlowingMeshStencilReference)})),observerDefault:e.onAfterRenderObservable.add(this.defaultStencilReference),glowEmissiveOnly:i},this._shouldRender=!0},i.prototype.removeMesh=function(e){var t=this._meshes[e.id];t&&(e.onBeforeRenderObservable.remove(t.observerHighlight),e.onAfterRenderObservable.remove(t.observerDefault)),this._meshes[e.id]=void 0,this._shouldRender=!1;for(var i in this._meshes)if(i){this._shouldRender=!0;break}},i.prototype.shouldRender=function(){return this.isEnabled&&this._shouldRender},i.prototype.setMainTextureSize=function(){this._options.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._options.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._options.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderingCanvas().width*this._options.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderingCanvas().height*this._options.mainTextureRatio,this._mainTextureDesiredSize.width=e.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize),this._mainTextureDesiredSize.height=e.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize))},i.prototype.defaultStencilReference=function(e){e.getScene().getEngine().setStencilFunctionReference(i.normalMeshStencilReference)},i.prototype.disposeTextureAndPostProcesses=function(){this._blurTexture.dispose(),this._mainTexture.dispose(),this._downSamplePostprocess.dispose(),this._horizontalBlurPostprocess.dispose(),this._verticalBlurPostprocess.dispose()},i.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.disposeTextureAndPostProcesses();for(var i in this._meshes){var r=this._meshes[i];r&&r.mesh&&(r.mesh.onBeforeRenderObservable.remove(r.observerHighlight),r.mesh.onAfterRenderObservable.remove(r.observerDefault))}this._meshes=null;for(var i in this._excludedMeshes){var r=this._excludedMeshes[i];r&&(r.mesh.onBeforeRenderObservable.remove(r.beforeRender),r.mesh.onAfterRenderObservable.remove(r.afterRender))}this._excludedMeshes=null;var n=this._scene.highlightLayers.indexOf(this,0);n>-1&&this._scene.highlightLayers.splice(n,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeBlurObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},i.neutralColor=new e.Color4(0,0,0,0),i.glowingMeshStencilReference=2,i.normalMeshStencilReference=1,i})();e.HighlightLayer=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e.TransformCoordinatesToRefSIMD=function(t,i,r){e.TransformCoordinatesFromFloatsToRefSIMD(t.x,t.y,t.z,i,r)},e.TransformCoordinatesFromFloatsToRefSIMD=function(e,t,i,r,n){var o=r.m,s=SIMD.Float32x4.load(o,0),a=SIMD.Float32x4.load(o,4),h=SIMD.Float32x4.load(o,8),c=SIMD.Float32x4.load(o,12),l=SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(e),s),SIMD.Float32x4.mul(SIMD.Float32x4.splat(t),a)),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(i),h),c));l=SIMD.Float32x4.div(l,SIMD.Float32x4.swizzle(l,3,3,3,3)),n.x=SIMD.Float32x4.extractLane(l,0),n.y=SIMD.Float32x4.extractLane(l,1),n.z=SIMD.Float32x4.extractLane(l,2)},e})(),i=(function(){function e(){}return e.prototype.multiplyToArraySIMD=function(e,t,i){for(var r=this.m,n=e.m,o=SIMD.Float32x4.load(n,0),s=SIMD.Float32x4.load(n,4),a=SIMD.Float32x4.load(n,8),h=SIMD.Float32x4.load(n,12),c=0;c<16;c+=4)SIMD.Float32x4.store(t,c+i,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c]),o),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c+1]),s),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c+2]),a),SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c+3]),h)))));return this},e.prototype.invertToRefSIMD=function(e){var t=this.m,i=e.m,r=SIMD.Float32x4.load(t,0),n=SIMD.Float32x4.load(t,4),o=SIMD.Float32x4.load(t,8),s=SIMD.Float32x4.load(t,12),a=SIMD.Float32x4.shuffle(r,n,0,1,4,5),h=SIMD.Float32x4.shuffle(o,s,0,1,4,5),c=SIMD.Float32x4.shuffle(a,h,0,2,4,6);h=SIMD.Float32x4.shuffle(h,a,1,3,5,7),a=SIMD.Float32x4.shuffle(r,n,2,3,6,7);var l=SIMD.Float32x4.shuffle(o,s,2,3,6,7),u=SIMD.Float32x4.shuffle(a,l,0,2,4,6);l=SIMD.Float32x4.shuffle(l,a,1,3,5,7),a=SIMD.Float32x4.mul(u,l),a=SIMD.Float32x4.swizzle(a,1,0,3,2);var d=SIMD.Float32x4.mul(h,a),f=SIMD.Float32x4.mul(c,a);a=SIMD.Float32x4.swizzle(a,2,3,0,1),d=SIMD.Float32x4.sub(SIMD.Float32x4.mul(h,a),d),f=SIMD.Float32x4.sub(SIMD.Float32x4.mul(c,a),f),f=SIMD.Float32x4.swizzle(f,2,3,0,1),a=SIMD.Float32x4.mul(h,u),a=SIMD.Float32x4.swizzle(a,1,0,3,2),d=SIMD.Float32x4.add(SIMD.Float32x4.mul(l,a),d);var p=SIMD.Float32x4.mul(c,a);a=SIMD.Float32x4.swizzle(a,2,3,0,1),d=SIMD.Float32x4.sub(d,SIMD.Float32x4.mul(l,a)),p=SIMD.Float32x4.sub(SIMD.Float32x4.mul(c,a),p),p=SIMD.Float32x4.swizzle(p,2,3,0,1),a=SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(h,2,3,0,1),l),a=SIMD.Float32x4.swizzle(a,1,0,3,2),u=SIMD.Float32x4.swizzle(u,2,3,0,1),d=SIMD.Float32x4.add(SIMD.Float32x4.mul(u,a),d);var m=SIMD.Float32x4.mul(c,a);a=SIMD.Float32x4.swizzle(a,2,3,0,1),d=SIMD.Float32x4.sub(d,SIMD.Float32x4.mul(u,a)),m=SIMD.Float32x4.sub(SIMD.Float32x4.mul(c,a),m),m=SIMD.Float32x4.swizzle(m,2,3,0,1),a=SIMD.Float32x4.mul(c,h),a=SIMD.Float32x4.swizzle(a,1,0,3,2),m=SIMD.Float32x4.add(SIMD.Float32x4.mul(l,a),m),p=SIMD.Float32x4.sub(SIMD.Float32x4.mul(u,a),p),a=SIMD.Float32x4.swizzle(a,2,3,0,1),m=SIMD.Float32x4.sub(SIMD.Float32x4.mul(l,a),m),p=SIMD.Float32x4.sub(p,SIMD.Float32x4.mul(u,a)),a=SIMD.Float32x4.mul(c,l),a=SIMD.Float32x4.swizzle(a,1,0,3,2),f=SIMD.Float32x4.sub(f,SIMD.Float32x4.mul(u,a)),m=SIMD.Float32x4.add(SIMD.Float32x4.mul(h,a),m),a=SIMD.Float32x4.swizzle(a,2,3,0,1),f=SIMD.Float32x4.add(SIMD.Float32x4.mul(u,a),f),m=SIMD.Float32x4.sub(m,SIMD.Float32x4.mul(h,a)),a=SIMD.Float32x4.mul(c,u),a=SIMD.Float32x4.swizzle(a,1,0,3,2),f=SIMD.Float32x4.add(SIMD.Float32x4.mul(l,a),f),p=SIMD.Float32x4.sub(p,SIMD.Float32x4.mul(h,a)),a=SIMD.Float32x4.swizzle(a,2,3,0,1),f=SIMD.Float32x4.sub(f,SIMD.Float32x4.mul(l,a)),p=SIMD.Float32x4.add(SIMD.Float32x4.mul(h,a),p);var _=SIMD.Float32x4.mul(c,d);return _=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(_,2,3,0,1),_),_=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(_,1,0,3,2),_),a=SIMD.Float32x4.reciprocalApproximation(_),_=SIMD.Float32x4.sub(SIMD.Float32x4.add(a,a),SIMD.Float32x4.mul(_,SIMD.Float32x4.mul(a,a))),_=SIMD.Float32x4.swizzle(_,0,0,0,0),SIMD.Float32x4.store(i,0,SIMD.Float32x4.mul(_,d)),SIMD.Float32x4.store(i,4,SIMD.Float32x4.mul(_,f)),SIMD.Float32x4.store(i,8,m=SIMD.Float32x4.mul(_,m)),SIMD.Float32x4.store(i,12,SIMD.Float32x4.mul(_,p)),this},e.LookAtLHToRefSIMD=function(e,t,i,r){var n=r.m,o=SIMD.Float32x4(t.x,t.y,t.z,0),s=SIMD.Float32x4(e.x,e.y,e.z,0),a=SIMD.Float32x4(i.x,i.y,i.z,0),h=SIMD.Float32x4.sub(o,s),c=SIMD.Float32x4.mul(h,h);c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),h=SIMD.Float32x4.mul(h,SIMD.Float32x4.reciprocalSqrtApproximation(c)),c=SIMD.Float32x4.mul(a,a),c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),a=SIMD.Float32x4.mul(a,SIMD.Float32x4.reciprocalSqrtApproximation(c));var l=SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(h,1,2,0,3),SIMD.Float32x4.swizzle(a,2,0,1,3)),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(h,2,0,1,3),SIMD.Float32x4.swizzle(a,1,2,0,3)));c=SIMD.Float32x4.mul(l,l),c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),l=SIMD.Float32x4.mul(l,SIMD.Float32x4.reciprocalSqrtApproximation(c));var u=SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(l,1,2,0,3),SIMD.Float32x4.swizzle(h,2,0,1,3)),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(l,2,0,1,3),SIMD.Float32x4.swizzle(h,1,2,0,3)));c=SIMD.Float32x4.mul(l,l),c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),l=SIMD.Float32x4.mul(l,SIMD.Float32x4.reciprocalSqrtApproximation(c));var d=SIMD.Float32x4.splat(0);l=SIMD.Float32x4.neg(l);var f=SIMD.Float32x4.shuffle(l,u,0,1,4,5),p=SIMD.Float32x4.shuffle(h,d,0,1,4,5),m=SIMD.Float32x4.shuffle(f,p,0,2,4,6),_=SIMD.Float32x4.shuffle(f,p,1,3,5,7),g=SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(l,u,2,3,6,7),SIMD.Float32x4.shuffle(h,d,2,3,6,7),0,2,4,6),v=SIMD.Float32x4(0,0,0,1),y=SIMD.Float32x4(1,0,0,0);SIMD.Float32x4.store(n,0,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v))))),y=SIMD.Float32x4(0,1,0,0),SIMD.Float32x4.store(n,4,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v))))),y=SIMD.Float32x4(0,0,1,0),SIMD.Float32x4.store(n,8,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v))))),y=SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(s),3,1),SIMD.Float32x4.store(n,12,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v)))))},e})(),r=e.Matrix.prototype.multiplyToArray,n=e.Matrix.prototype.invertToRef,o=e.Matrix.LookAtLHToRef,s=e.Vector3.TransformCoordinatesToRef,a=e.Vector3.TransformCoordinatesFromFloatsToRef,h=(function(){function h(){}return Object.defineProperty(h,"IsEnabled",{get:function(){return h._isEnabled},enumerable:!0,configurable:!0}),h.DisableSIMD=function(){e.Matrix.prototype.multiplyToArray=r,e.Matrix.prototype.invertToRef=n,e.Matrix.LookAtLHToRef=o,e.Vector3.TransformCoordinatesToRef=s,e.Vector3.TransformCoordinatesFromFloatsToRef=a,h._isEnabled=!1},h.EnableSIMD=function(){void 0!==self.SIMD&&(self.Math.fround||(self.Math.fround=(function(e){return function(t){return e[0]=t,e[0]}})(new Float32Array(1))),self.Math.imul||(self.Math.imul=function(e,t){var i=e>>>16&65535,r=65535&e,n=t>>>16&65535,o=65535&t;return r*o+(i*o+r*n<<16>>>0)|0}),e.Matrix.prototype.multiplyToArray=i.prototype.multiplyToArraySIMD,e.Matrix.prototype.invertToRef=i.prototype.invertToRefSIMD,e.Matrix.LookAtLHToRef=i.LookAtLHToRefSIMD,e.Vector3.TransformCoordinatesToRef=t.TransformCoordinatesToRefSIMD,e.Vector3.TransformCoordinatesFromFloatsToRef=t.TransformCoordinatesFromFloatsToRefSIMD,h._isEnabled=!0)},h._isEnabled=!1,h})();e.SIMDHelper=h})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this._pos=i,this._size=r,this._root=e,this._parent=t,this._contentSize=null,this._bottomNode=null,this._leftNode=null,this._initialSize=null,this._rightNode=null}return Object.defineProperty(t.prototype,"pos",{get:function(){return this._pos},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"contentSize",{get:function(){return this._contentSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"UVs",{get:function(){return this.getUVsForCustomSize(this._root._size)},enumerable:!0,configurable:!0}),t.prototype.getUVsForCustomSize=function(t){var i=this._root._size.width,r=this._root._size.height,n=new e.Vector2(this._pos.x/i,this._pos.y/r),o=new e.Vector2((this._pos.x+t.width-1)/i,(this._pos.y+t.height-1)/r),s=new Array;return s.push(n),s.push(new e.Vector2(o.x,n.y)),s.push(o),s.push(new e.Vector2(n.x,o.y)),s},t.prototype.freeContent=function(){this.contentSize&&(this._contentSize=null,this.attemptDefrag())},Object.defineProperty(t.prototype,"isUsed",{get:function(){return null!=this._contentSize||null!=this._leftNode},enumerable:!0,configurable:!0}),t.prototype.findAndSplitNode=function(e){var t=this.findNode(e);return t?(t.splitNode(e),t):null},t.prototype.findNode=function(e){var t=null;if(this.isUsed)this._leftNode&&(t=this._leftNode.findNode(e)),!t&&this._rightNode&&(t=this._rightNode.findNode(e)),!t&&this._bottomNode&&(t=this._bottomNode.findNode(e));else if(this._initialSize){if(!(e.width<=this._initialSize.width&&e.height<=this._initialSize.height))return null;t=this}else e.width<=this._size.width&&e.height<=this._size.height&&(t=this);return t},t.prototype.splitNode=function(i){return!this._contentSize&&this._initialSize?(this._contentSize=i.clone(),this._leftNode=new t(this._root,this,new e.Vector2(this._pos.x,this._pos.y),new e.Size(this._initialSize.width,this._initialSize.height)),this._leftNode.splitNode(i)):(this._contentSize=i.clone(),this._initialSize=i.clone(),i.width!==this._size.width&&(this._rightNode=new t(this._root,this,new e.Vector2(this._pos.x+i.width,this._pos.y),new e.Size(this._size.width-i.width,i.height))),i.height!==this._size.height&&(this._bottomNode=new t(this._root,this,new e.Vector2(this._pos.x,this._pos.y+i.height),new e.Size(this._size.width,this._size.height-i.height))),this)},t.prototype.attemptDefrag=function(){!this.isUsed&&this.isRecursiveFree&&(this.clearNode(),this._parent&&this._parent.attemptDefrag())},t.prototype.clearNode=function(){this._initialSize=null,this._rightNode=null,this._bottomNode=null},Object.defineProperty(t.prototype,"isRecursiveFree",{get:function(){return!this.contentSize&&(!this._leftNode||this._leftNode.isRecursiveFree)&&(!this._rightNode||this._rightNode.isRecursiveFree)&&(!this._bottomNode||this._bottomNode.isRecursiveFree)},enumerable:!0,configurable:!0}),t.prototype.evalFreeSize=function(e){var t=0;return this.isUsed||(t=this._initialSize?this._initialSize.surface:this._size.surface),this._rightNode&&(t+=this._rightNode.evalFreeSize(0)),this._bottomNode&&(t+=this._bottomNode.evalFreeSize(0)),t+e},t})();e.PackedRect=t;var i=(function(t){function i(i){t.call(this,null,null,e.Vector2.Zero(),i),this._root=this}return __extends(i,t),i.prototype.addRect=function(e){var t=this.findAndSplitNode(e);return t},Object.defineProperty(i.prototype,"freeSpace",{get:function(){var e=0;return e=this.evalFreeSize(e),e/(this._size.width*this._size.height)},enumerable:!0,configurable:!0}),i})(t);e.RectPackingMap=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e})();e.DynamicFloatArrayElementInfo=t;var i=(function(){function e(e,i){this.compareValueOffset=null,this.sortingAscending=!0,this._stride=e,this.buffer=new Float32Array(e*i),this._lastUsed=0,this._firstFree=0,this._allEntries=new Array(i),this._freeEntries=new Array(i);for(var r=0;r<i;r++){var n=new t;n.offset=r*e,this._allEntries[r]=n,this._freeEntries[i-r-1]=n}}return e.prototype.allocElement=function(){0===this._freeEntries.length&&this._growBuffer();var e=this._freeEntries.pop();return this._lastUsed=Math.max(e.offset,this._lastUsed),e.offset===this._firstFree&&(this._freeEntries.length>0?this._firstFree=this._freeEntries[this._freeEntries.length-1].offset:this._firstFree+=this._stride),e},e.prototype.freeElement=function(e){this._firstFree=Math.min(e.offset,this._firstFree),this._freeEntries.push(e)},e.prototype.pack=function(){if(0===this._freeEntries.length)return this.buffer;if(this._lastUsed<this._firstFree){var e=this.buffer.subarray(0,this._lastUsed+this._stride);return e}var i=this._stride,r=new t;r.offset=this.totalElementCount*i,this._freeEntries.push(r);for(var n=this._freeEntries.sort((function(e,t){return e.offset-t.offset})),o=this._allEntries.sort((function(e,t){return e.offset-t.offset})),s=n[0].offset,a=1,h=(this.usedElementCount+1)*i,c=n[0].offset,l=1;l<n.length&&!(s>=h);l++){var u=n[l],d=u.offset,f=d-c;if(f!==i){for(var p=f/i-1,m=d-i,_=Math.min(a,p),g=0;g<_;g++){var v=s/i,y=m/i,x=o[y];this._moveElement(x,s);var b=o[v];b.offset=m,o[v]=x,o[y]=b,m-=i,s+=i}a<=p?(s=m+i,a=1+_):a=(d-s)/i+1,c=d}else++a,c=d}var T=this.buffer.subarray(0,s);return this._lastUsed=s-i,this._firstFree=s,n.pop(),this._freeEntries=n.sort((function(e,t){return t.offset-e.offset})),this._allEntries=o,T},e.prototype._moveElement=function(e,t){for(var i=0;i<this._stride;i++)this.buffer[t+i]=this.buffer[e.offset+i];e.offset=t},e.prototype._growBuffer=function(){var e=Math.floor(1.5*this.totalElementCount),i=new Float32Array(e*this._stride);i.set(this.buffer);for(var r=this.totalElementCount,n=e-this.totalElementCount,o=0;o<n;o++){var s=new t;s.offset=(r+o)*this.stride,this._allEntries.push(s),this._freeEntries[n-o-1]=s}this._firstFree=r*this.stride,this.buffer=i},Object.defineProperty(e.prototype,"totalElementCount",{get:function(){return this._allEntries.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"freeElementCount",{get:function(){return this._freeEntries.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"usedElementCount",{get:function(){return this._allEntries.length-this._freeEntries.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stride",{get:function(){return this._stride},enumerable:!0,configurable:!0}),e.prototype.sort=function(){var e=this;if(!this.compareValueOffset)throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");var t=this.usedElementCount;if(!this._sortTable||this._sortTable.length<t){var i=Math.min(this.totalElementCount,2*t);this._sortTable=new Array(i)}this._sortedTable&&this._sortedTable.length===t||(this._sortedTable=new Array(t)),this.pack();for(var n=0,o=this.stride,s=0;s<t;s++,n+=o){var a=this._sortTable[s];a||(a=new r,this._sortTable[s]=a),a.compareData=this.buffer[n+this.compareValueOffset],a.offset=n,a.swapedOffset=null,this._sortedTable[s]=a}this.sortingAscending?this._sortedTable.sort((function(e,t){return e.compareData-t.compareData})):this._sortedTable.sort((function(e,t){return t.compareData-e.compareData}));for(var h=function(t,i){for(var r=0;r<o;r++){var n=e.buffer[i+r];e.buffer[i+r]=e.buffer[t+r],e.buffer[t+r]=n}},s=0;s<t;s++){var c=this._sortedTable[s],l=this._sortTable[s],u=c.offset;if(c.swapedOffset){for(var d=c;d.swapedOffset;)d=this._sortTable[d.swapedOffset/o];u=d.offset}l.swapedOffset=u,u!==l.offset&&h(u,l.offset),this._allEntries[c.offset/o].offset=l.offset}return this._allEntries.sort((function(e,t){return e.offset-t.offset})),!0},e})();e.DynamicFloatArray=i;var r=(function(){function e(){this.compareData=this.offset=this.swapedOffset=null}return e})()})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e})();e.CharInfo=t;var i=(function(i){function r(t,r,n,o,s,a,h){if(void 0===o&&(o=200),void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=!1),void 0===h&&(h=!1),i.call(this,null,n,!0,!1,s),this._charInfos={},this._curCharCount=0,this._lastUpdateCharCount=-1,this._usedCounter=1,this.name=t,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._sdfScale=8,this._signedDistanceField=h,this._superSample=!1,a||h){var c=this.getSuperSampleFont(r);c&&(this._superSample=!0,r=c)}this._canvas=document.createElement("canvas"),this._context=this._canvas.getContext("2d"),this._context.font=r,this._context.fillStyle="white",
this._context.textBaseline="top",this._cachedFontId=null;var l=this.getFontHeight(r);this._lineHeightSuper=l.height+4,this._lineHeight=this._superSample?Math.ceil(this._lineHeightSuper/2):this._lineHeightSuper,this._offset=l.offset-1,this._xMargin=1+Math.ceil(this._lineHeightSuper/15),this._yMargin=this._xMargin;var u=this._context.measureText("W").width;this._spaceWidthSuper=this._context.measureText(" ").width,this._spaceWidth=this._superSample?this._spaceWidthSuper/2:this._spaceWidthSuper;var d=(this._lineHeightSuper+this._yMargin)*(u+this._xMargin)*o,f=Math.sqrt(d),p=Math.pow(2,Math.ceil(Math.log(f)/Math.log(2)));this._texture=n.getEngine().createDynamicTexture(p,p,!1,s);var m=this.getSize();if(this.hasAlpha=this._signedDistanceField===!1,this._canvas=document.createElement("canvas"),this._canvas.width=m.width,this._canvas.height=m.height,this._context=this._canvas.getContext("2d"),this._context.textBaseline="top",this._context.font=r,this._context.fillStyle="white",this._context.imageSmoothingEnabled=!1,this._context.clearRect(0,0,m.width,m.height),this._signedDistanceField){var _=document.createElement("canvas"),g=this._sdfScale;_.width=u*g,_.height=this._lineHeightSuper*g;var v=_.getContext("2d");v.scale(g,g),v.textBaseline="top",v.font=r,v.fillStyle="white",v.imageSmoothingEnabled=!1,this._sdfCanvas=_,this._sdfContext=v}this._currentFreePosition=e.Vector2.Zero();for(var y=32;y<127;y++){var x=String.fromCharCode(y);this.getChar(x)}this.update()}return __extends(r,i),Object.defineProperty(r.prototype,"isSuperSampled",{get:function(){return this._superSample},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"isSignedDistanceField",{get:function(){return this._signedDistanceField},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"spaceWidth",{get:function(){return this._spaceWidth},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"lineHeight",{get:function(){return this._lineHeight},enumerable:!0,configurable:!0}),r.GetCachedFontTexture=function(t,i,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var s=t;s.__fontTextureCache__||(s.__fontTextureCache__=new e.StringDictionary);var a=s.__fontTextureCache__,h=i.toLocaleLowerCase()+(n?"_+SS":"_-SS")+(o?"_+SDF":"_-SDF"),c=a.get(h);return c?(++c._usedCounter,c):(c=new r(null,i,t,n?100:200,e.Texture.BILINEAR_SAMPLINGMODE,n,o),c._cachedFontId=h,a.add(h,c),c)},r.ReleaseCachedFontTexture=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n=e,o=n.__fontTextureCache__;if(o){var s=t.toLocaleLowerCase()+(i?"_+SS":"_-SS")+(r?"_+SDF":"_-SDF"),a=o.get(s);0===--a._usedCounter&&(o.remove(s),a.dispose())}},r.prototype.getChar=function(i){if(1!==i.length)return null;var r=this._charInfos[i];if(r)return r;r=new t;var n=this._context.measureText(i),o=this.getSize(),s=Math.round(n.width);if(this._currentFreePosition.x+s+this._xMargin>o.width&&(this._currentFreePosition.x=0,this._currentFreePosition.y+=this._lineHeightSuper+this._yMargin,this._currentFreePosition.y>o.height))return this.getChar("!");if(this._signedDistanceField){this._sdfContext.clearRect(0,0,this._sdfCanvas.width,this._sdfCanvas.height),this._sdfContext.fillText(i,0,-this._offset);var a=this._sdfContext.getImageData(0,0,s*this._sdfScale,this._sdfCanvas.height),h=this._computeSDFChar(a);this._context.putImageData(h,this._currentFreePosition.x,this._currentFreePosition.y)}else this._context.fillText(i,this._currentFreePosition.x,this._currentFreePosition.y-this._offset);if(r.topLeftUV=new e.Vector2(this._currentFreePosition.x/o.width,this._currentFreePosition.y/o.height),r.bottomRightUV=new e.Vector2((this._currentFreePosition.x+s)/o.width,r.topLeftUV.y+(this._lineHeightSuper+2)/o.height),this._signedDistanceField){var c=1/o.width;r.topLeftUV.addInPlace(new e.Vector2(c,c)),r.bottomRightUV.addInPlace(new e.Vector2(c,c))}return r.charWidth=this._superSample?s/2:s,this._charInfos[i]=r,this._curCharCount++,this._currentFreePosition.x+=s+this._xMargin,r},r.prototype._computeSDFChar=function(e){for(var t=this._sdfScale,i=e.width,r=e.height,n=i/t,o=r/t,s=0,a=0,h=t,c=h-1,l=function(n,o,h,c,l){var u=n*t,d=o*t;if(u+h<0||u+h>=i||d+c<0||d+c>=r)return!0;var f=e.data[4*((d+c)*i+(u+h))],p=f>0===l;return p||(s=h,a=c),p},u=function(e,t,i){if(l(e,t,0,c,i)&&l(e,t,0,-c,i)&&l(e,t,-c,0,i)&&l(e,t,c,0,i))return 0;for(var r=1;r<=h;r++){if(!(l(e,t,0,r,i)&&l(e,t,0,-r,i)&&l(e,t,-r,0,i)&&l(e,t,r,0,i)))return r*r;for(var n=1;n<=r;n++)if(!(l(e,t,-n,r,i)&&l(e,t,n,r,i)&&l(e,t,r,-n,i)&&l(e,t,r,n,i)&&l(e,t,-n,-r,i)&&l(e,t,n,-r,i)&&l(e,t,-r,-n,i)&&l(e,t,-r,n,i))){var o=r*r+n*n,u=1;return l(e,t,s-1,a,i)||(o+=(s-1)*(s-1)+a*a,++u),l(e,t,s+1,a,i)||(o+=(s+1)*(s+1)+a*a,++u),l(e,t,s,a-1,i)||(o+=s*s+(a-1)*(a-1),++u),l(e,t,s,a+1,i)||(o+=s*s+(a+1)*(a+1),++u),l(e,t,s-1,a-1,i)||(o+=(s-1)*(s-1)+(a-1)*(a-1),++u),l(e,t,s+1,a+1,i)||(o+=(s+1)*(s+1)+(a+1)*(a+1),++u),l(e,t,s+1,a-1,i)||(o+=(s+1)*(s+1)+(a-1)*(a-1),++u),l(e,t,s-1,a+1,i)||(o+=(s-1)*(s-1)+(a+1)*(a+1),++u),o/u}}return 0},d=new Array(n*o),f=0;f<o;f++)for(var p=0;p<n;p++){var m=l(p,f,0,0,!0),_=u(p,f,m);0===_&&(_=h*h*2),d[f*n+p]=m?_:-_}for(var g=this._context.createImageData(n,o),v=n*o,y=0;y<v;y++){var _=d[y],x=_<0?-1:1;_=Math.sqrt(Math.abs(_))*x,_*=127.5/h,_+=127.5,_<0?_=0:_>255&&(_=255),_+=.5,g.data[4*y+0]=_,g.data[4*y+1]=_,g.data[4*y+2]=_,g.data[4*y+3]=255}return g},r.prototype.measureText=function(t,i){void 0===i&&(i=4);for(var r=0,n=0,o=1,s=0,a=0,h=t;a<h.length;a++){var c=h[a];if("\n"!==c)if("\t"!==c)c<" "||(n+=this.getChar(c).charWidth,++s);else{var l=s+i;l-=l%i,n+=(l-s)*this.spaceWidth,s=l}else r=Math.max(r,n),s=0,n=0,++o}return r=Math.max(r,n),new e.Size(r,o*this.lineHeight)},r.prototype.getSuperSampleFont=function(e){var t=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/,i=e.toLocaleLowerCase().match(t);if(null==i)return null;var r=parseInt(i[4]);i[4]=(2*r).toString()+(i[4].match(/\D+/)||[]).pop();for(var n="",o=1;o<i.length;o++)null!=i[o]&&(n+=i[o]+" ");return n},r.prototype.getFontHeight=function(e){var t=document.createElement("canvas"),i=t.getContext("2d");i.fillRect(0,0,t.width,t.height),i.textBaseline="top",i.fillStyle="white",i.font=e,i.fillText("jH|",0,0);for(var r=i.getImageData(0,0,t.width,t.height).data,n=-1,o=-1,s=0;s<t.height;s++)for(var a=0;a<t.width;a++){var h=4*(s*t.width+a);{if(0!==r[h]){n===-1&&(n=s);break}if(a===t.width-1&&n!==-1){o=s,s=t.height;break}}}return{height:o-n+1,offset:n-1}},Object.defineProperty(r.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),r.prototype.getContext=function(){return this._context},r.prototype.update=function(){this._lastUpdateCharCount<this._curCharCount&&(this.getScene().getEngine().updateDynamicTexture(this._texture,this._canvas,!1,!0),this._lastUpdateCharCount=this._curCharCount)},r.prototype.clone=function(){return null},r.prototype.incCachedFontTextureCounter=function(){++this._usedCounter},r.prototype.decCachedFontTextureCounter=function(){var e=this.getScene(),t=e.__fontTextureCache__;t&&0===--this._usedCounter&&(t.remove(this._cachedFontId),this.dispose())},r})(e.Texture);e.FontTexture=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=!1),t.call(this,null,r,!s,!1,o),this.name=i,this._size=n,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._rectPackingMap=new e.RectPackingMap(new e.Size(n.width,n.height)),this._texture=r.getEngine().createRenderTargetTexture(n,{generateMipMaps:!this.noMipmap,type:e.Engine.TEXTURETYPE_UNSIGNED_INT})}return __extends(i,t),i.prototype.allocateRect=function(e){return this._rectPackingMap.addRect(e)},i.prototype.freeRect=function(e){e&&e.freeContent()},Object.defineProperty(i.prototype,"freeSpace",{get:function(){return this._rectPackingMap.freeSpace},enumerable:!0,configurable:!0}),i.prototype.bindTextureForRect=function(e,t){return this.bindTextureForPosSize(e.pos,e.contentSize,t)},i.prototype.bindTextureForPosSize=function(t,i,r){var n=this.getScene().getEngine();n.bindFramebuffer(this._texture),this._replacedViewport=n.setDirectViewport(t.x,t.y,i.width,i.height),r&&n.scissorClear(t.x,t.y,i.width,i.height,new e.Color4(0,0,0,0))},i.prototype.unbindTexture=function(t){t&&e.Tools.DumpFramebuffer(this._size.width,this._size.height,this.getScene().getEngine());var i=this.getScene().getEngine();this._replacedViewport&&(i.setViewport(this._replacedViewport),this._replacedViewport=null),i.unBindFramebuffer(this._texture)},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.clone=function(){return null},i})(e.Texture);e.MapTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){t.call(this,i,r),this._textures={},this._textureArrays={},this._floats={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._matrices3x3={},this._matrices2x2={},this._vectors3Arrays={},this._cachedWorldViewMatrix=new e.Matrix,this._shaderPath=n,o.needAlphaBlending=o.needAlphaBlending||!1,o.needAlphaTesting=o.needAlphaTesting||!1,o.attributes=o.attributes||["position","normal","uv"],o.uniforms=o.uniforms||["worldViewProjection"],o.samplers=o.samplers||[],o.defines=o.defines||[],this._options=o}return __extends(i,t),i.prototype.needAlphaBlending=function(){return this._options.needAlphaBlending},i.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting},i.prototype._checkUniform=function(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)},i.prototype.setTexture=function(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this},i.prototype.setTextureArray=function(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setVector4=function(e,t){return this._checkUniform(e),this._vectors4[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.setMatrix3x3=function(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this},i.prototype.setMatrix2x2=function(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this},i.prototype.setArray3=function(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this},i.prototype._checkCache=function(e,t,i){return!t||(this._effect&&this._effect.defines.indexOf("#define INSTANCES")!==-1!==i,!1)},i.prototype.isReady=function(t,i){var r=this.getScene(),n=r.getEngine();if(!this.checkReadyOnEveryCall&&this._renderId===r.getRenderId()&&this._checkCache(r,t,i))return!0;var o=[],s=new e.EffectFallbacks;i&&o.push("#define INSTANCES");for(var a=0;a<this._options.defines.length;a++)o.push(this._options.defines[a]);t&&t.useBones&&t.computeBonesUsingShaders&&(o.push("#define NUM_BONE_INFLUENCERS "+t.numBoneInfluencers),o.push("#define BonesPerMesh "+(t.skeleton.bones.length+1)),s.addCPUSkinningFallback(0,t)),n.getAlphaTesting()&&o.push("#define ALPHATEST");var h=this._effect,c=o.join("\n");return this._effect=n.createEffect(this._shaderPath,this._options.attributes,this._options.uniforms,this._options.samplers,c,s,this.onCompiled,this.onError),!!this._effect.isReady()&&(h!==this._effect&&r.resetCachedMaterial(),this._renderId=r.getRenderId(),!0)},i.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._options.uniforms.indexOf("world")!==-1&&this._effect.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&this._effect.setMatrix("worldViewProjection",e.multiply(t.getTransformMatrix()))},i.prototype.bind=function(i,r){if(this.bindOnlyWorldMatrix(i),this.getScene().getCachedMaterial()!==this){this._options.uniforms.indexOf("view")!==-1&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),this._options.uniforms.indexOf("projection")!==-1&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),this._options.uniforms.indexOf("viewProjection")!==-1&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.MaterialHelper.BindBonesParameters(r,this._effect);var n;for(n in this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._textureArrays)this._effect.setTextureArray(n,this._textureArrays[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var o=this._colors4[n];this._effect.setFloat4(n,o.r,o.g,o.b,o.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._vectors4)this._effect.setVector4(n,this._vectors4[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);for(n in this._matrices3x3)this._effect.setMatrix3x3(n,this._matrices3x3[n]);for(n in this._matrices2x2)this._effect.setMatrix2x2(n,this._matrices2x2[n]);for(n in this._vectors3Arrays)this._effect.setArray3(n,this._vectors3Arrays[n])}t.prototype.bind.call(this,i,r)},i.prototype.clone=function(e){var t=new i(e,this.getScene(),this._shaderPath,this._options);return t},i.prototype.dispose=function(e,i){if(i){var r;for(r in this._textures)this._textures[r].dispose();for(r in this._textureArrays)for(var n=this._textureArrays[r],o=0;o<n.length;o++)n[o].dispose()}this._textures={},t.prototype.dispose.call(this,e,i)},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);t.customType="BABYLON.ShaderMaterial",t.options=this._options,t.shaderPath=this._shaderPath;var i;t.textures={};for(i in this._textures)t.textures[i]=this._textures[i].serialize();t.textureArrays={};for(i in this._textureArrays){t.textureArrays[i]=[];for(var r=this._textureArrays[i],n=0;n<r.length;n++)t.textureArrays[i].push(r[n].serialize())}t.floats={};for(i in this._floats)t.floats[i]=this._floats[i];t.floatArrays={};for(i in this._floatsArrays)t.floatArrays[i]=this._floatsArrays[i];t.colors3={};for(i in this._colors3)t.colors3[i]=this._colors3[i].asArray();t.colors4={};for(i in this._colors4)t.colors4[i]=this._colors4[i].asArray();t.vectors2={};for(i in this._vectors2)t.vectors2[i]=this._vectors2[i].asArray();t.vectors3={};for(i in this._vectors3)t.vectors3[i]=this._vectors3[i].asArray();t.vectors4={};for(i in this._vectors4)t.vectors4[i]=this._vectors4[i].asArray();t.matrices={};for(i in this._matrices)t.matrices[i]=this._matrices[i].asArray();t.matrices3x3={};for(i in this._matrices3x3)t.matrices3x3[i]=this._matrices3x3[i];t.matrices2x2={};for(i in this._matrices2x2)t.matrices2x2[i]=this._matrices2x2[i];t.vectors3Arrays={};for(i in this._vectors3Arrays)t.vectors3Arrays[i]=this._vectors3Arrays[i];return t},i.Parse=function(t,r,n){var o,s=e.SerializationHelper.Parse((function(){return new i(t.name,r,t.shaderPath,t.options)}),t,r,n);for(o in t.textures)s.setTexture(o,e.Texture.Parse(t.textures[o],r,n));for(o in t.textureArrays){for(var a=t.textureArrays[o],h=new Array,c=0;c<a.length;c++)h.push(e.Texture.Parse(a[c],r,n));s.setTextureArray(o,h)}for(o in t.floats)s.setFloat(o,t.floats[o]);for(o in t.floatsArrays)s.setFloats(o,t.floatsArrays[o]);for(o in t.colors3)s.setColor3(o,e.Color3.FromArray(t.colors3[o]));for(o in t.colors4)s.setColor4(o,e.Color4.FromArray(t.colors4[o]));for(o in t.vectors2)s.setVector2(o,e.Vector2.FromArray(t.vectors2[o]));for(o in t.vectors3)s.setVector3(o,e.Vector3.FromArray(t.vectors3[o]));for(o in t.vectors4)s.setVector4(o,e.Vector4.FromArray(t.vectors4[o]));for(o in t.matrices)s.setMatrix(o,e.Matrix.FromArray(t.matrices[o]));for(o in t.matrices3x3)s.setMatrix3x3(o,t.matrices3x3[o]);for(o in t.matrices2x2)s.setMatrix2x2(o,t.matrices2x2[o]);for(o in t.vectors3Arrays)s.setArray3(o,t.vectors3Arrays[o]);return s},i})(e.Material);e.ShaderMaterial=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){function i(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function r(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}var n=542327876,o=131072,s=512,a=4,h=64,c=131072,l=i("DXT1"),u=i("DXT3"),d=i("DXT5"),f=31,p=0,m=1,_=2,g=3,v=4,y=7,x=20,b=21,T=22,A=28,E=(function(){function t(){}return t.GetDDSInfo=function(e){var t=new Int32Array(e,0,f),i=1;return t[_]&o&&(i=Math.max(1,t[y])),{width:t[v],height:t[g],mipmapCount:i,isFourCC:(t[x]&a)===a,isRGB:(t[x]&h)===h,isLuminance:(t[x]&c)===c,isCube:(t[A]&s)===s}},t.GetRGBAArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),s=new Uint8Array(n),a=0,h=t-1;h>=0;h--)for(var c=0;c<e;c++){var l=i+4*(c+h*e);o[a+2]=s[l],o[a+1]=s[l+1],o[a]=s[l+2],o[a+3]=s[l+3],a+=4}return o},t.GetRGBArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),s=new Uint8Array(n),a=0,h=t-1;h>=0;h--)for(var c=0;c<e;c++){var l=i+3*(c+h*e);o[a+2]=s[l],o[a+1]=s[l+1],o[a]=s[l+2],a+=3}return o},t.GetLuminanceArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),s=new Uint8Array(n),a=0,h=t-1;h>=0;h--)for(var c=0;c<e;c++){var l=i+(c+h*e);o[a]=s[l],a++}return o},t.UploadDDSLevels=function(i,s,a,h,c,x){var A,E,P,M,S,C,R,O,D,I,w=new Int32Array(a,0,f);if(w[p]!=n)return void e.Tools.Error("Invalid magic number in DDS header");if(!h.isFourCC&&!h.isRGB&&!h.isLuminance)return void e.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");if(h.isFourCC)switch(A=w[b]){case l:E=8,P=s.COMPRESSED_RGBA_S3TC_DXT1_EXT;break;case u:E=16,P=s.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case d:E=16,P=s.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;default:return void console.error("Unsupported FourCC code:",r(A))}D=1,w[_]&o&&c!==!1&&(D=Math.max(1,w[y]));for(var L=w[T],B=0;B<x;B++){var F=1===x?i.TEXTURE_2D:i.TEXTURE_CUBE_MAP_POSITIVE_X+B;for(M=w[v],S=w[g],R=w[m]+4,I=0;I<D;++I){if(h.isRGB)24===L?(C=M*S*3,O=t.GetRGBArrayBuffer(M,S,R,C,a),i.texImage2D(F,I,i.RGB,M,S,0,i.RGB,i.UNSIGNED_BYTE,O)):(C=M*S*4,O=t.GetRGBAArrayBuffer(M,S,R,C,a),i.texImage2D(F,I,i.RGBA,M,S,0,i.RGBA,i.UNSIGNED_BYTE,O));else if(h.isLuminance){var V=i.getParameter(i.UNPACK_ALIGNMENT),N=M,z=Math.floor((M+V-1)/V)*V;C=z*(S-1)+N,O=t.GetLuminanceArrayBuffer(M,S,R,C,a),i.texImage2D(F,I,i.LUMINANCE,M,S,0,i.LUMINANCE,i.UNSIGNED_BYTE,O)}else C=Math.max(4,M)/4*Math.max(4,S)/4*E,O=new Uint8Array(a,R,C),i.compressedTexImage2D(F,I,P,M,S,0,O);R+=C,M*=.5,S*=.5,M=Math.max(1,M),S=Math.max(1,S)}}},t})();t.DDSTools=E})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){return void 0===t&&(t=!0),void 0===i&&(i=10),this._useDeltaForWorldStep=t,this.name="CannonJSPlugin",this._physicsMaterials=[],this._fixedTimeStep=1/60,this._currentCollisionGroup=2,this._minus90X=new e.Quaternion((-.7071067811865475),0,0,.7071067811865475),this._plus90X=new e.Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=e.Vector3.Zero(),this._tmpQuaternion=new e.Quaternion,this._tmpDeltaPosition=e.Vector3.Zero(),this._tmpDeltaRotation=new e.Quaternion,this._tmpUnityRotation=new e.Quaternion,this.isSupported()?(this.world=new CANNON.World,this.world.broadphase=new CANNON.NaiveBroadphase,void(this.world.solver.iterations=i)):void e.Tools.Error("CannonJS is not available. Please make sure you included the js file.")}return t.prototype.setGravity=function(e){this.world.gravity.copy(e)},t.prototype.setTimeStep=function(e){this._fixedTimeStep=e},t.prototype.executeStep=function(e,t){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?1e3*e:0,3)},t.prototype.applyImpulse=function(e,t,i){var r=new CANNON.Vec3(i.x,i.y,i.z),n=new CANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},t.prototype.applyForce=function(e,t,i){var r=new CANNON.Vec3(i.x,i.y,i.z),n=new CANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},t.prototype.generatePhysicsBody=function(e){if(e.parent)return void(e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate()));if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);e.physicsBody=new CANNON.Body(n),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){e.physicsBody[t].copy(i[t])})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)},t.prototype._processChildMeshes=function(t){var i=this,r=t.object.getChildMeshes?t.object.getChildMeshes():[];if(r.length){var n=function(e,r){var o=r.getPhysicsImpostor();if(o){var s=o.parent;if(s!==t){var e=r.position;o.physicsBody&&(i.removePhysicsBody(o),o.physicsBody=null),o.parent=t,o.resetUpdateFlags(),t.physicsBody.addShape(i._createShape(o),new CANNON.Vec3(e.x,e.y,e.z)),t.physicsBody.mass+=o.getParam("mass")}}r.getChildMeshes().forEach(n.bind(i,r.position))};r.forEach(n.bind(this,e.Vector3.Zero()))}},t.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this.world.remove(e.physicsBody)},t.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s={pivotA:o.mainPivot?(new CANNON.Vec3).copy(o.mainPivot):null,pivotB:o.connectedPivot?(new CANNON.Vec3).copy(o.connectedPivot):null,axisA:o.mainAxis?(new CANNON.Vec3).copy(o.mainAxis):null,axisB:o.connectedAxis?(new CANNON.Vec3).copy(o.connectedAxis):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(t.joint.type){case e.PhysicsJoint.HingeJoint:case e.PhysicsJoint.Hinge2Joint:n=new CANNON.HingeConstraint(i,r,s);break;case e.PhysicsJoint.DistanceJoint:n=new CANNON.DistanceConstraint(i,r,o.maxDistance||2);break;case e.PhysicsJoint.SpringJoint:var a=o;n=new CANNON.Spring(i,r,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:s.pivotA,localAnchorB:s.pivotB});break;case e.PhysicsJoint.LockJoint:n=new CANNON.LockConstraint(i,r,s);break;case e.PhysicsJoint.PointToPointJoint:case e.PhysicsJoint.BallAndSocketJoint:default:n=new CANNON.PointToPointConstraint(i,s.pivotA,r,s.pivotA,s.maxForce)}n.collideConnected=!!o.collision,t.joint.physicsJoint=n,t.joint.type!==e.PhysicsJoint.SpringJoint?this.world.addConstraint(n):t.mainImpostor.registerAfterPhysicsStep((function(){n.applyForce()}))}},t.prototype.removeJoint=function(e){this.world.removeConstraint(e.joint.physicsJoint)},t.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r<this._physicsMaterials.length;r++)if(n=this._physicsMaterials[r],n.friction===t&&n.restitution===i)return n;var o=new CANNON.Material(e);return o.friction=t,o.restitution=i,this._physicsMaterials.push(o),o},t.prototype._checkWithEpsilon=function(t){return t<e.PhysicsEngine.Epsilon?e.PhysicsEngine.Epsilon:t},t.prototype._createShape=function(t){var i,r=t.object,n=t.getObjectExtendSize();switch(t.type){case e.PhysicsEngine.SphereImpostor:var o=n.x,s=n.y,a=n.z;i=new CANNON.Sphere(Math.max(this._checkWithEpsilon(o),this._checkWithEpsilon(s),this._checkWithEpsilon(a))/2);break;case e.PhysicsImpostor.CylinderImpostor:i=new CANNON.Cylinder(this._checkWithEpsilon(n.x)/2,this._checkWithEpsilon(n.x)/2,this._checkWithEpsilon(n.y),16);break;case e.PhysicsImpostor.BoxImpostor:var h=n.scale(.5);i=new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(h.x),this._checkWithEpsilon(h.y),this._checkWithEpsilon(h.z)));break;case e.PhysicsImpostor.PlaneImpostor:e.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),i=new CANNON.Plane;break;case e.PhysicsImpostor.MeshImpostor:var c=r.getVerticesData?r.getVerticesData(e.VertexBuffer.PositionKind):[],l=r.getIndices?r.getIndices():[];e.Tools.Warn("MeshImpostor only collides against spheres."),i=new CANNON.Trimesh(c,l);break;case e.PhysicsImpostor.HeightmapImpostor:i=this._createHeightmap(r);break;case e.PhysicsImpostor.ParticleImpostor:i=new CANNON.Particle}return i},t.prototype._createHeightmap=function(t,i){for(var r=t.getVerticesData(e.VertexBuffer.PositionKind),n=[],o=i||~~(Math.sqrt(r.length/3)-1),s=Math.min(t.getBoundingInfo().boundingBox.extendSize.x,t.getBoundingInfo().boundingBox.extendSize.z),a=2*s/o,h=t.getBoundingInfo().boundingBox.extendSize.y,c=0;c<r.length;c+=3){var l=Math.round(r[c+0]/a+o/2),u=Math.round((r[c+2]/a-o/2)*-1),d=r[c+1]+h;n[l]||(n[l]=[]),n[l][u]||(n[l][u]=d),n[l][u]=Math.max(d,n[l][u])}for(var l=0;l<=o;++l){if(!n[l]){for(var f=1;!n[(l+f)%o];)f++;n[l]=n[(l+f)%o].slice()}for(var u=0;u<=o;++u)if(!n[l][u]){for(var p,f=1;void 0===p;)p=n[l][(u+f++)%o];n[l][u]=p}}var m=new CANNON.Heightfield(n,{elementSize:a});return m.minY=h,m},t.prototype._updatePhysicsBodyTransformation=function(t){var i=t.object;i.computeWorldMatrix&&i.computeWorldMatrix(!0);var r=t.getObjectCenter();t.getObjectExtendSize();this._tmpDeltaPosition.copyFrom(i.position.subtract(r)),this._tmpPosition.copyFrom(r);var n=i.rotationQuaternion;if(t.type!==e.PhysicsImpostor.PlaneImpostor&&t.type!==e.PhysicsImpostor.HeightmapImpostor&&t.type!==e.PhysicsImpostor.CylinderImpostor||(n=n.multiply(this._minus90X),t.setDeltaRotation(this._plus90X)),t.type===e.PhysicsEngine.HeightmapImpostor){var o=i,s=o.rotationQuaternion;o.rotationQuaternion=this._tmpUnityRotation,o.computeWorldMatrix(!0);var a=r.clone(),h=o.getPivotMatrix()||e.Matrix.Translation(0,0,0);o.rotationQuaternion=s;var c=e.Matrix.Translation(o.getBoundingInfo().boundingBox.extendSize.x,0,-o.getBoundingInfo().boundingBox.extendSize.z);o.setPivotMatrix(c),o.computeWorldMatrix(!0);var l=o.getBoundingInfo().boundingBox.center.subtract(r).subtract(o.position).negate();this._tmpPosition.copyFromFloats(l.x,l.y-o.getBoundingInfo().boundingBox.extendSize.y,l.z),this._tmpDeltaPosition.copyFrom(o.getBoundingInfo().boundingBox.center.subtract(a)),this._tmpDeltaPosition.y+=o.getBoundingInfo().boundingBox.extendSize.y,o.setPivotMatrix(h),o.computeWorldMatrix(!0)}else t.type===e.PhysicsEngine.MeshImpostor&&(this._tmpDeltaPosition.copyFromFloats(0,0,0),this._tmpPosition.copyFrom(i.position));t.setDeltaPosition(this._tmpDeltaPosition),t.physicsBody.position.copy(this._tmpPosition),t.physicsBody.quaternion.copy(n)},t.prototype.setTransformationFromPhysicsBody=function(e){e.object.position.copyFrom(e.physicsBody.position),e.object.rotationQuaternion.copyFrom(e.physicsBody.quaternion)},t.prototype.setPhysicsBodyTransformation=function(e,t,i){e.physicsBody.position.copy(t),e.physicsBody.quaternion.copy(i)},t.prototype.isSupported=function(){return void 0!==window.CANNON},t.prototype.setLinearVelocity=function(e,t){e.physicsBody.velocity.copy(t)},t.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},t.prototype.getLinearVelocity=function(t){var i=t.physicsBody.velocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.setBodyMass=function(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()},t.prototype.sleepBody=function(e){e.physicsBody.sleep()},t.prototype.wakeUpBody=function(e){e.physicsBody.wakeUp()},t.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.distance=t},t.prototype.enableMotor=function(e,t){t||e.physicsJoint.enableMotor()},t.prototype.disableMotor=function(e,t){t||e.physicsJoint.disableMotor()},t.prototype.setMotor=function(e,t,i,r){r||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))},t.prototype.setLimit=function(e,t,i){e.physicsJoint.motorEquation.maxForce=t,e.physicsJoint.motorEquation.minForce=void 0===i?-t:i},t.prototype.dispose=function(){},t})();e.CannonJSPlugin=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=e.Vector3.Zero(),this.world=new OIMO.World(1/60,2,t,(!0)),this.world.worldscale(1),this.world.clear(),this.world.isNoStat=!0}return t.prototype.setGravity=function(e){this.world.gravity.copy(e)},t.prototype.setTimeStep=function(e){this.world.timeStep=e},t.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody}),o.onCollide({body:n.physicsBody}),r=r.next):r=r.next}else r=r.next},t.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.massInfo.mass;e.physicsBody.applyImpulse(i.scale(OIMO.INV_SCALE),t.scale(OIMO.INV_SCALE*r))},t.prototype.applyForce=function(t,i,r){e.Tools.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,i,r)},t.prototype.generatePhysicsBody=function(t){var i=this;if(t.parent)return void(t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate()));if(t.isBodyInitRequired()){var r={name:t.uniqueId,config:[t.getParam("mass")||1,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],rot:[],move:0!==t.getParam("mass"),world:this.world},n=[t],o=function(e){e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&(n.push(e.physicsImpostor),e.physicsImpostor._init())}))};o(t.object);var s=function(t){return Math.max(t,e.PhysicsEngine.Epsilon)};n.forEach((function(n){var o=n.object.rotationQuaternion,a=(new OIMO.Euler).setFromQuaternion({x:t.object.rotationQuaternion.x,y:t.object.rotationQuaternion.y,z:t.object.rotationQuaternion.z,s:t.object.rotationQuaternion.w}),h=n.getObjectExtendSize();if(n===t){var c=t.getObjectCenter();t.object.position.subtractToRef(c,i._tmpPositionVector),r.pos.push(c.x),r.pos.push(c.y),r.pos.push(c.z),r.rot.push(a.x/(OIMO.degtorad||OIMO.TO_RAD)),r.rot.push(a.y/(OIMO.degtorad||OIMO.TO_RAD)),r.rot.push(a.z/(OIMO.degtorad||OIMO.TO_RAD))}else r.pos.push(n.object.position.x),r.pos.push(n.object.position.y),r.pos.push(n.object.position.z),r.rot.push(0),r.rot.push(0),r.rot.push(0);switch(n.type){case e.PhysicsImpostor.ParticleImpostor:e.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");case e.PhysicsImpostor.SphereImpostor:var l=h.x,u=h.y,d=h.z,f=Math.max(s(l),s(u),s(d))/2;r.type.push("sphere"),r.size.push(f),r.size.push(f),r.size.push(f);break;case e.PhysicsImpostor.CylinderImpostor:var p=s(h.x)/2,m=s(h.y);r.type.push("cylinder"),r.size.push(p),r.size.push(m),r.size.push(m);break;case e.PhysicsImpostor.PlaneImpostor:case e.PhysicsImpostor.BoxImpostor:
default:var p=s(h.x),m=s(h.y),_=s(h.z);r.type.push("box"),r.size.push(p),r.size.push(m),r.size.push(_)}n.object.rotationQuaternion=o})),t.physicsBody=new OIMO.Body(r).body}else this._tmpPositionVector.copyFromFloats(0,0,0);t.setDeltaPosition(this._tmpPositionVector)},t.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},t.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s=o.nativeParams||{},a={body1:i,body2:r,axe1:s.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:s.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:s.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:s.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||o.collision,spring:s.spring,world:this.world};switch(t.joint.type){case e.PhysicsJoint.BallAndSocketJoint:n="jointBall";break;case e.PhysicsJoint.SpringJoint:e.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var h=o;a.min=h.length||a.min,a.max=Math.max(a.min,a.max);case e.PhysicsJoint.DistanceJoint:n="jointDistance",a.max=o.maxDistance;break;case e.PhysicsJoint.PrismaticJoint:n="jointPrisme";break;case e.PhysicsJoint.SliderJoint:n="jointSlide";break;case e.PhysicsJoint.WheelJoint:n="jointWheel";break;case e.PhysicsJoint.HingeJoint:default:n="jointHinge"}a.type=n,t.joint.physicsJoint=new OIMO.Link(a).joint}},t.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(i){e.Tools.Warn(i)}},t.prototype.isSupported=function(){return void 0!==OIMO},t.prototype.setTransformationFromPhysicsBody=function(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){var t=this._getLastShape(e.physicsBody);e.object.position.x=t.position.x*OIMO.WORLD_SCALE,e.object.position.y=t.position.y*OIMO.WORLD_SCALE,e.object.position.z=t.position.z*OIMO.WORLD_SCALE}else e.object.position.copyFrom(e.physicsBody.getPosition());e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()),e.object.rotationQuaternion.normalize()}},t.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;r.position.init(t.x*OIMO.INV_SCALE,t.y*OIMO.INV_SCALE,t.z*OIMO.INV_SCALE),r.orientation.init(i.w,i.x,i.y,i.z),r.syncShapes(),r.awake()},t.prototype._getLastShape=function(e){for(var t=e.shapes;t.next;)t=t.next;return t},t.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.init(t.x,t.y,t.z)},t.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.init(t.x,t.y,t.z)},t.prototype.getLinearVelocity=function(t){var i=t.physicsBody.linearVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},t.prototype.sleepBody=function(e){e.physicsBody.sleep()},t.prototype.wakeUpBody=function(e){e.physicsBody.awake()},t.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},t.prototype.setMotor=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},t.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},t.prototype.dispose=function(){this.world.clear()},t})();e.OimoJSPlugin=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"displayPass",["passSampler"],["passSampler"],i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.DisplayPassPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}return e})();e.SimplificationSettings=t;var i=(function(){function t(){this.running=!1,this._simplificationArray=[]}return t.prototype.addTask=function(e){this._simplificationArray.push(e)},t.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},t.prototype.runSimplification=function(t){var i=this;if(t.parallelProcessing)t.settings.forEach((function(e){var r=i.getSimplifier(t);r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,e.quality===t.settings[t.settings.length-1].quality&&t.successCallback&&t.successCallback(),i.executeNext()}))}));else{var r=this.getSimplifier(t),n=function(e,i){r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,i()}))};e.AsyncLoop.Run(t.settings.length,(function(e){n(t.settings[e.index],(function(){e.executeNext()}))}),(function(){t.successCallback&&t.successCallback(),i.executeNext()}))}},t.prototype.getSimplifier=function(e){switch(e.simplificationType){case r.QUADRATIC:default:return new h(e.mesh)}},t})();e.SimplificationQueue=i,(function(e){e[e.QUADRATIC=0]="QUADRATIC"})(e.SimplificationType||(e.SimplificationType={}));var r=e.SimplificationType,n=(function(){function e(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}return e})();e.DecimationTriangle=n;var o=(function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new s,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e})();e.DecimationVertex=o;var s=(function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,s,a,h){var c=this.data[e]*this.data[n]*this.data[h]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[o]*this.data[s]-this.data[i]*this.data[n]*this.data[s]-this.data[e]*this.data[o]*this.data[a]-this.data[t]*this.data[r]*this.data[h];return c},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e})();e.QuadraticMatrix=s;var a=(function(){function e(e,t){this.vertexId=e,this.triangleId=t}return e})();e.Reference=a;var h=(function(){function t(t){this._mesh=t,this.initialized=!1,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=e.Epsilon}return t.prototype.simplify=function(t,i){var r=this;this.initDecimatedMesh(),e.AsyncLoop.Run(this._mesh.subMeshes.length,(function(e){r.initWithMesh(e.index,(function(){r.runDecimation(t,e.index,(function(){e.executeNext()}))}),t.optimizeMesh)}),(function(){setTimeout((function(){i(r._reconstructedMesh)}),0)}))},t.prototype.isTriangleOnBoundingBox=function(e){var t=this,i=0;return e.vertices.forEach((function(e){var r=0,n=e.position,o=t._mesh.getBoundingInfo().boundingBox;(o.maximum.x-n.x<t.boundingBoxEpsilon||n.x-o.minimum.x>t.boundingBoxEpsilon)&&++r,o.maximum.y!==n.y&&n.y!==o.minimum.y||++r,o.maximum.z!==n.z&&n.z!==o.minimum.z||++r,r>1&&++i})),i>1&&console.log(e,i),i>1},t.prototype.runDecimation=function(t,i,r){var n=this,o=~~(this.triangles.length*t.quality),s=0,a=this.triangles.length,h=function(t,i){setTimeout((function(){t%5===0&&n.updateMesh(0===t);for(var r=0;r<n.triangles.length;++r)n.triangles[r].isDirty=!1;var h=1e-9*Math.pow(t+3,n.aggressiveness),c=function(t){var i=~~((n.triangles.length/2+t)%n.triangles.length),r=n.triangles[i];if(r&&!(r.error[3]>h||r.deleted||r.isDirty))for(var o=0;o<3;++o)if(r.error[o]<h){var a=[],c=[],l=r.vertices[o],u=r.vertices[(o+1)%3];if(l.isBorder||u.isBorder)continue;var d=e.Vector3.Zero(),f=e.Vector3.Zero(),p=e.Vector2.Zero(),m=new e.Color4(0,0,0,1);n.calculateError(l,u,d,f,p,m);var _=[];if(n.isFlipped(l,u,d,a,r.borderFactor,_))continue;if(n.isFlipped(u,l,d,c,r.borderFactor,_))continue;if(a.indexOf(!0)<0||c.indexOf(!0)<0)continue;var g=[];if(_.forEach((function(e){g.indexOf(e)===-1&&(e.deletePending=!0,g.push(e))})),g.length%2!==0)continue;l.q=u.q.add(l.q),l.updatePosition(d);var v=n.references.length;s=n.updateTriangles(l,l,a,s),s=n.updateTriangles(l,u,c,s);var y=n.references.length-v;if(y<=l.triangleCount){if(y)for(var x=0;x<y;x++)n.references[l.triangleStart+x]=n.references[v+x]}else l.triangleStart=v;l.triangleCount=y;break}};e.AsyncLoop.SyncAsyncForLoop(n.triangles.length,n.syncIterations,c,i,(function(){return a-s<=o}))}),0)};e.AsyncLoop.Run(this.decimationIterations,(function(e){a-s<=o?e.breakLoop():h(e.index,(function(){e.executeNext()}))}),(function(){setTimeout((function(){n.reconstructMesh(i),r()}),0)}))},t.prototype.initWithMesh=function(t,i,r){var s=this;this.vertices=[],this.triangles=[];var a=this._mesh.getVerticesData(e.VertexBuffer.PositionKind),h=this._mesh.getIndices(),c=this._mesh.subMeshes[t],l=function(e){if(r)for(var t=0;t<s.vertices.length;++t)if(s.vertices[t].position.equals(e))return s.vertices[t];return null},u=[],d=function(t){var i=t+c.verticesStart,r=e.Vector3.FromArray(a,3*i),n=l(r)||new o(r,s.vertices.length);n.originalOffsets.push(i),n.id===s.vertices.length&&s.vertices.push(n),u.push(n.id)},f=c.verticesCount;e.AsyncLoop.SyncAsyncForLoop(f,this.syncIterations/4>>0,d,(function(){var t=function(e){var t=c.indexStart/3+e,i=3*t,r=h[i+0],o=h[i+1],a=h[i+2],l=s.vertices[u[r-c.verticesStart]],d=s.vertices[u[o-c.verticesStart]],f=s.vertices[u[a-c.verticesStart]],p=new n([l,d,f]);p.originalOffset=i,s.triangles.push(p)};e.AsyncLoop.SyncAsyncForLoop(c.indexCount/3,s.syncIterations,t,(function(){s.init(i)}))}))},t.prototype.init=function(t){var i=this,r=function(t){var r=i.triangles[t];r.normal=e.Vector3.Cross(r.vertices[1].position.subtract(r.vertices[0].position),r.vertices[2].position.subtract(r.vertices[0].position)).normalize();for(var n=0;n<3;n++)r.vertices[n].q.addArrayInPlace(s.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-e.Vector3.Dot(r.normal,r.vertices[0].position)))};e.AsyncLoop.SyncAsyncForLoop(this.triangles.length,this.syncIterations,r,(function(){var r=function(e){for(var t=i.triangles[e],r=0;r<3;++r)t.error[r]=i.calculateError(t.vertices[r],t.vertices[(r+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])};e.AsyncLoop.SyncAsyncForLoop(i.triangles.length,i.syncIterations,r,(function(){i.initialized=!0,t()}))}))},t.prototype.reconstructMesh=function(t){var i,r=[];for(i=0;i<this.vertices.length;++i)this.vertices[i].triangleCount=0;var n,o;for(i=0;i<this.triangles.length;++i)if(!this.triangles[i].deleted){for(n=this.triangles[i],o=0;o<3;++o)n.vertices[o].triangleCount=1;r.push(n)}var s=this._reconstructedMesh.getVerticesData(e.VertexBuffer.PositionKind)||[],a=this._reconstructedMesh.getVerticesData(e.VertexBuffer.NormalKind)||[],h=this._reconstructedMesh.getVerticesData(e.VertexBuffer.UVKind)||[],c=this._reconstructedMesh.getVerticesData(e.VertexBuffer.ColorKind)||[],l=this._mesh.getVerticesData(e.VertexBuffer.NormalKind),u=this._mesh.getVerticesData(e.VertexBuffer.UVKind),d=this._mesh.getVerticesData(e.VertexBuffer.ColorKind),f=0;for(i=0;i<this.vertices.length;++i){var p=this.vertices[i];p.id=f,p.triangleCount&&p.originalOffsets.forEach((function(e){s.push(p.position.x),s.push(p.position.y),s.push(p.position.z),a.push(l[3*e]),a.push(l[3*e+1]),a.push(l[3*e+2]),u&&u.length?(h.push(u[2*e]),h.push(u[2*e+1])):d&&d.length&&(c.push(d[4*e]),c.push(d[4*e+1]),c.push(d[4*e+2]),c.push(d[4*e+3])),++f}))}var m=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];var v=this._reconstructedMesh.getIndices(),y=this._mesh.getIndices();for(i=0;i<r.length;++i)n=r[i],[0,1,2].forEach((function(e){var t=y[n.originalOffset+e],i=n.vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),v.push(n.vertices[e].id+i+_)}));this._reconstructedMesh.setIndices(v),this._reconstructedMesh.setVerticesData(e.VertexBuffer.PositionKind,s),this._reconstructedMesh.setVerticesData(e.VertexBuffer.NormalKind,a),h.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.UVKind,h),c.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.ColorKind,c);var x=this._mesh.subMeshes[t];if(t>0){this._reconstructedMesh.subMeshes=[],g.forEach((function(t){new e.SubMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,t.getMesh())}));new e.SubMesh(x.materialIndex,_,f,m,3*r.length,this._reconstructedMesh)}},t.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new e.Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},t.prototype.isFlipped=function(t,i,r,n,o,s){for(var a=0;a<t.triangleCount;++a){var h=this.triangles[this.references[t.triangleStart+a].triangleId];if(!h.deleted){var c=this.references[t.triangleStart+a].vertexId,l=h.vertices[(c+1)%3],u=h.vertices[(c+2)%3];if(l!==i&&u!==i){var d=l.position.subtract(r);d=d.normalize();var f=u.position.subtract(r);if(f=f.normalize(),Math.abs(e.Vector3.Dot(d,f))>.999)return!0;var p=e.Vector3.Cross(d,f).normalize();if(n[a]=!1,e.Vector3.Dot(p,h.normal)<.2)return!0}else n[a]=!0,s.push(h)}}return!1},t.prototype.updateTriangles=function(e,t,i,r){for(var n=r,o=0;o<t.triangleCount;++o){var s=this.references[t.triangleStart+o],a=this.triangles[s.triangleId];a.deleted||(i[o]&&a.deletePending?(a.deleted=!0,n++):(a.vertices[s.vertexId]=e,a.isDirty=!0,a.error[0]=this.calculateError(a.vertices[0],a.vertices[1])+a.borderFactor/2,a.error[1]=this.calculateError(a.vertices[1],a.vertices[2])+a.borderFactor/2,a.error[2]=this.calculateError(a.vertices[2],a.vertices[0])+a.borderFactor/2,a.error[3]=Math.min(a.error[0],a.error[1],a.error[2]),this.references.push(s)))}return n},t.prototype.identifyBorder=function(){for(var e=0;e<this.vertices.length;++e){var t,i=[],r=[],n=this.vertices[e];for(t=0;t<n.triangleCount;++t)for(var o=this.triangles[this.references[n.triangleStart+t].triangleId],s=0;s<3;s++){for(var a=0,h=o.vertices[s];a<i.length&&r[a]!==h.id;)++a;a===i.length?(i.push(1),r.push(h.id)):i[a]++}for(t=0;t<i.length;++t)1===i[t]?this.vertices[r[t]].isBorder=!0:this.vertices[r[t]].isBorder=!1}},t.prototype.updateMesh=function(e){void 0===e&&(e=!1);var t;if(!e){var i=[];for(t=0;t<this.triangles.length;++t)this.triangles[t].deleted||i.push(this.triangles[t]);this.triangles=i}for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleCount=0,this.vertices[t].triangleStart=0;var r,n,o;for(t=0;t<this.triangles.length;++t)for(r=this.triangles[t],n=0;n<3;++n)o=r.vertices[n],o.triangleCount++;var s=0;for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleStart=s,s+=this.vertices[t].triangleCount,this.vertices[t].triangleCount=0;var h=new Array(3*this.triangles.length);for(t=0;t<this.triangles.length;++t)for(r=this.triangles[t],n=0;n<3;++n)o=r.vertices[n],h[o.triangleStart+o.triangleCount]=new a(n,t),o.triangleCount++;this.references=h,e&&this.identifyBorder()},t.prototype.vertexError=function(e,t){var i=t.x,r=t.y,n=t.z;return e.data[0]*i*i+2*e.data[1]*i*r+2*e.data[2]*i*n+2*e.data[3]*i+e.data[4]*r*r+2*e.data[5]*r*n+2*e.data[6]*r+e.data[7]*n*n+2*e.data[8]*n+e.data[9]},t.prototype.calculateError=function(t,i,r,n,o,s){var a=t.q.add(i.q),h=t.isBorder&&i.isBorder,c=0,l=a.det(0,1,2,1,4,5,2,5,7);if(0===l||h){var u=t.position.add(i.position).divide(new e.Vector3(2,2,2)),d=this.vertexError(a,t.position),f=this.vertexError(a,i.position),p=this.vertexError(a,u);c=Math.min(d,f,p),c===d?r&&r.copyFrom(t.position):c===f?r&&r.copyFrom(i.position):r&&r.copyFrom(u)}else r||(r=e.Vector3.Zero()),r.x=-1/l*a.det(1,2,3,4,5,6,5,7,8),r.y=1/l*a.det(0,2,3,1,5,6,2,7,8),r.z=-1/l*a.det(0,1,3,1,4,6,2,5,8),c=this.vertexError(a,r);return c},t})();e.QuadraticErrorSimplification=h})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=[],i=function(i,r){if(!t[i.id]&&!i.doNotSerialize){if(i instanceof e.Geometry.Primitives.Box)r.boxes.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Sphere)r.spheres.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Cylinder)r.cylinders.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Torus)r.toruses.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Ground)r.grounds.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Plane)r.planes.push(i.serialize());else if(i instanceof e.Geometry.Primitives.TorusKnot)r.torusKnots.push(i.serialize());else{if(i instanceof e.Geometry.Primitives._Primitive)throw new Error("Unknown primitive type");r.vertexData.push(i.serializeVerticeData())}t[i.id]=!0}},r=function(t,r){var n={};n.name=t.name,n.id=t.id,e.Tags.HasTags(t)&&(n.tags=e.Tags.GetTags(t)),n.position=t.position.asArray(),t.rotationQuaternion?n.rotationQuaternion=t.rotationQuaternion.asArray():t.rotation&&(n.rotation=t.rotation.asArray()),n.scaling=t.scaling.asArray(),n.localMatrix=t.getPivotMatrix().asArray(),n.isEnabled=t.isEnabled(),n.isVisible=t.isVisible,n.infiniteDistance=t.infiniteDistance,n.pickable=t.isPickable,n.receiveShadows=t.receiveShadows,n.billboardMode=t.billboardMode,n.visibility=t.visibility,n.checkCollisions=t.checkCollisions,n.isBlocker=t.isBlocker,t.parent&&(n.parentId=t.parent.id);var o=t._geometry;if(o){var s=o.id;n.geometryId=s,t.getScene().getGeometryByID(s)||i(o,r.geometries),n.subMeshes=[];for(var a=0;a<t.subMeshes.length;a++){var h=t.subMeshes[a];n.subMeshes.push({materialIndex:h.materialIndex,verticesStart:h.verticesStart,verticesCount:h.verticesCount,indexStart:h.indexStart,indexCount:h.indexCount})}}t.material?n.materialId=t.material.id:t.material=null,t.skeleton&&(n.skeletonId=t.skeleton.id),t.getPhysicsImpostor()&&(n.physicsMass=t.getPhysicsMass(),n.physicsFriction=t.getPhysicsFriction(),n.physicsRestitution=t.getPhysicsRestitution(),n.physicsImpostor=t.getPhysicsImpostor().type),t.metadata&&(n.metadata=t.metadata),n.instances=[];for(var c=0;c<t.instances.length;c++){var l=t.instances[c],u={name:l.name,position:l.position.asArray(),scaling:l.scaling.asArray()};l.rotationQuaternion?u.rotationQuaternion=l.rotationQuaternion.asArray():l.rotation&&(u.rotation=l.rotation.asArray()),n.instances.push(u),e.Animation.AppendSerializedAnimations(l,u),u.ranges=l.serializeAnimationRanges()}return e.Animation.AppendSerializedAnimations(t,n),n.ranges=t.serializeAnimationRanges(),n.layerMask=t.layerMask,n.alphaIndex=t.alphaIndex,n.hasVertexAlpha=t.hasVertexAlpha,n.overlayAlpha=t.overlayAlpha,n.overlayColor=t.overlayColor.asArray(),n.renderOverlay=t.renderOverlay,n.applyFog=t.applyFog,t.actionManager&&(n.actions=t.actionManager.serialize(t.name)),n},n=function(t,n){if(t.delayLoadState===e.Engine.DELAYLOADSTATE_LOADED||t.delayLoadState===e.Engine.DELAYLOADSTATE_NONE){t.material&&(t.material instanceof e.StandardMaterial?(n.materials=n.materials||[],n.materials.some((function(e){return e.id===t.material.id}))||n.materials.push(t.material.serialize())):t.material instanceof e.MultiMaterial&&(n.multiMaterials=n.multiMaterials||[],n.multiMaterials.some((function(e){return e.id===t.material.id}))||n.multiMaterials.push(t.material.serialize())));var o=t._geometry;o&&(n.geometries||(n.geometries={},n.geometries.boxes=[],n.geometries.spheres=[],n.geometries.cylinders=[],n.geometries.toruses=[],n.geometries.grounds=[],n.geometries.planes=[],n.geometries.torusKnots=[],n.geometries.vertexData=[]),i(o,n.geometries)),t.skeleton&&(n.skeletons=n.skeletons||[],n.skeletons.push(t.skeleton.serialize())),n.meshes=n.meshes||[],n.meshes.push(r(t,n))}},o=(function(){function o(){}return o.ClearCache=function(){t=[]},o.Serialize=function(n){var o={};o.useDelayedTextureLoading=n.useDelayedTextureLoading,o.autoClear=n.autoClear,o.clearColor=n.clearColor.asArray(),o.ambientColor=n.ambientColor.asArray(),o.gravity=n.gravity.asArray(),o.collisionsEnabled=n.collisionsEnabled,o.workerCollisions=n.workerCollisions,n.fogMode&&0!==n.fogMode&&(o.fogMode=n.fogMode,o.fogColor=n.fogColor.asArray(),o.fogStart=n.fogStart,o.fogEnd=n.fogEnd,o.fogDensity=n.fogDensity),n.isPhysicsEnabled()&&(o.physicsEnabled=!0,o.physicsGravity=n.getPhysicsEngine().gravity.asArray(),o.physicsEngine=n.getPhysicsEngine().getPhysicsPluginName()),n.metadata&&(o.metadata=n.metadata),o.lights=[];var s,a;for(s=0;s<n.lights.length;s++)a=n.lights[s],a.doNotSerialize||o.lights.push(a.serialize());for(o.cameras=[],s=0;s<n.cameras.length;s++){var h=n.cameras[s];h.doNotSerialize||o.cameras.push(h.serialize())}n.activeCamera&&(o.activeCameraID=n.activeCamera.id),e.Animation.AppendSerializedAnimations(n,o),o.materials=[],o.multiMaterials=[];var c;for(s=0;s<n.materials.length;s++)c=n.materials[s],c.doNotSerialize||o.materials.push(c.serialize());for(o.multiMaterials=[],s=0;s<n.multiMaterials.length;s++){var l=n.multiMaterials[s];o.multiMaterials.push(l.serialize())}for(o.skeletons=[],s=0;s<n.skeletons.length;s++)o.skeletons.push(n.skeletons[s].serialize());o.geometries={},o.geometries.boxes=[],o.geometries.spheres=[],o.geometries.cylinders=[],o.geometries.toruses=[],o.geometries.grounds=[],o.geometries.planes=[],o.geometries.torusKnots=[],o.geometries.vertexData=[],t=[];var u=n.getGeometries();for(s=0;s<u.length;s++){var d=u[s];d.isReady()&&i(d,o.geometries)}for(o.meshes=[],s=0;s<n.meshes.length;s++){var f=n.meshes[s];if(f instanceof e.Mesh){var p=f;p.doNotSerialize||p.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADED&&p.delayLoadState!==e.Engine.DELAYLOADSTATE_NONE||o.meshes.push(r(p,o))}}for(o.particleSystems=[],s=0;s<n.particleSystems.length;s++)o.particleSystems.push(n.particleSystems[s].serialize());for(o.lensFlareSystems=[],s=0;s<n.lensFlareSystems.length;s++)o.lensFlareSystems.push(n.lensFlareSystems[s].serialize());for(o.shadowGenerators=[],s=0;s<n.lights.length;s++){a=n.lights[s];var m=a.getShadowGenerator();m&&m instanceof e.ShadowGenerator&&o.shadowGenerators.push(m.serialize())}for(n.actionManager&&(o.actions=n.actionManager.serialize("scene")),o.sounds=[],s=0;s<n.soundTracks.length;s++)for(var _=n.soundTracks[s],g=0;g<_.soundCollection.length;g++)o.sounds.push(_.soundCollection[g].serialize());return o},o.SerializeMesh=function(t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var o={};if(t=t instanceof Array?t:[t],i||r)for(var s=0;s<t.length;++s)r&&t[s].getDescendants().forEach((function(i){i instanceof e.Mesh&&t.indexOf(i)<0&&t.push(i)})),i&&t[s].parent&&t.indexOf(t[s].parent)<0&&t.push(t[s].parent);return t.forEach((function(e){n(e,o)})),o},o})();e.SceneSerializer=o})(BABYLON||(BABYLON={}));var Earcut;!(function(e){function t(e,t,r){r=r||2;var o=t&&t.length,s=o?t[0]*r:e.length,a=i(e,0,s,r,!0),h=[];if(!a)return h;var l,u,d,f,p,m,_;if(o&&(a=c(e,t,a,r)),e.length>80*r){l=d=e[0],u=f=e[1];for(var g=r;g<s;g+=r)p=e[g],m=e[g+1],p<l&&(l=p),m<u&&(u=m),p>d&&(d=p),m>f&&(f=m);_=Math.max(d-l,f-u)}return n(a,h,r,l,u,_,void 0),h}function i(e,t,i,r,n){var o,s;if(n===O(e,t,i,r)>0)for(o=t;o<i;o+=r)s=M(o,e[o],e[o+1],s);else for(o=i-r;o>=t;o-=r)s=M(o,e[o],e[o+1],s);return s&&x(s,s.next)&&(S(s),s=s.next),s}function r(e,t){if(!e)return e;t||(t=e);var i,r=e;do if(i=!1,r.steiner||!x(r,r.next)&&0!==y(r.prev,r,r.next))r=r.next;else{if(S(r),r=t=r.prev,r===r.next)return null;i=!0}while(i||r!==t);return t}function n(e,t,i,c,l,u,d){if(e){!d&&u&&f(e,c,l,u);for(var p,m,_=e;e.prev!==e.next;)if(p=e.prev,m=e.next,u?s(e,c,l,u):o(e))t.push(p.i/i),t.push(e.i/i),t.push(m.i/i),S(e),e=m.next,_=m.next;else if(e=m,e===_){d?1===d?(e=a(e,t,i),n(e,t,i,c,l,u,2)):2===d&&h(e,t,i,c,l,u):n(r(e,void 0),t,i,c,l,u,1);break}}}function o(e){var t=e.prev,i=e,r=e.next;if(y(t,i,r)>=0)return!1;for(var n=e.next.next;n!==e.prev;){if(g(t.x,t.y,i.x,i.y,r.x,r.y,n.x,n.y)&&y(n.prev,n,n.next)>=0)return!1;n=n.next}return!0}function s(e,t,i,r){var n=e.prev,o=e,s=e.next;if(y(n,o,s)>=0)return!1;for(var a=n.x<o.x?n.x<s.x?n.x:s.x:o.x<s.x?o.x:s.x,h=n.y<o.y?n.y<s.y?n.y:s.y:o.y<s.y?o.y:s.y,c=n.x>o.x?n.x>s.x?n.x:s.x:o.x>s.x?o.x:s.x,l=n.y>o.y?n.y>s.y?n.y:s.y:o.y>s.y?o.y:s.y,u=m(a,h,t,i,r),d=m(c,l,t,i,r),f=e.nextZ;f&&f.z<=d;){if(f!==e.prev&&f!==e.next&&g(n.x,n.y,o.x,o.y,s.x,s.y,f.x,f.y)&&y(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=e.prevZ;f&&f.z>=u;){if(f!==e.prev&&f!==e.next&&g(n.x,n.y,o.x,o.y,s.x,s.y,f.x,f.y)&&y(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0}function a(e,t,i){var r=e;do{var n=r.prev,o=r.next.next;!x(n,o)&&b(n,r,r.next,o)&&A(n,o)&&A(o,n)&&(t.push(n.i/i),t.push(r.i/i),t.push(o.i/i),S(r),S(r.next),r=e=o),r=r.next}while(r!==e);return r}function h(e,t,i,o,s,a){var h=e;do{for(var c=h.next.next;c!==h.prev;){if(h.i!==c.i&&v(h,c)){var l=P(h,c);return h=r(h,h.next),l=r(l,l.next),n(h,t,i,o,s,a,void 0),void n(l,t,i,o,s,a,void 0)}c=c.next}h=h.next}while(h!==e)}function c(e,t,n,o){var s,a,h,c,d,f=[];for(s=0,a=t.length;s<a;s++)h=t[s]*o,c=s<a-1?t[s+1]*o:e.length,d=i(e,h,c,o,!1),d===d.next&&(d.steiner=!0),f.push(_(d));for(f.sort(l),s=0;s<f.length;s++)u(f[s],n),n=r(n,n.next);return n}function l(e,t){return e.x-t.x}function u(e,t){if(t=d(e,t)){var i=P(t,e);r(i,i.next)}}function d(e,t){var i,r=t,n=e.x,o=e.y,s=-(1/0);do{if(o<=r.y&&o>=r.next.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=n&&a>s){if(s=a,a===n){if(o===r.y)return r;if(o===r.next.y)return r.next}i=r.x<r.next.x?r:r.next}}r=r.next}while(r!==t);if(!i)return null;if(n===s)return i.prev;var h,c=i,l=i.x,u=i.y,d=1/0;for(r=i.next;r!==c;)n>=r.x&&r.x>=l&&g(o<u?n:s,o,l,u,o<u?s:n,o,r.x,r.y)&&(h=Math.abs(o-r.y)/(n-r.x),(h<d||h===d&&r.x>i.x)&&A(r,e)&&(i=r,d=h)),r=r.next;return i}function f(e,t,i,r){var n=e;do null===n.z&&(n.z=m(n.x,n.y,t,i,r)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,p(n)}function p(e){var t,i,r,n,o,s,a,h,c=1;do{for(i=e,e=null,o=null,s=0;i;){for(s++,r=i,a=0,t=0;t<c&&(a++,r=r.nextZ,r);t++);for(h=c;a>0||h>0&&r;)0===a?(n=r,r=r.nextZ,h--):0!==h&&r?i.z<=r.z?(n=i,i=i.nextZ,a--):(n=r,r=r.nextZ,h--):(n=i,i=i.nextZ,a--),o?o.nextZ=n:e=n,n.prevZ=o,o=n;i=r}o.nextZ=null,c*=2}while(s>1);return e}function m(e,t,i,r,n){return e=32767*(e-i)/n,t=32767*(t-r)/n,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e|t<<1}function _(e){var t=e,i=e;do t.x<i.x&&(i=t),t=t.next;while(t!==e);return i}function g(e,t,i,r,n,o,s,a){return(n-s)*(t-a)-(e-s)*(o-a)>=0&&(e-s)*(r-a)-(i-s)*(t-a)>=0&&(i-s)*(o-a)-(n-s)*(r-a)>=0}function v(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!T(e,t)&&A(e,t)&&A(t,e)&&E(e,t)}function y(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function x(e,t){return e.x===t.x&&e.y===t.y}function b(e,t,i,r){return!!(x(e,t)&&x(i,r)||x(e,r)&&x(i,t))||y(e,t,i)>0!=y(e,t,r)>0&&y(i,r,e)>0!=y(i,r,t)>0}function T(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&b(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}function A(e,t){return y(e.prev,e,e.next)<0?y(e,t,e.next)>=0&&y(e,e.prev,t)>=0:y(e,t,e.prev)<0||y(e,e.next,t)<0}function E(e,t){var i=e,r=!1,n=(e.x+t.x)/2,o=(e.y+t.y)/2;do i.y>o!=i.next.y>o&&n<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next;while(i!==e);return r}function P(e,t){var i=new C(e.i,e.x,e.y),r=new C(t.i,t.x,t.y),n=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=n,n.prev=i,r.next=i,i.prev=r,o.next=r,r.prev=o,r}function M(e,t,i,r){var n=new C(e,t,i);return r?(n.next=r.next,n.prev=r,r.next.prev=n,r.next=n):(n.prev=n,n.next=n),n}function S(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function C(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function R(e,t,i,r){var n=t&&t.length,o=n?t[0]*i:e.length,s=Math.abs(O(e,0,o,i));if(n)for(var a=0,h=t.length;a<h;a++){var c=t[a]*i,l=a<h-1?t[a+1]*i:e.length;s-=Math.abs(O(e,c,l,i))}var u=0;for(a=0;a<r.length;a+=3){var d=r[a]*i,f=r[a+1]*i,p=r[a+2]*i;u+=Math.abs((e[d]-e[p])*(e[f+1]-e[d+1])-(e[d]-e[f])*(e[p+1]-e[d+1]))}return 0===s&&0===u?0:Math.abs((u-s)/s)}function O(e,t,i,r){for(var n=0,o=t,s=i-r;o<i;o+=r)n+=(e[s]-e[o])*(e[o+1]+e[s+1]),s=o;return n}function D(e){for(var t=e[0][0].length,i={vertices:[],holes:[],dimensions:t},r=0,n=0;n<e.length;n++){for(var o=0;o<e[n].length;o++)for(var s=0;s<t;s++)i.vertices.push(e[n][o][s]);n>0&&(r+=e[n-1].length,i.holes.push(r))}return i}e.earcut=t,e.deviation=R,e.flatten=D})(Earcut||(Earcut={}));var BABYLON;!(function(e){var t=0,i=(function(){function t(e,t,i){this.pos=e,this.normal=t,this.uv=i}return t.prototype.clone=function(){return new t(this.pos.clone(),this.normal.clone(),this.uv.clone())},t.prototype.flip=function(){this.normal=this.normal.scale(-1)},t.prototype.interpolate=function(i,r){return new t(e.Vector3.Lerp(this.pos,i.pos,r),e.Vector3.Lerp(this.normal,i.normal,r),e.Vector2.Lerp(this.uv,i.uv,r))},t})(),r=(function(){function t(e,t){this.normal=e,this.w=t}return t.FromPoints=function(i,r,n){var o=n.subtract(i),s=r.subtract(i);if(0===o.lengthSquared()||0===s.lengthSquared())return null;var a=e.Vector3.Normalize(e.Vector3.Cross(o,s));return new t(a,e.Vector3.Dot(a,i))},t.prototype.clone=function(){return new t(this.normal.clone(),this.w)},t.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},t.prototype.splitPolygon=function(i,r,o,s,a){var h,c,l=0,u=1,d=2,f=3,p=0,m=[];for(h=0;h<i.vertices.length;h++){c=e.Vector3.Dot(this.normal,i.vertices[h].pos)-this.w;var _=c<-t.EPSILON?d:c>t.EPSILON?u:l;p|=_,m.push(_)}switch(p){case l:(e.Vector3.Dot(this.normal,i.plane.normal)>0?r:o).push(i);break;case u:s.push(i);break;case d:a.push(i);break;case f:var g=[],v=[];for(h=0;h<i.vertices.length;h++){var y=(h+1)%i.vertices.length,x=m[h],b=m[y],T=i.vertices[h],A=i.vertices[y];if(x!==d&&g.push(T),x!==u&&v.push(x!==d?T.clone():T),(x|b)===f){c=(this.w-e.Vector3.Dot(this.normal,T.pos))/e.Vector3.Dot(this.normal,A.pos.subtract(T.pos));var E=T.interpolate(A,c);g.push(E),v.push(E.clone())}}var P;g.length>=3&&(P=new n(g,i.shared),P.plane&&s.push(P)),v.length>=3&&(P=new n(v,i.shared),P.plane&&a.push(P))}},t.EPSILON=1e-5,t})(),n=(function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=r.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){var t=this.vertices.map((function(e){return e.clone()}));return new e(t,this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e})(),o=(function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=[],e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e<this.polygons.length;e++)this.polygons[e].flip();this.plane&&this.plane.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();var t=this.front;this.front=this.back,this.back=t},e.prototype.clipPolygons=function(e){if(!this.plane)return e.slice();for(var t=[],i=[],r=0;r<e.length;r++)this.plane.splitPolygon(e[r],t,i,t,i);return this.front&&(t=this.front.clipPolygons(t)),i=this.back?this.back.clipPolygons(i):[],t.concat(i)},e.prototype.clipTo=function(e){this.polygons=e.clipPolygons(this.polygons),this.front&&this.front.clipTo(e),this.back&&this.back.clipTo(e)},e.prototype.allPolygons=function(){var e=this.polygons.slice();return this.front&&(e=e.concat(this.front.allPolygons())),this.back&&(e=e.concat(this.back.allPolygons())),e},e.prototype.build=function(t){if(t.length){this.plane||(this.plane=t[0].plane.clone());for(var i=[],r=[],n=0;n<t.length;n++)this.plane.splitPolygon(t[n],this.polygons,this.polygons,i,r);
i.length&&(this.front||(this.front=new e),this.front.build(i)),r.length&&(this.back||(this.back=new e),this.back.build(r))}},e})(),s=(function(){function r(){this.polygons=new Array}return r.FromMesh=function(o){var s,a,h,c,l,u,d,f,p,m,_,g=new Array;if(!(o instanceof e.Mesh))throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";o.computeWorldMatrix(!0),d=o.getWorldMatrix(),f=o.position.clone(),p=o.rotation.clone(),o.rotationQuaternion&&(m=o.rotationQuaternion.clone()),_=o.scaling.clone();for(var v=o.getIndices(),y=o.getVerticesData(e.VertexBuffer.PositionKind),x=o.getVerticesData(e.VertexBuffer.NormalKind),b=o.getVerticesData(e.VertexBuffer.UVKind),T=o.subMeshes,A=0,E=T.length;A<E;A++)for(var P=T[A].indexStart,M=T[A].indexCount+T[A].indexStart;P<M;P+=3){u=[];for(var S=0;S<3;S++){var C=new e.Vector3(x[3*v[P+S]],x[3*v[P+S]+1],x[3*v[P+S]+2]);h=new e.Vector2(b[2*v[P+S]],b[2*v[P+S]+1]);var R=new e.Vector3(y[3*v[P+S]],y[3*v[P+S]+1],y[3*v[P+S]+2]);c=e.Vector3.TransformCoordinates(R,d),a=e.Vector3.TransformNormal(C,d),s=new i(c,a,h),u.push(s)}l=new n(u,{subMeshId:A,meshId:t,materialIndex:T[A].materialIndex}),l.plane&&g.push(l)}var O=r.FromPolygons(g);return O.matrix=d,O.position=f,O.rotation=p,O.scaling=_,O.rotationQuaternion=m,t++,O},r.FromPolygons=function(e){var t=new r;return t.polygons=e,t},r.prototype.clone=function(){var e=new r;return e.polygons=this.polygons.map((function(e){return e.clone()})),e.copyTransformAttributes(this),e},r.prototype.toPolygons=function(){return this.polygons},r.prototype.union=function(e){var t=new o(this.clone().polygons),i=new o(e.clone().polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),r.FromPolygons(t.allPolygons()).copyTransformAttributes(this)},r.prototype.unionInPlace=function(e){var t=new o(this.polygons),i=new o(e.polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this.polygons=t.allPolygons()},r.prototype.subtract=function(e){var t=new o(this.clone().polygons),i=new o(e.clone().polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),r.FromPolygons(t.allPolygons()).copyTransformAttributes(this)},r.prototype.subtractInPlace=function(e){var t=new o(this.polygons),i=new o(e.polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this.polygons=t.allPolygons()},r.prototype.intersect=function(e){var t=new o(this.clone().polygons),i=new o(e.clone().polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),r.FromPolygons(t.allPolygons()).copyTransformAttributes(this)},r.prototype.intersectInPlace=function(e){var t=new o(this.polygons),i=new o(e.polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this.polygons=t.allPolygons()},r.prototype.inverse=function(){var e=this.clone();return e.inverseInPlace(),e},r.prototype.inverseInPlace=function(){this.polygons.map((function(e){e.flip()}))},r.prototype.copyTransformAttributes=function(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this},r.prototype.buildMeshGeometry=function(t,i,r){var n=this.matrix.clone();n.invert();var o,s,a,h=new e.Mesh(t,i),c=[],l=[],u=[],d=[],f=e.Vector3.Zero(),p=e.Vector3.Zero(),m=e.Vector2.Zero(),_=this.polygons,g=[0,0,0],v={},y=0,x={};r&&_.sort((function(e,t){return e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId}));for(var b=0,T=_.length;b<T;b++){o=_[b],x[o.shared.meshId]||(x[o.shared.meshId]={}),x[o.shared.meshId][o.shared.subMeshId]||(x[o.shared.meshId][o.shared.subMeshId]={indexStart:+(1/0),indexEnd:-(1/0),materialIndex:o.shared.materialIndex}),a=x[o.shared.meshId][o.shared.subMeshId];for(var A=2,E=o.vertices.length;A<E;A++){g[0]=0,g[1]=A-1,g[2]=A;for(var P=0;P<3;P++){f.copyFrom(o.vertices[g[P]].pos),p.copyFrom(o.vertices[g[P]].normal),m.copyFrom(o.vertices[g[P]].uv);var M=e.Vector3.TransformCoordinates(f,n),S=e.Vector3.TransformNormal(p,n);s=v[M.x+","+M.y+","+M.z],"undefined"!=typeof s&&u[3*s]===S.x&&u[3*s+1]===S.y&&u[3*s+2]===S.z&&d[2*s]===m.x&&d[2*s+1]===m.y||(c.push(M.x,M.y,M.z),d.push(m.x,m.y),u.push(p.x,p.y,p.z),s=v[M.x+","+M.y+","+M.z]=c.length/3-1),l.push(s),a.indexStart=Math.min(y,a.indexStart),a.indexEnd=Math.max(y,a.indexEnd),y++}}}if(h.setVerticesData(e.VertexBuffer.PositionKind,c),h.setVerticesData(e.VertexBuffer.NormalKind,u),h.setVerticesData(e.VertexBuffer.UVKind,d),h.setIndices(l),r){var C,R=0;h.subMeshes=new Array;for(var O in x){C=-1;for(var D in x[O])a=x[O][D],e.SubMesh.CreateFromIndices(a.materialIndex+R,a.indexStart,a.indexEnd-a.indexStart+1,h),C=Math.max(a.materialIndex,C);R+=++C}}return h},r.prototype.toMesh=function(e,t,i,r){var n=this.buildMeshGeometry(e,i,r);return n.material=t,n.position.copyFrom(this.position),n.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(n.rotationQuaternion=this.rotationQuaternion.clone()),n.scaling.copyFrom(this.scaling),n.computeWorldMatrix(!0),n},r})();e.CSG=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,o.postProcessScaleFactor,r,e.Texture.BILINEAR_SAMPLINGMODE,null,null),this._isRightEye=n,this._distortionFactors=o.distortionK,this._postProcessScaleFactor=o.postProcessScaleFactor,this._lensCenterOffset=o.lensCenterOffset,this.onSizeChangedObservable.add((function(){s.aspectRatio=.5*s.width/s.height,s._scaleIn=new e.Vector2(2,2/s.aspectRatio),s._scaleFactor=new e.Vector2(.5*(1/s._postProcessScaleFactor),.5*(1/s._postProcessScaleFactor)*s.aspectRatio),s._lensCenter=new e.Vector2(s._isRightEye?.5-.5*s._lensCenterOffset:.5+.5*s._lensCenterOffset,.5)})),this.onApplyObservable.add((function(e){e.setFloat2("LensCenter",s._lensCenter.x,s._lensCenter.y),e.setFloat2("Scale",s._scaleFactor.x,s._scaleFactor.y),e.setFloat2("ScaleIn",s._scaleIn.x,s._scaleIn.y),e.setFloat4("HmdWarpParam",s._distortionFactors[0],s._distortionFactors[1],s._distortionFactors[2],s._distortionFactors[3])}))}return __extends(i,t),i})(e.PostProcess);e.VRDistortionCorrectionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"})(e.JoystickAxis||(e.JoystickAxis={}));var t=e.JoystickAxis,i=(function(){function i(r){var n=this;r?this._leftJoystick=!0:this._leftJoystick=!1,this._joystickIndex=i._globalJoystickIndex,i._globalJoystickIndex++,this._axisTargetedByLeftAndRight=t.X,this._axisTargetedByUpAndDown=t.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new e.StringDictionary,this.deltaPosition=e.Vector3.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._rotationSpeed=25,this._inverseRotationSpeed=1/(this._rotationSpeed/1e3),this._rotateOnAxisRelativeToMesh=!1,this._onResize=function(e){i.vjCanvasWidth=window.innerWidth,i.vjCanvasHeight=window.innerHeight,i.vjCanvas.width=i.vjCanvasWidth,i.vjCanvas.height=i.vjCanvasHeight,i.halfWidth=i.vjCanvasWidth/2,i.halfHeight=i.vjCanvasHeight/2},i.vjCanvas||(window.addEventListener("resize",this._onResize,!1),i.vjCanvas=document.createElement("canvas"),i.vjCanvasWidth=window.innerWidth,i.vjCanvasHeight=window.innerHeight,i.vjCanvas.width=window.innerWidth,i.vjCanvas.height=window.innerHeight,i.vjCanvas.style.width="100%",i.vjCanvas.style.height="100%",i.vjCanvas.style.position="absolute",i.vjCanvas.style.backgroundColor="transparent",i.vjCanvas.style.top="0px",i.vjCanvas.style.left="0px",i.vjCanvas.style.zIndex="5",i.vjCanvas.style.msTouchAction="none",i.vjCanvas.setAttribute("touch-action","none"),i.vjCanvasContext=i.vjCanvas.getContext("2d"),i.vjCanvasContext.strokeStyle="#ffffff",i.vjCanvasContext.lineWidth=2,document.body.appendChild(i.vjCanvas)),i.halfWidth=i.vjCanvas.width/2,i.halfHeight=i.vjCanvas.height/2,this.pressed=!1,this._joystickColor="cyan",this._joystickPointerID=-1,this._joystickPointerPos=new e.Vector2(0,0),this._joystickPreviousPointerPos=new e.Vector2(0,0),this._joystickPointerStartPos=new e.Vector2(0,0),this._deltaJoystickVector=new e.Vector2(0,0),this._onPointerDownHandlerRef=function(e){n._onPointerDown(e)},this._onPointerMoveHandlerRef=function(e){n._onPointerMove(e)},this._onPointerOutHandlerRef=function(e){n._onPointerUp(e)},this._onPointerUpHandlerRef=function(e){n._onPointerUp(e)},i.vjCanvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),i.vjCanvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),i.vjCanvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),i.vjCanvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),i.vjCanvas.addEventListener("contextmenu",(function(e){e.preventDefault()}),!1),requestAnimationFrame((function(){n._drawVirtualJoystick()}))}return i.prototype.setJoystickSensibility=function(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)},i.prototype._onPointerDown=function(e){var t;e.preventDefault(),t=this._leftJoystick===!0?e.clientX<i.halfWidth:e.clientX>i.halfWidth,t&&this._joystickPointerID<0?(this._joystickPointerID=e.pointerId,this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):i._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))},i.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var i=this.reverseLeftRight?-1:1,r=i*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r))}var n=this.reverseUpDown?1:-1,o=n*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var s=this._touches.get(e.pointerId.toString());s&&(s.x=e.clientX,s.y=e.clientY)}},i.prototype._onPointerUp=function(e){if(this._joystickPointerID==e.pointerId)i.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-63,this._joystickPointerStartPos.y-63,126,126),i.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-41,this._joystickPreviousPointerPos.y-41,82,82),this._joystickPointerID=-1,this.pressed=!1;else{var t=this._touches.get(e.pointerId.toString());t&&i.vjCanvasContext.clearRect(t.prevX-43,t.prevY-43,86,86)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())},i.prototype.setJoystickColor=function(e){this._joystickColor=e},i.prototype.setActionOnTouch=function(e){this._action=e},i.prototype.setAxisForLeftRight=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=t.X}},i.prototype.setAxisForUpDown=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=t.Y}},i.prototype._clearCanvas=function(){this._leftJoystick?i.vjCanvasContext.clearRect(0,0,i.vjCanvasWidth/2,i.vjCanvasHeight):i.vjCanvasContext.clearRect(i.vjCanvasWidth/2,0,i.vjCanvasWidth,i.vjCanvasHeight)},i.prototype._drawVirtualJoystick=function(){var e=this;this.pressed&&this._touches.forEach((function(t){t.pointerId===e._joystickPointerID?(i.vjCanvasContext.clearRect(e._joystickPointerStartPos.x-63,e._joystickPointerStartPos.y-63,126,126),i.vjCanvasContext.clearRect(e._joystickPreviousPointerPos.x-41,e._joystickPreviousPointerPos.y-41,82,82),i.vjCanvasContext.beginPath(),i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.lineWidth=2,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,60,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerPos.x,e._joystickPointerPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),e._joystickPreviousPointerPos=e._joystickPointerPos.clone()):(i.vjCanvasContext.clearRect(t.prevX-43,t.prevY-43,86,86),i.vjCanvasContext.beginPath(),i.vjCanvasContext.fillStyle="white",i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle="red",i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((function(){e._drawVirtualJoystick()}))},i.prototype.releaseCanvas=function(){i.vjCanvas&&(i.vjCanvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),i.vjCanvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),i.vjCanvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),i.vjCanvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(i.vjCanvas),i.vjCanvas=null)},i._globalJoystickIndex=0,i})();e.VirtualJoystick=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addVirtualJoystick()}return __extends(t,e),t})(e.FreeCamera);e.VirtualJoysticksCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.prototype.getLeftJoystick=function(){return this._leftjoystick},t.prototype.getRightJoystick=function(){return this._rightjoystick},t.prototype.checkInputs=function(){if(this._leftjoystick){var t=this.camera,i=50*t._computeLocalCameraSpeed(),r=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),n=e.Vector3.TransformCoordinates(new e.Vector3(this._leftjoystick.deltaPosition.x*i,this._leftjoystick.deltaPosition.y*i,this._leftjoystick.deltaPosition.z*i),r);t.cameraDirection=t.cameraDirection.add(n),t.cameraRotation=t.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},t.prototype.attachControl=function(t,i){this._leftjoystick=new e.VirtualJoystick((!0)),this._leftjoystick.setAxisForUpDown(e.JoystickAxis.Z),this._leftjoystick.setAxisForLeftRight(e.JoystickAxis.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new e.VirtualJoystick((!1)),this._rightjoystick.setAxisForUpDown(e.JoystickAxis.X),this._rightjoystick.setAxisForLeftRight(e.JoystickAxis.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},t.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},t.prototype.getTypeName=function(){return"FreeCameraVirtualJoystickInput"},t.prototype.getSimpleName=function(){return"virtualJoystick"},t})();e.FreeCameraVirtualJoystickInput=t,e.CameraInputTypes.FreeCameraVirtualJoystickInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=this;e.call(this,t,"anaglyph",null,["leftSampler"],i,r[1],n,o,s),this._passedProcess=r[0]._rigPostProcess,this.onApplyObservable.add((function(e){e.setTextureFromPostProcess("leftSampler",a._passedProcess)}))}return __extends(t,e),t})(e.PostProcess);e.AnaglyphPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._scene=e}return t.prototype.render=function(t,i,r){var n=this;void 0===r&&(r=!1);var o=this._scene,s=this._scene.getEngine(),a=null!==s.getCaps().instancedArrays&&null!==i.visibleInstances[t._id]&&void 0!==i.visibleInstances[t._id];if(this.isReady(t,a)){var h=t.getRenderingMesh(),c=t.getMaterial();if(s.enableEffect(this._effect),this._effect.setFloat("offset",r?0:h.outlineWidth),this._effect.setColor4("color",r?h.overlayColor:h.outlineColor,r?h.overlayAlpha:1),this._effect.setMatrix("viewProjection",o.getTransformMatrix()),h.useBones&&h.computeBonesUsingShaders&&this._effect.setMatrices("mBones",h.skeleton.getTransformMatrices(h)),h._bind(t,this._effect,e.Material.TriangleFillMode),c&&c.needAlphaTesting()){var l=c.getAlphaTestTexture();this._effect.setTexture("diffuseSampler",l),this._effect.setMatrix("diffuseMatrix",l.getTextureMatrix())}h._processRendering(t,this._effect,e.Material.TriangleFillMode,i,a,(function(e,t){n._effect.setMatrix("world",t)}))}},t.prototype.isReady=function(t,i){var r=[],n=[e.VertexBuffer.PositionKind,e.VertexBuffer.NormalKind],o=t.getMesh(),s=t.getMaterial();s&&s.needAlphaTesting()&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2"))),o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var a=r.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color"],["diffuseSampler"],a)),this._effect.isReady()},t})();e.OutlineRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this;e.SceneLoader.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,t,(function(e,t,r){n.loadedMeshes=e,n.loadedParticleSystems=t,n.loadedSkeletons=r,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()}),null,(function(){n.onError&&n.onError(n),r()}))},t})();e.MeshAssetTask=t;var i=(function(){function t(e,t){this.name=e,this.url=t,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this;e.Tools.LoadFile(this.url,(function(e){n.text=e,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()}),null,t.database,!1,(function(){n.onError&&n.onError(n),r()}))},t})();e.TextFileAssetTask=i;var r=(function(){function t(e,t){this.name=e,this.url=t,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this;e.Tools.LoadFile(this.url,(function(e){n.data=e,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()}),null,t.database,!0,(function(){n.onError&&n.onError(n),r()}))},t})();e.BinaryFileAssetTask=r;var n=(function(){function t(e,t){this.name=e,this.url=t,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this,o=new Image;e.Tools.SetCorsBehavior(this.url,o),o.onload=function(){n.image=o,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()},o.onerror=function(){n.onError&&n.onError(n),r()},o.src=this.url},t})();e.ImageAssetTask=n;var o=(function(){function t(t,i,r,n,o){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),this.name=t,this.url=i,this.noMipmap=r,this.invertY=n,this.samplingMode=o,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this,o=function(){n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()},s=function(){n.onError&&n.onError(n),r()};this.texture=new e.Texture(this.url,t,this.noMipmap,this.invertY,this.samplingMode,o,s)},t})();e.TextureAssetTask=o;var s=(function(){function t(e,t,i,r,n){this.name=e,this.url=t,this.extensions=i,this.noMipmap=r,this.files=n,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this,o=function(){n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()},s=function(){n.onError&&n.onError(n),r()};this.texture=new e.CubeTexture(this.url,t,this.extensions,this.noMipmap,this.files,o,s)},t})();e.CubeTextureAssetTask=s;var a=(function(){function s(e){this.tasks=new Array,this.waitingTasksCount=0,this.useDefaultLoadingScreen=!0,this._scene=e}return s.prototype.addMeshTask=function(e,i,r,n){var o=new t(e,i,r,n);return this.tasks.push(o),o},s.prototype.addTextFileTask=function(e,t){var r=new i(e,t);return this.tasks.push(r),r},s.prototype.addBinaryFileTask=function(e,t){var i=new r(e,t);return this.tasks.push(i),i},s.prototype.addImageTask=function(e,t){var i=new n(e,t);return this.tasks.push(i),i},s.prototype.addTextureTask=function(t,i,r,n,s){void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE);var a=new o(t,i,r,n,s);return this.tasks.push(a),a},s.prototype._decreaseWaitingTasksCount=function(){this.waitingTasksCount--,0===this.waitingTasksCount&&(this.onFinish&&this.onFinish(this.tasks),this._scene.getEngine().hideLoadingUI())},s.prototype._runTask=function(e){var t=this;e.run(this._scene,(function(){t.onTaskSuccess&&t.onTaskSuccess(e),t._decreaseWaitingTasksCount()}),(function(){t.onTaskError&&t.onTaskError(e),t._decreaseWaitingTasksCount()}))},s.prototype.reset=function(){return this.tasks=new Array,this},s.prototype.load=function(){if(this.waitingTasksCount=this.tasks.length,0===this.waitingTasksCount)return this.onFinish&&this.onFinish(this.tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e<this.tasks.length;e++){var t=this.tasks[e];this._runTask(t)}return this},s})();e.AssetsManager=a})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.compensateDistortion=!0}return Object.defineProperty(t.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftHMatrix",{get:function(){var t=this.hScreenSize/4-this.lensSeparationDistance/2,i=4*t/this.hScreenSize;return e.Matrix.Translation(i,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightHMatrix",{get:function(){var t=this.hScreenSize/4-this.lensSeparationDistance/2,i=4*t/this.hScreenSize;return e.Matrix.Translation(-i,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftPreViewMatrix",{get:function(){return e.Matrix.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightPreViewMatrix",{get:function(){return e.Matrix.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),t.GetDefault=function(){var e=new t;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e},t})();e.VRCameraMetrics=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this;void 0===o&&(o=!1),void 0===s&&(s={}),t.call(this,i,r,n),this.webVROptions=s,this._vrDevice=null,this._cacheState=null,this._vrEnabled=!1,this._attached=!1,this._positionOffset=r,this.getEngine().initWebVR(),this.getEngine().vrDisplaysPromise?(this._frameData=new VRFrameData,this.getEngine().vrDisplaysPromise.then((function(t){if(t.length>0){if(a._vrEnabled=!0,a.webVROptions.displayName){var i=t.some((function(e){return e.displayName===a.webVROptions.displayName&&(a._vrDevice=e,!0)}));i||(a._vrDevice=t[0],e.Tools.Warn("Display "+a.webVROptions.displayName+" was not found. Using "+a._vrDevice.displayName))}else a._vrDevice=t[0];a.setCameraRigMode(e.Camera.RIG_MODE_WEBVR,{vrDisplay:a._vrDevice,frameData:a._frameData}),a._attached&&a.getEngine().enableVR(a._vrDevice)}else e.Tools.Error("No WebVR devices found!")}))):e.Tools.Error("WebVR is not enabled on your browser"),this.rotationQuaternion=new e.Quaternion,this._quaternionCache=new e.Quaternion}return __extends(i,t),i.prototype._checkInputs=function(){if(this._vrEnabled&&this._vrDevice.getFrameData(this._frameData)){var e=this._frameData.pose;e&&e.orientation&&(this._cacheState=e,this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0],this._cacheState.orientation[1],-this._cacheState.orientation[2],-this._cacheState.orientation[3]),this.webVROptions.trackPosition&&this._cacheState.position&&(this.position.copyFromFloats(this._cacheState.position[0],this._cacheState.position[1],-this._cacheState.position[2]),this.webVROptions.positionScale&&this.position.scaleInPlace(this.webVROptions.positionScale),this.position.addInPlace(this._positionOffset)))}t.prototype._checkInputs.call(this)},i.prototype.attachControl=function(i,r){t.prototype.attachControl.call(this,i,r),this._attached=!0,r=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&r,this._vrEnabled&&this.getEngine().enableVR(this._vrDevice)},i.prototype.detachControl=function(e){t.prototype.detachControl.call(this,e),this._vrEnabled=!1,this._attached=!1,this.getEngine().disableVR()},i.prototype.requestVRFullscreen=function(t){e.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.")},i.prototype.getTypeName=function(){return"WebVRFreeCamera"},i.prototype.resetToCurrentRotation=function(){this._vrDevice.resetPose()},i.prototype.setPositionOffset=function(e){e?this._positionOffset=e:this._positionOffset.copyFrom(this.position)},i})(e.FreeCamera);e.WebVRFreeCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){void 0===e&&(e=0),this.priority=e,this.apply=function(e){return!0}}return e})();e.SceneOptimization=t;var i=(function(e){function t(t,i){var r=this;void 0===t&&(t=0),void 0===i&&(i=1024),e.call(this,t),this.priority=t,this.maximumSize=i,this.apply=function(e){for(var t=!0,i=0;i<e.textures.length;i++){var n=e.textures[i];if(n.canRescale){var o=n.getSize(),s=Math.max(o.width,o.height);s>r.maximumSize&&(n.scale(.5),t=!1)}}return t}}return __extends(t,e),t})(t);e.TextureOptimization=i;var r=(function(e){function t(t,i){var r=this;void 0===t&&(t=0),void 0===i&&(i=2),e.call(this,t),this.priority=t,this.maximumScale=i,this._currentScale=1,this.apply=function(e){return r._currentScale++,e.getEngine().setHardwareScalingLevel(r._currentScale),r._currentScale>=r.maximumScale}}return __extends(t,e),t})(t);e.HardwareScalingOptimization=r;var n=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.shadowsEnabled=!1,!0}}return __extends(t,e),t})(t);e.ShadowsOptimization=n;var o=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.postProcessesEnabled=!1,!0}}return __extends(t,e),t})(t);e.PostProcessesOptimization=o;var s=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.lensFlaresEnabled=!1,!0}}return __extends(t,e),t})(t);e.LensFlaresOptimization=s;var a=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.particlesEnabled=!1,!0}}return __extends(t,e),t})(t);e.ParticlesOptimization=a;var h=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.renderTargetsEnabled=!1,!0}}return __extends(t,e),t})(t);e.RenderTargetsOptimization=h;var c=(function(t){function i(){var r=this;t.apply(this,arguments),this._canBeMerged=function(t){if(!(t instanceof e.Mesh))return!1;var i=t;return!(!i.isVisible||!i.isEnabled())&&(!(i.instances.length>0)&&(!i.skeleton&&!i.hasLODLevels&&!i.parent))},this.apply=function(t,n){for(var o=t.meshes.slice(0),s=o.length,a=0;a<s;a++){var h=new Array,c=o[a];if(r._canBeMerged(c)){h.push(c);for(var l=a+1;l<s;l++){var u=o[l];r._canBeMerged(u)&&u.material===c.material&&u.checkCollisions===c.checkCollisions&&(h.push(u),s--,o.splice(l,1),l--)}h.length<2||e.Mesh.MergeMeshes(h)}}return void 0!=n?n&&t.createOrUpdateSelectionOctree():i.UpdateSelectionTree&&t.createOrUpdateSelectionOctree(),!0}}return __extends(i,t),Object.defineProperty(i,"UpdateSelectionTree",{get:function(){return i._UpdateSelectionTree},set:function(e){i._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),i._UpdateSelectionTree=!1,i})(t);e.MergeMeshesOptimization=c;var l=(function(){function e(e,t){void 0===e&&(e=60),void 0===t&&(t=2e3),this.targetFrameRate=e,this.trackerDuration=t,this.optimizations=new Array}return e.LowDegradationAllowed=function(t){var r=new e(t),h=0;return r.optimizations.push(new c(h)),r.optimizations.push(new n(h)),r.optimizations.push(new s(h)),h++,r.optimizations.push(new o(h)),r.optimizations.push(new a(h)),h++,r.optimizations.push(new i(h,1024)),r},e.ModerateDegradationAllowed=function(t){var l=new e(t),u=0;return l.optimizations.push(new c(u)),l.optimizations.push(new n(u)),l.optimizations.push(new s(u)),u++,l.optimizations.push(new o(u)),l.optimizations.push(new a(u)),u++,l.optimizations.push(new i(u,512)),u++,l.optimizations.push(new h(u)),u++,l.optimizations.push(new r(u,2)),l},e.HighDegradationAllowed=function(t){var l=new e(t),u=0;return l.optimizations.push(new c(u)),l.optimizations.push(new n(u)),l.optimizations.push(new s(u)),u++,l.optimizations.push(new o(u)),l.optimizations.push(new a(u)),u++,l.optimizations.push(new i(u,256)),u++,l.optimizations.push(new h(u)),u++,l.optimizations.push(new r(u,4)),l},e})();e.SceneOptimizerOptions=l;var u=(function(){function e(){}return e._CheckCurrentState=function(t,i,r,n,o){if(t.getEngine().getFps()>=i.targetFrameRate)return void(n&&n());for(var s=!0,a=!0,h=0;h<i.optimizations.length;h++){var c=i.optimizations[h];c.priority===r&&(a=!1,s=s&&c.apply(t))}return a?void(o&&o()):(s&&r++,void t.executeWhenReady((function(){setTimeout((function(){e._CheckCurrentState(t,i,r,n,o)}),i.trackerDuration)})))},e.OptimizeAsync=function(t,i,r,n){i||(i=l.ModerateDegradationAllowed()),t.executeWhenReady((function(){setTimeout((function(){e._CheckCurrentState(t,i,0,r,n)}),i.trackerDuration)}))},e})();e.SceneOptimizer=u})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(e,t){this.distance=e,this.mesh=t}return e})();e.MeshLODLevel=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){void 0===a&&(a=!0),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,s,!a,h),this.format=o,this._texture=s.getEngine().createRawTexture(i,r,n,o,a,h,c),this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE}return __extends(i,t),i.prototype.update=function(e){this.getScene().getEngine().updateRawTexture(this._texture,e,this.format,this._invertY)},i.CreateLuminanceTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE,o,s,a,h);
},i.CreateLuminanceAlphaTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA,o,s,a,h)},i.CreateAlphaTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_ALPHA,o,s,a,h)},i.CreateRGBTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGB,o,s,a,h)},i.CreateRGBATexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGBA,o,s,a,h)},i})(e.Texture);e.RawTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i){e.call(this,t.x,t.y),this.index=i}return __extends(t,e),t})(e.Vector2),i=(function(){function i(){this.elements=new Array}return i.prototype.add=function(e){var i=this,r=new Array;return e.forEach((function(e){if(0===r.length||!e.equalsWithEpsilon(r[0])){var n=new t(e,i.elements.length);r.push(n),i.elements.push(n)}})),r},i.prototype.computeBounds=function(){var t=new e.Vector2(this.elements[0].x,this.elements[0].y),i=new e.Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(e){e.x<t.x?t.x=e.x:e.x>i.x&&(i.x=e.x),e.y<t.y?t.y=e.y:e.y>i.y&&(i.y=e.y)})),{min:t,max:i,width:i.x-t.x,height:i.y-t.y}},i})(),r=(function(){function t(){}return t.Rectangle=function(t,i,r,n){return[new e.Vector2(t,i),new e.Vector2(r,i),new e.Vector2(r,n),new e.Vector2(t,n)]},t.Circle=function(t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=32);for(var o=new Array,s=0,a=2*Math.PI/n,h=0;h<n;h++)o.push(new e.Vector2(i+Math.cos(s)*t,r+Math.sin(s)*t)),s-=a;return o},t.Parse=function(t){var i,r=t.split(/[^-+eE\.\d]+/).map(parseFloat).filter((function(e){return!isNaN(e)})),n=[];for(i=0;i<(2147483646&r.length);i+=2)n.push(new e.Vector2(r[i],r[i+1]));return n},t.StartingAt=function(t,i){return e.Path2.StartingAt(t,i)},t})();e.Polygon=r;var n=(function(){function t(t,r,n){this._points=new i,this._outlinepoints=new i,this._holes=[],this._epoints=new Array,this._eholes=new Array,this._name=t,this._scene=n;var o;o=r instanceof e.Path2?r.getPoints():r,this._addToepoint(o),this._points.add(o),this._outlinepoints.add(o)}return t.prototype._addToepoint=function(e){for(var t=0,i=e;t<i.length;t++){var r=i[t];this._epoints.push(r.x,r.y)}},t.prototype.addHole=function(e){this._points.add(e);var t=new i;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this},t.prototype.build=function(t,i){var r=this;void 0===t&&(t=!1);var n=new e.Mesh(this._name,this._scene),o=[],s=[],a=[],h=this._points.computeBounds();this._points.elements.forEach((function(e){o.push(0,1,0),s.push(e.x,0,e.y),a.push((e.x-h.min.x)/h.width,(e.y-h.min.y)/h.height)}));for(var c=[],l=Earcut.earcut(this._epoints,this._eholes,2),u=0;u<l.length;u++)c.push(l[u]);if(i>0){var d=s.length/3;this._points.elements.forEach((function(e){o.push(0,-1,0),s.push(e.x,-i,e.y),a.push(1-(e.x-h.min.x)/h.width,1-(e.y-h.min.y)/h.height)}));for(var f=c.length,u=0;u<f;u+=3){var p=c[u+0],m=c[u+1],_=c[u+2];c.push(_+d),c.push(m+d),c.push(p+d)}this.addSide(s,o,a,c,h,this._outlinepoints,i,!1),this._holes.forEach((function(e){r.addSide(s,o,a,c,h,e,i,!0)}))}return n.setVerticesData(e.VertexBuffer.PositionKind,s,t),n.setVerticesData(e.VertexBuffer.NormalKind,o,t),n.setVerticesData(e.VertexBuffer.UVKind,a,t),n.setIndices(c),n},t.prototype.addSide=function(t,i,r,n,o,s,a,h){for(var c=t.length/3,l=0,u=0;u<s.elements.length;u++){var d,f=s.elements[u];d=u+1>s.elements.length-1?s.elements[0]:s.elements[u+1],t.push(f.x,0,f.y),t.push(f.x,-a,f.y),t.push(d.x,0,d.y),t.push(d.x,-a,d.y);var p=new e.Vector3(f.x,0,f.y),m=new e.Vector3(d.x,0,d.y),_=m.subtract(p),g=new e.Vector3(0,1,0),v=e.Vector3.Cross(_,g);v=v.normalize(),r.push(l/o.width,0),r.push(l/o.width,1),l+=_.length(),r.push(l/o.width,0),r.push(l/o.width,1),h?(i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),n.push(c),n.push(c+2),n.push(c+1),n.push(c+1),n.push(c+2),n.push(c+3)):(i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),n.push(c),n.push(c+1),n.push(c+2),n.push(c+1),n.push(c+3),n.push(c+2)),c+=4}},t})();e.PolygonMeshBuilder=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){void 0===r&&(r=2),this.maxDepth=r,this.dynamicContent=new Array,this._maxBlockCapacity=i||64,this._selectionContent=new e.SmartArray(1024),this._creationFunc=t}return t.prototype.update=function(e,i,r){t._CreateBlocks(e,i,r,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)},t.prototype.addMesh=function(e){for(var t=0;t<this.blocks.length;t++){var i=this.blocks[t];i.addEntry(e)}},t.prototype.select=function(e,t){this._selectionContent.reset();for(var i=0;i<this.blocks.length;i++){var r=this.blocks[i];r.select(e,this._selectionContent,t)}return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},t.prototype.intersects=function(e,t,i){this._selectionContent.reset();for(var r=0;r<this.blocks.length;r++){var n=this.blocks[r];n.intersects(e,t,this._selectionContent,i)}return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},t.prototype.intersectsRay=function(e){this._selectionContent.reset();for(var t=0;t<this.blocks.length;t++){var i=this.blocks[t];i.intersectsRay(e,this._selectionContent)}return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},t._CreateBlocks=function(t,i,r,n,o,s,a,h){a.blocks=new Array;for(var c=new e.Vector3((i.x-t.x)/2,(i.y-t.y)/2,(i.z-t.z)/2),l=0;l<2;l++)for(var u=0;u<2;u++)for(var d=0;d<2;d++){var f=t.add(c.multiplyByFloats(l,u,d)),p=t.add(c.multiplyByFloats(l+1,u+1,d+1)),m=new e.OctreeBlock(f,p,n,o+1,s,h);m.addEntries(r),a.blocks.push(m)}},t.CreationFuncForMeshes=function(e,t){!e.isBlocked&&e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},t.CreationFuncForSubMeshes=function(e,t){e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},t})();e.Octree=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=n,this._creationFunc=o,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}return Object.defineProperty(t.prototype,"capacity",{get:function(){return this._capacity},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minPoint",{get:function(){return this._minPoint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxPoint",{get:function(){return this._maxPoint},enumerable:!0,configurable:!0}),t.prototype.addEntry=function(e){if(this.blocks)for(var t=0;t<this.blocks.length;t++){var i=this.blocks[t];i.addEntry(e)}else this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()},t.prototype.addEntries=function(e){for(var t=0;t<e.length;t++){var i=e[t];this.addEntry(i)}},t.prototype.select=function(t,i,r){if(e.BoundingBox.IsInFrustum(this._boundingVectors,t)){if(this.blocks){for(var n=0;n<this.blocks.length;n++){var o=this.blocks[n];o.select(t,i,r)}return}r?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}},t.prototype.intersects=function(t,i,r,n){if(e.BoundingBox.IntersectsSphere(this._minPoint,this._maxPoint,t,i)){if(this.blocks){for(var o=0;o<this.blocks.length;o++){var s=this.blocks[o];s.intersects(t,i,r,n)}return}n?r.concat(this.entries):r.concatWithNoDuplicate(this.entries)}},t.prototype.intersectsRay=function(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(var i=0;i<this.blocks.length;i++){var r=this.blocks[i];r.intersectsRay(e,t)}return}t.concatWithNoDuplicate(this.entries)}},t.prototype.createInnerBlocks=function(){e.Octree._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc)},t})();e.OctreeBlock=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,i,"blur",["screenSize","direction","blurWidth"],null,o,s,a,h,c),this.direction=r,this.blurWidth=n,this.onApplyObservable.add((function(e){e.setFloat2("screenSize",l.width,l.height),e.setVector2("direction",l.direction),e.setFloat("blurWidth",l.blurWidth)}))}return __extends(i,t),i})(e.PostProcess);e.BlurPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c,l,u){var d=this;t.call(this,i,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,h,c,l,u),this.color=n,this.depth=o,this.colorLevel=s,this.onActivateObservable.add((function(t){d._refRexture=d._refRexture||new e.Texture(r,t.getScene())})),this.onApplyObservable.add((function(e){e.setColor3("baseColor",d.color),e.setFloat("depth",d.depth),e.setFloat("colorLevel",d.colorLevel),e.setTexture("refractionSampler",d._refRexture)}))}return __extends(i,t),i.prototype.dispose=function(e){this._refRexture&&this._refRexture.dispose(),t.prototype.dispose.call(this,e)},i})(e.PostProcess);e.RefractionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"blackAndWhite",null,null,i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.BlackAndWhitePostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var h=this;e.call(this,t,"convolution",["kernel","screenSize"],null,r,n,o,s,a),this.kernel=i,this.onApply=function(e){e.setFloat2("screenSize",h.width,h.height),e.setArray("kernel",h.kernel)}}return __extends(t,e),t.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],t.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],t.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],t.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],t.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],t.GaussianKernel=[0,1,0,1,1,1,0,1,0],t})(e.PostProcess);e.ConvolutionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var h=this;e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,s,a),this.kernelMatrix=i,this.onApply=function(e){e.setMatrix("kernelMatrix",h.kernelMatrix)}}return __extends(t,e),t})(e.PostProcess);e.FilterPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=this;e.call(this,t,"fxaa",["texelSize"],null,i,r,n,o,s),this.onSizeChangedObservable.add((function(){a.texelWidth=1/a.width,a.texelHeight=1/a.height})),this.onApplyObservable.add((function(e){e.setFloat2("texelSize",a.texelWidth,a.texelHeight)}))}return __extends(t,e),t})(e.PostProcess);e.FxaaPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;t.call(this,i,"stereoscopicInterlace",["stepSize"],["camASampler"],1,r[1],o,s,a,n?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=r[0]._rigPostProcess,this._stepSize=new e.Vector2(1/this.width,1/this.height),this.onSizeChangedObservable.add((function(){h._stepSize=new e.Vector2(1/h.width,1/h.height)})),this.onApplyObservable.add((function(e){e.setTextureFromPostProcess("camASampler",h._passedProcess),e.setFloat2("stepSize",h._stepSize.x,h._stepSize.y)}))}return __extends(i,t),i})(e.PostProcess);e.StereoscopicInterlacePostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.size=t,this.position=i,this.alphaMode=e.Engine.ALPHA_ONEONE,this.dispose=function(){this.texture&&this.texture.dispose();var e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)},this.color=r||new e.Color3(1,1,1),this.texture=n?new e.Texture(n,o.getScene(),(!0)):null,this._system=o,o.lensFlares.push(this)}return t})();e.LensFlare=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=r,this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&r.activeCamera.layerMask)};var n=r.getEngine(),o=[];o.push(1,1),o.push(-1,1),o.push(-1,-1),o.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(n,o,e.VertexBuffer.PositionKind,(!1),(!1),2);var s=[];s.push(0),s.push(1),s.push(2),s.push(0),s.push(2),s.push(3),this._indexBuffer=n.createIndexBuffer(s),this._effect=n.createEffect("lensFlare",[e.VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEmitter=function(){return this._emitter},t.prototype.setEmitter=function(e){this._emitter=e},t.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},t.prototype.computeEffectivePosition=function(t){var i=this.getEmitterPosition();return i=e.Vector3.Project(i,e.Matrix.Identity(),this._scene.getTransformMatrix(),t),this._positionX=i.x,this._positionY=i.y,i=e.Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder,t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,i.x+=this.viewportBorder,i.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),i.z>0&&(this._positionX>t.x&&this._positionX<t.x+t.width&&this._positionY>t.y&&this._positionY<t.y+t.height,!0)},t.prototype._isVisible=function(){if(!this._isEnabled)return!1;var t=this.getEmitterPosition(),i=t.subtract(this._scene.activeCamera.globalPosition),r=i.length();i.normalize();var n=new e.Ray(this._scene.activeCamera.globalPosition,i),o=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!o.hit||o.distance>r},t.prototype.render=function(){if(!this._effect.isReady())return!1;var t=this._scene.getEngine(),i=this._scene.activeCamera.viewport,r=i.toGlobal(t.getRenderWidth(!0),t.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n,o;n=this._positionX<this.borderLimit+r.x?this.borderLimit+r.x-this._positionX:this._positionX>r.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0,o=this._positionY<this.borderLimit+r.y?this.borderLimit+r.y-this._positionY:this._positionY>r.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0;var s=n>o?n:o;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);var a=1-s/this.borderLimit;if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var h=r.x+r.width/2,c=r.y+r.height/2,l=h-this._positionX,u=c-this._positionY;t.enableEffect(this._effect),t.setState(!1),t.setDepthBuffer(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var d=0;d<this.lensFlares.length;d++){var f=this.lensFlares[d];t.setAlphaMode(f.alphaMode);var p=h-l*f.position,m=c-u*f.position,_=f.size,g=f.size*t.getAspectRatio(this._scene.activeCamera,!0),v=2*(p/(r.width+2*r.x))-1,y=1-2*(m/(r.height+2*r.y)),x=e.Matrix.FromValues(_/2,0,0,0,0,g/2,0,0,0,0,1,0,v,y,0,1);this._effect.setMatrix("viewportMatrix",x),this._effect.setTexture("textureSampler",f.texture),this._effect.setFloat4("color",f.color.r*a,f.color.g*a,f.color.b*a,1),t.draw(!0,0,6)}return t.setDepthBuffer(!0),t.setAlphaMode(e.Engine.ALPHA_DISABLE),!0},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];for(t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();var i=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(i,1)},t.Parse=function(i,r,n){var o=r.getLastEntryByID(i.emitterId),s=i.name||"lensFlareSystem#"+i.emitterId,a=new t(s,o,r);a.id=i.id||s,a.borderLimit=i.borderLimit;for(var h=0;h<i.flares.length;h++){var c=i.flares[h];new e.LensFlare(c.size,c.position,e.Color3.FromArray(c.color),n+c.textureName,a)}return a},t.prototype.serialize=function(){var t={};t.id=this.id,t.name=this.name,t.emitterId=this.getEmitter().id,t.borderLimit=this.borderLimit,t.flares=[];for(var i=0;i<this.lensFlares.length;i++){var r=this.lensFlares[i];t.flares.push({size:r.size,position:r.position,color:r.color.asArray(),textureName:e.Tools.GetFilename(r.texture.name)})}return t},t})();e.LensFlareSystem=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,r,n),this._quaternionCache=new e.Quaternion,this.inputs.addDeviceOrientation()}return __extends(i,t),i.prototype.getTypeName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(t){var i=this;void 0===t&&(t=e.Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new e.Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(e){t[e]?i._initialQuaternion[e]*=-1:i._initialQuaternion[e]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i})(e.FreeCamera);e.DeviceOrientationCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault()),t.call(this,i,r,n),s.compensateDistortion=o,this.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:s})}return __extends(i,t),i.prototype.getTypeName=function(){return"VRDeviceOrientationFreeCamera"},i})(e.DeviceOrientationCamera);e.VRDeviceOrientationFreeCamera=t;var i=(function(t){function i(i,r,n,o,s,a,h,c){void 0===h&&(h=!0),void 0===c&&(c=e.VRCameraMetrics.GetDefault()),t.call(this,i,r,n,o,s,a),c.compensateDistortion=h,this.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:c}),this.inputs.addVRDeviceOrientation()}return __extends(i,t),i.prototype.getTypeName=function(){return"VRDeviceOrientationArcRotateCamera"},i})(e.ArcRotateCamera);e.VRDeviceOrientationArcRotateCamera=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addGamepad()}return __extends(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadAngularSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadMoveSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getTypeName=function(){return"UniversalCamera"},t})(e.TouchCamera);e.UniversalCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){var t=this;this.babylonGamepads=[],this.oneGamepadConnected=!1,this.isMonitoring=!1,this.gamepadEventSupported="GamepadEvent"in window,this.gamepadSupportAvailable=navigator.getGamepads||!!navigator.webkitGetGamepads||!!navigator.msGetGamepads||!!navigator.webkitGamepads,this._callbackGamepadConnected=e,this.gamepadSupportAvailable&&(this.gamepadEventSupported?(this._onGamepadConnectedEvent=function(e){t._onGamepadConnected(e)},this._onGamepadDisonnectedEvent=function(e){t._onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisonnectedEvent,!1)):this._startMonitoringGamepads())}return e.prototype.dispose=function(){e.gamepadDOMInfo&&document.body.removeChild(e.gamepadDOMInfo),this._onGamepadConnectedEvent&&(window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.removeEventListener("gamepaddisconnected",this._onGamepadDisonnectedEvent,!1),this._onGamepadConnectedEvent=null,this._onGamepadDisonnectedEvent=null)},e.prototype._onGamepadConnected=function(e){var t=this._addNewGamepad(e.gamepad);this._callbackGamepadConnected&&this._callbackGamepadConnected(t),this._startMonitoringGamepads()},e.prototype._addNewGamepad=function(t){this.oneGamepadConnected||(this.oneGamepadConnected=!0,e.gamepadDOMInfo&&(document.body.removeChild(e.gamepadDOMInfo),e.gamepadDOMInfo=null));var i,r=t.id.search("Xbox One")!==-1;return i=r||t.id.search("Xbox 360")!==-1||t.id.search("xinput")!==-1?new a(t.id,t.index,t,r):new n(t.id,t.index,t),this.babylonGamepads.push(i),i},e.prototype._onGamepadDisconnected=function(e){for(var t in this.babylonGamepads)if(this.babylonGamepads[t].index==e.gamepad.index){this.babylonGamepads.splice(+t,1);break}0==this.babylonGamepads.length&&this._stopMonitoringGamepads()},e.prototype._startMonitoringGamepads=function(){this.isMonitoring||(this.isMonitoring=!0,this._checkGamepadsStatus())},e.prototype._stopMonitoringGamepads=function(){this.isMonitoring=!1},e.prototype._checkGamepadsStatus=function(){var e=this;this._updateGamepadObjects();for(var t in this.babylonGamepads)this.babylonGamepads[t].update();this.isMonitoring&&(window.requestAnimationFrame?window.requestAnimationFrame((function(){e._checkGamepadsStatus()})):window.mozRequestAnimationFrame?window.mozRequestAnimationFrame((function(){e._checkGamepadsStatus()})):window.webkitRequestAnimationFrame&&window.webkitRequestAnimationFrame((function(){e._checkGamepadsStatus()})))},e.prototype._updateGamepadObjects=function(){for(var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[],t=0;t<e.length;t++)if(e[t])if(e[t].index in this.babylonGamepads)this.babylonGamepads[t].browserGamepad=e[t];else{var i=this._addNewGamepad(e[t]);this._callbackGamepadConnected&&this._callbackGamepadConnected(i)}},e})();e.Gamepads=t;var i=(function(){function e(e,t){this.x=e,this.y=t}return e})();e.StickValues=i;var r=(function(){function e(e,t,i,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=1),void 0===o&&(o=2),void 0===s&&(s=3),this.id=e,this.index=t,this.browserGamepad=i,this._leftStickAxisX=r,this._leftStickAxisY=n,this._rightStickAxisX=o,this._rightStickAxisY=s,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e})();e.Gamepad=r;var n=(function(e){function t(t,i,r){e.call(this,t,i,r),this.id=t,this.index=i,this.gamepad=r,this._buttons=new Array(r.buttons.length)}return __extends(t,e),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(this._onbuttondown&&1===e&&this._onbuttondown(i),this._onbuttonup&&0===e&&this._onbuttonup(i)),e},t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t<this._buttons.length;t++)this._buttons[t]=this._setButtonValue(this.gamepad.buttons[t].value,this._buttons[t],t)},t})(r);e.GenericPad=n,(function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.Start=4]="Start",e[e.Back=5]="Back",e[e.LB=6]="LB",e[e.RB=7]="RB",e[e.LeftStick=8]="LeftStick",e[e.RightStick=9]="RightStick"})(e.Xbox360Button||(e.Xbox360Button={}));var o=e.Xbox360Button;!(function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Left=2]="Left",e[e.Right=3]="Right"})(e.Xbox360Dpad||(e.Xbox360Dpad={}));var s=e.Xbox360Dpad,a=(function(e){function t(t,i,r,n){void 0===n&&(n=!1),e.call(this,t,i,r,0,1,n?3:2,n?4:3),this._leftTrigger=0,this._rightTrigger=0,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this._isXboxOnePad=n}return __extends(t,e),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!0,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(this._onbuttondown&&1===e&&this._onbuttondown(i),this._onbuttonup&&0===e&&this._onbuttonup(i)),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(this._ondpaddown&&1===e&&this._ondpaddown(i),this._ondpadup&&0===e&&this._ondpadup(i)),e},Object.defineProperty(t.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,o.A)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,o.B)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,o.X)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,o.Y)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,o.Start)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,o.Back)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,o.LB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,o.RB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,o.LeftStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,o.RightStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,s.Up)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,s.Down)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,s.Left)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,s.Right)},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this),this._isXboxOnePad?(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.axes[2],this.rightTrigger=this.browserGamepad.axes[5],this.buttonBack=this.browserGamepad.buttons[9].value,this.buttonStart=this.browserGamepad.buttons[8].value,this.buttonLeftStick=this.browserGamepad.buttons[6].value,this.buttonRightStick=this.browserGamepad.buttons[7].value,this.dPadUp=this.browserGamepad.buttons[11].value,this.dPadDown=this.browserGamepad.buttons[12].value,this.dPadLeft=this.browserGamepad.buttons[13].value,this.dPadRight=this.browserGamepad.buttons[14].value):(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,
this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value)},t})(r);e.Xbox360Pad=a})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){e.Tools.Warn("Deprecated. Please use Universal Camera instead."),t.call(this,i,r,n)}return __extends(i,t),Object.defineProperty(i.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadAngularSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadMoveSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),i.prototype.getTypeName=function(){return"GamepadCamera"},i})(e.UniversalCamera);e.GamepadCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},this._scene=t,this._audioEngine=e.Engine.audioEngine,this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))}return t.prototype.getFrequencyBinCount=function(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0},t.prototype.getByteFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs},t.prototype.getByteTimeDomainData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime},t.prototype.getFloatFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs},t.prototype.drawDebugCanvas=function(){var e=this;if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=function(){e.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc)){var t=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(var i=0;i<this.getFrequencyBinCount();i++){var r=t[i],n=r/this.BARGRAPHAMPLITUDE,o=this.DEBUGCANVASSIZE.height*n,s=this.DEBUGCANVASSIZE.height-o-1,a=this.DEBUGCANVASSIZE.width/this.getFrequencyBinCount(),h=i/this.getFrequencyBinCount()*360;this._debugCanvasContext.fillStyle="hsl("+h+", 100%, 50%)",this._debugCanvasContext.fillRect(i*a,s,a,o)}}},t.prototype.stopDebugCanvas=function(){this._debugCanvas&&(this._scene.unregisterBeforeRender(this._registerFunc),this._registerFunc=null,document.body.removeChild(this._debugCanvas),this._debugCanvas=null,this._debugCanvasContext=null)},t.prototype.connectAudioNodes=function(e,t){this._audioEngine.canUseWebAudio&&(e.connect(this._webAudioAnalyser),this._webAudioAnalyser.connect(t))},t.prototype.dispose=function(){this._audioEngine.canUseWebAudio&&this._webAudioAnalyser.disconnect()},t})();e.Analyser=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){var r=this;void 0===i&&(i=e.Engine.TEXTURETYPE_FLOAT),this._viewMatrix=e.Matrix.Zero(),this._projectionMatrix=e.Matrix.Zero(),this._transformMatrix=e.Matrix.Zero(),this._worldViewProjection=e.Matrix.Zero(),this._scene=t;var n=t.getEngine();this._depthMap=new e.RenderTargetTexture("depthMap",{width:n.getRenderWidth(),height:n.getRenderHeight()},this._scene,(!1),(!0),i),this._depthMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.onClearObservable.add((function(t){t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}));var o=function(t){var i=t.getRenderingMesh(),n=r._scene,o=n.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id];if(r.isReady(t,a)){o.enableEffect(r._effect),i._bind(t,r._effect,e.Material.TriangleFillMode);var h=t.getMaterial();if(r._effect.setMatrix("viewProjection",n.getTransformMatrix()),r._effect.setFloat("far",n.activeCamera.maxZ),h&&h.needAlphaTesting()){var c=h.getAlphaTestTexture();r._effect.setTexture("diffuseSampler",c),r._effect.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&r._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),i._processRendering(t,r._effect,e.Material.TriangleFillMode,s,a,(function(e,t){return r._effect.setMatrix("world",t)}))}}};this._depthMap.customRenderFunction=function(e,t){var i;for(i=0;i<e.length;i++)o(e.data[i]);for(i=0;i<t.length;i++)o(t.data[i])}}return t.prototype.isReady=function(t,i){var r=t.getMaterial();if(r.disableDepthWrite)return!1;var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMesh();s.getScene();r&&r.needAlphaTesting()&&(n.push("#define ALPHATEST"),s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),s.numBoneInfluencers>4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","far"],["diffuseSampler"],a)),this._effect.isReady()},t.prototype.getDepthMap=function(){return this._depthMap},t.prototype.dispose=function(){this._depthMap.dispose()},t})();e.DepthRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,r.getEngine(),i),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.radius=1e-4,this.area=.0075,this.fallOff=1e-6,this.base=.5,this._firstUpdate=!0,this._scene=r,this._createRandomTexture(),this._depthTexture=r.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,h=n.combineRatio||n;this._ratio={ssaoRatio:a,combineRatio:h},this._originalColorPostProcess=new e.PassPostProcess("SSAOOriginalSceneColor",h,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),(!1)),this._createSSAOPostProcess(a),this._createBlurPostProcess(a),this._createSSAOCombinePostProcess(h),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOOriginalSceneColorEffect,function(){return s._originalColorPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAORenderEffect,function(){return s._ssaoPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOBlurHRenderEffect,function(){return s._blurHPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOBlurVRenderEffect,function(){return s._blurVPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOCombineRenderEffect,function(){return s._ssaoCombinePostProcess},(!0))),r.postProcessRenderPipelineManager.addPipeline(this),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,o)}return __extends(i,t),i.prototype.getBlurHPostProcess=function(){return e.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists"),null},i.prototype.getBlurVPostProcess=function(){return e.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists"),null},i.prototype.dispose=function(e){void 0===e&&(e=!1);for(var t=0;t<this._scene.cameras.length;t++){var i=this._scene.cameras[t];this._originalColorPostProcess.dispose(i),this._ssaoPostProcess.dispose(i),this._blurHPostProcess.dispose(i),this._blurVPostProcess.dispose(i),this._ssaoCombinePostProcess.dispose(i)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras)},i.prototype._createBlurPostProcess=function(t){for(var i=this,r=[],n=-8;n<8;n++)r.push(2*n);this._blurHPostProcess=new e.PostProcess("BlurH","ssao",["outSize","samplerOffsets"],["depthSampler"],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16"),this._blurHPostProcess.onApply=function(e){e.setFloat("outSize",i._ssaoCombinePostProcess.width),e.setTexture("depthSampler",i._depthTexture),i._firstUpdate&&e.setArray("samplerOffsets",r)},this._blurVPostProcess=new e.PostProcess("BlurV","ssao",["outSize","samplerOffsets"],["depthSampler"],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define BILATERAL_BLUR\n#define SAMPLES 16"),this._blurVPostProcess.onApply=function(e){e.setFloat("outSize",i._ssaoCombinePostProcess.height),e.setTexture("depthSampler",i._depthTexture),i._firstUpdate&&(e.setArray("samplerOffsets",r),i._firstUpdate=!1)}},i.prototype._createSSAOPostProcess=function(t){var i=this,r=16,n=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271],o=1/r;this._ssaoPostProcess=new e.PostProcess("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],t,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define SAMPLES "+r+"\n#define SSAO");new e.Vector2(0,0);this._ssaoPostProcess.onApply=function(e){i._firstUpdate&&(e.setArray3("sampleSphere",n),e.setFloat("samplesFactor",o),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",i.totalStrength),e.setFloat("radius",i.radius),e.setFloat("area",i.area),e.setFloat("fallOff",i.fallOff),e.setFloat("base",i.base),e.setTexture("textureSampler",i._depthTexture),e.setTexture("randomSampler",i._randomTexture)}},i.prototype._createSSAOCombinePostProcess=function(t){var i=this;this._ssaoCombinePostProcess=new e.PostProcess("ssaoCombine","ssaoCombine",[],["originalColor"],t,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1)),this._ssaoCombinePostProcess.onApply=function(e){e.setTextureFromPostProcess("originalColor",i._originalColorPostProcess)}},i.prototype._createRandomTexture=function(){var t=512;this._randomTexture=new e.DynamicTexture("SSAORandomTexture",t,this._scene,(!1),e.Texture.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=e.Texture.WRAP_ADDRESSMODE,this._randomTexture.wrapV=e.Texture.WRAP_ADDRESSMODE;for(var i=this._randomTexture.getContext(),r=function(e,t){return Math.random()*(t-e)+e},n=e.Vector3.Zero(),o=0;o<t;o++)for(var s=0;s<t;s++)n.x=Math.floor(255*r(-1,1)),n.y=Math.floor(255*r(-1,1)),n.z=Math.floor(255*r(-1,1)),i.fillStyle="rgb("+n.x+", "+n.y+", "+n.z+")",i.fillRect(o,s,1,1);this._randomTexture.update(!1)},__decorate([e.serialize()],i.prototype,"totalStrength",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serialize()],i.prototype,"area",void 0),__decorate([e.serialize()],i.prototype,"fallOff",void 0),__decorate([e.serialize()],i.prototype,"base",void 0),__decorate([e.serialize()],i.prototype,"_ratio",void 0),i})(e.PostProcessRenderPipeline);e.SSAORenderingPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a,h,c,l,u){var d=this;void 0===a&&(a=100),void 0===h&&(h=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,r,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,o,h,c,l,"#define NUM_SAMPLES "+a),this._screenCoordinates=e.Vector2.Zero(),this.customMeshPosition=e.Vector3.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=new Array,this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,u=null===o?u:o.getScene();var c=u.getEngine();this._viewPort=new e.Viewport(0,0,1,1).toGlobal(c.getRenderWidth(),c.getRenderHeight()),this.mesh=null!==s?s:i.CreateDefaultMesh("VolumetricLightScatteringMesh",u),this._createPass(u,n.passRatio||n),this.onActivate=function(e){d.isSupported||d.dispose(e),d.onActivate=null},this.onApplyObservable.add((function(e){d._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",d._volumetricLightScatteringRTT),e.setFloat("exposure",d.exposure),e.setFloat("decay",d.decay),e.setFloat("weight",d.weight),e.setFloat("density",d.density),e.setVector2("meshPositionOnScreen",d._screenCoordinates)}))}return __extends(i,t),Object.defineProperty(i.prototype,"useDiffuseColor",{get:function(){return e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(t){e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),i.prototype.isReady=function(t,i){var r=t.getMesh();if(r===this.mesh)return r.material.isReady(r);var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMaterial();s&&(s.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=r.getScene().getEngine().createEffect({vertexElement:"depth",fragmentElement:"volumetricLightScatteringPass"},o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a)),this._volumetricLightScatteringPass.isReady()},i.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},i.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},i.prototype.dispose=function(e){var i=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);i!==-1&&e.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),t.prototype.dispose.call(this,e)},i.prototype.getPass=function(){return this._volumetricLightScatteringRTT},i.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1},i.prototype._createPass=function(t,i){var r=this,n=t.getEngine();this._volumetricLightScatteringRTT=new e.RenderTargetTexture("volumetricLightScatteringMap",{width:n.getRenderWidth()*i,height:n.getRenderHeight()*i},t,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,t.customRenderTargets.push(this._volumetricLightScatteringRTT);var o,s=function(t){var i=t.getRenderingMesh();if(!r._meshExcluded(i)){var n=i.getScene(),o=n.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id];if(r.isReady(t,a)){var h=r._volumetricLightScatteringPass;if(i===r.mesh&&(h=t.getMaterial().getEffect()),o.enableEffect(h),i._bind(t,h,e.Material.TriangleFillMode),i===r.mesh)t.getMaterial().bind(i.getWorldMatrix(),i);else{var c=t.getMaterial();if(r._volumetricLightScatteringPass.setMatrix("viewProjection",n.getTransformMatrix()),c&&c.needAlphaTesting()){var l=c.getAlphaTestTexture();r._volumetricLightScatteringPass.setTexture("diffuseSampler",l),l&&r._volumetricLightScatteringPass.setMatrix("diffuseMatrix",l.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&r._volumetricLightScatteringPass.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}i._processRendering(t,r._volumetricLightScatteringPass,e.Material.TriangleFillMode,s,a,(function(e,t){return h.setMatrix("world",t)}))}}}},a=new e.Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){o=t.clearColor,t.clearColor=a})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){t.clearColor=o})),this._volumetricLightScatteringRTT.customRenderFunction=function(i,r,n){var o,a=t.getEngine();for(o=0;o<i.length;o++)s(i.data[o]);for(a.setAlphaTesting(!0),o=0;o<r.length;o++)s(r.data[o]);if(a.setAlphaTesting(!1),n.length){for(o=0;o<n.length;o++){var h=n.data[o];h._alphaIndex=h.getMesh().alphaIndex,h._distanceToCamera=h.getBoundingInfo().boundingSphere.centerWorld.subtract(t.activeCamera.position).length()}var c=n.data.slice(0,n.length);for(c.sort((function(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0})),a.setAlphaMode(e.Engine.ALPHA_COMBINE),o=0;o<c.length;o++)s(c[o]);a.setAlphaMode(e.Engine.ALPHA_DISABLE)}}},i.prototype._updateMeshScreenCoordinates=function(t){var i,r=t.getTransformMatrix();i=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;var n=e.Vector3.Project(i,e.Matrix.Identity(),r,this._viewPort);this._screenCoordinates.x=n.x/this._viewPort.width,this._screenCoordinates.y=n.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)},i.CreateDefaultMesh=function(t,i){var r=e.Mesh.CreatePlane(t,1,i);r.billboardMode=e.AbstractMesh.BILLBOARDMODE_ALL;var n=new e.StandardMaterial(t+"Material",i);return n.emissiveColor=new e.Color3(1,1,1),r.material=n,r},__decorate([e.serializeAsVector3()],i.prototype,"customMeshPosition",void 0),__decorate([e.serialize()],i.prototype,"useCustomMeshPosition",void 0),__decorate([e.serialize()],i.prototype,"invert",void 0),__decorate([e.serializeAsMeshReference()],i.prototype,"mesh",void 0),__decorate([e.serialize()],i.prototype,"excludedMeshes",void 0),__decorate([e.serialize()],i.prototype,"exposure",void 0),__decorate([e.serialize()],i.prototype,"decay",void 0),__decorate([e.serialize()],i.prototype,"weight",void 0),__decorate([e.serialize()],i.prototype,"density",void 0),i})(e.PostProcess);e.VolumetricLightScatteringPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this;void 0===o&&(o=1),t.call(this,n.getEngine(),i),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._scene=n,this._depthTexture=n.enableDepthRenderer().getDepthMap(),r.grain_texture?this._grainTexture=r.grain_texture:this._createGrainTexture(),this._edgeBlur=r.edge_blur?r.edge_blur:0,this._grainAmount=r.grain_amount?r.grain_amount:0,this._chromaticAberration=r.chromatic_aberration?r.chromatic_aberration:0,this._distortion=r.distortion?r.distortion:0,this._highlightsGain=void 0!==r.dof_gain?r.dof_gain:-1,this._highlightsThreshold=r.dof_threshold?r.dof_threshold:1,this._dofDistance=void 0!==r.dof_focus_distance?r.dof_focus_distance:-1,this._dofAperture=r.dof_aperture?r.dof_aperture:1,this._dofDarken=r.dof_darken?r.dof_darken:0,this._dofPentagon=void 0===r.dof_pentagon||r.dof_pentagon,this._blurNoise=void 0===r.blur_noise||r.blur_noise,this._createChromaticAberrationPostProcess(o),this._createHighlightsPostProcess(o),this._createDepthOfFieldPostProcess(o/4),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),this.LensChromaticAberrationEffect,function(){return a._chromaticAberrationPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),this.HighlightsEnhancingEffect,function(){return a._highlightsPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),this.LensDepthOfFieldEffect,function(){return a._depthOfFieldPostProcess},(!0))),this._highlightsGain===-1&&this._disableEffect(this.HighlightsEnhancingEffect,null),n.postProcessRenderPipelineManager.addPipeline(this),s&&n.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,s)}return __extends(i,t),i.prototype.setEdgeBlur=function(e){this._edgeBlur=e},i.prototype.disableEdgeBlur=function(){this._edgeBlur=0},i.prototype.setGrainAmount=function(e){this._grainAmount=e},i.prototype.disableGrain=function(){this._grainAmount=0},i.prototype.setChromaticAberration=function(e){this._chromaticAberration=e},i.prototype.disableChromaticAberration=function(){this._chromaticAberration=0},i.prototype.setEdgeDistortion=function(e){this._distortion=e},i.prototype.disableEdgeDistortion=function(){this._distortion=0},i.prototype.setFocusDistance=function(e){this._dofDistance=e},i.prototype.disableDepthOfField=function(){this._dofDistance=-1},i.prototype.setAperture=function(e){this._dofAperture=e},i.prototype.setDarkenOutOfFocus=function(e){this._dofDarken=e},i.prototype.enablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n")},i.prototype.disablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect()},i.prototype.enableNoiseBlur=function(){this._blurNoise=!0},i.prototype.disableNoiseBlur=function(){this._blurNoise=!1},i.prototype.setHighlightsGain=function(e){this._highlightsGain=e},i.prototype.setHighlightsThreshold=function(e){this._highlightsGain===-1&&(this._highlightsGain=1),this._highlightsThreshold=e},i.prototype.disableHighlights=function(){this._highlightsGain=-1},i.prototype.dispose=function(e){void 0===e&&(e=!1),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=void 0,this._highlightsPostProcess=void 0,this._depthOfFieldPostProcess=void 0,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()},i.prototype._createChromaticAberrationPostProcess=function(t){var i=this;this._chromaticAberrationPostProcess=new e.PostProcess("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height"],[],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1)),this._chromaticAberrationPostProcess.onApply=function(e){e.setFloat("chromatic_aberration",i._chromaticAberration),e.setFloat("screen_width",i._scene.getEngine().getRenderingCanvas().width),e.setFloat("screen_height",i._scene.getEngine().getRenderingCanvas().height)}},i.prototype._createHighlightsPostProcess=function(t){var i=this;this._highlightsPostProcess=new e.PostProcess("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.onApply=function(e){e.setFloat("gain",i._highlightsGain),e.setFloat("threshold",i._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",i._chromaticAberrationPostProcess),e.setFloat("screen_width",i._scene.getEngine().getRenderingCanvas().width),e.setFloat("screen_height",i._scene.getEngine().getRenderingCanvas().height)}},i.prototype._createDepthOfFieldPostProcess=function(t){var i=this;this._depthOfFieldPostProcess=new e.PostProcess("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1)),this._depthOfFieldPostProcess.onApply=function(e){e.setTexture("depthSampler",i._depthTexture),e.setTexture("grainSampler",i._grainTexture),e.setTextureFromPostProcess("textureSampler",i._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",i._depthOfFieldPostProcess),e.setFloat("grain_amount",i._grainAmount),e.setBool("blur_noise",i._blurNoise),e.setFloat("screen_width",i._scene.getEngine().getRenderingCanvas().width),e.setFloat("screen_height",i._scene.getEngine().getRenderingCanvas().height),e.setFloat("distortion",i._distortion),e.setBool("dof_enabled",i._dofDistance!==-1),e.setFloat("screen_distance",1/(.1-1/i._dofDistance)),e.setFloat("aperture",i._dofAperture),e.setFloat("darken",i._dofDarken),e.setFloat("edge_blur",i._edgeBlur),e.setBool("highlights",i._highlightsGain!==-1),e.setFloat("near",i._scene.activeCamera.minZ),e.setFloat("far",i._scene.activeCamera.maxZ)}},i.prototype._createGrainTexture=function(){var t=512;this._grainTexture=new e.DynamicTexture("LensNoiseTexture",t,this._scene,(!1),e.Texture.BILINEAR_SAMPLINGMODE),this._grainTexture.wrapU=e.Texture.WRAP_ADDRESSMODE,this._grainTexture.wrapV=e.Texture.WRAP_ADDRESSMODE;for(var i,r=this._grainTexture.getContext(),n=function(e,t){return Math.random()*(t-e)+e},o=0;o<t;o++)for(var s=0;s<t;s++)i=Math.floor(255*n(.42,.58)),r.fillStyle="rgb("+i+", "+i+", "+i+")",r.fillRect(o,s,1,1);this._grainTexture.update(!1)},i})(e.PostProcessRenderPipeline);e.LensRenderingPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){var c=this;t.call(this,i,"colorCorrection",null,["colorTable"],n,o,s,a,h),this._colorTableTexture=new e.Texture(r,o.getScene(),(!0),(!1),e.Texture.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this.onApply=function(e){e.setTexture("colorTable",c._colorTableTexture)}}return __extends(i,t),i})(e.PostProcess);e.ColorCorrectionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){t.call(this,i,r,o),this.interaxialDistance=n,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphFreeCamera"},i})(e.FreeCamera);e.AnaglyphFreeCamera=t;var i=(function(t){function i(i,r,n,o,s,a,h){t.call(this,i,r,n,o,s,h),this.interaxialDistance=a,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphArcRotateCamera"},i})(e.ArcRotateCamera);e.AnaglyphArcRotateCamera=i;var r=(function(t){function i(i,r,n,o){t.call(this,i,r,o),this.interaxialDistance=n,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphGamepadCamera"},i})(e.GamepadCamera);e.AnaglyphGamepadCamera=r;var n=(function(t){function i(i,r,n,o){t.call(this,i,r,o),this.interaxialDistance=n,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphUniversalCamera"},i})(e.UniversalCamera);e.AnaglyphUniversalCamera=n;var o=(function(t){function i(i,r,n,o,s){t.call(this,i,r,s),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicFreeCamera"},i})(e.FreeCamera);e.StereoscopicFreeCamera=o;var s=(function(t){function i(i,r,n,o,s,a,h,c){t.call(this,i,r,n,o,s,c),this.interaxialDistance=a,this.isStereoscopicSideBySide=h,this.setCameraRigMode(h?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicArcRotateCamera"},i})(e.ArcRotateCamera);e.StereoscopicArcRotateCamera=s;var a=(function(t){function i(i,r,n,o,s){t.call(this,i,r,s),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicGamepadCamera"},i})(e.GamepadCamera);e.StereoscopicGamepadCamera=a;var h=(function(t){function i(i,r,n,o,s){t.call(this,i,r,s),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicUniversalCamera"},i})(e.UniversalCamera);e.StereoscopicUniversalCamera=h})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a){var h=this;void 0===s&&(s=null),t.call(this,n.getEngine(),r),this.gaussCoeff=.3,this.gaussMean=1,this.gaussStandDev=.8,this.gaussMultiplier=4,this.exposure=1,this.minimumLuminance=1,this.maximumLuminance=1e20,this.luminanceIncreaserate=.5,this.luminanceDecreaseRate=.5,this.brightThreshold=.8,this._needUpdate=!0,this._scene=n,this._createBrightPassPostProcess(n,o),this._createDownSampleX4PostProcess(n,o),this._createGaussianBlurPostProcess(n,o),this._createTextureAdderPostProcess(n,o),this._createLuminanceGeneratorPostProcess(n),this._createHDRPostProcess(n,o),null===s?this._originalPostProcess=new e.PassPostProcess("hdr",o,null,e.Texture.BILINEAR_SAMPLINGMODE,n.getEngine(),(!1)):this._originalPostProcess=s,this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRPassPostProcess",function(){return h._originalPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRBrightPass",function(){return h._brightPassPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRDownSampleX4",function(){return h._downSampleX4PostProcess;
},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRGaussianBlurH",function(){return h._guassianBlurHPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRGaussianBlurV",function(){return h._guassianBlurVPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRTextureAdder",function(){return h._textureAdderPostProcess},(!0)));for(var c=function(t){h.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRDownSampler"+t,function(){return h._downSamplePostProcesses[t]},(!0)))},l=i.LUM_STEPS-1;l>=0;l--)c(l);this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDR",function(){return h._hdrPostProcess},(!0))),n.postProcessRenderPipelineManager.addPipeline(this),null!==a&&n.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(r,a),this.update()}return __extends(i,t),i.prototype.update=function(){this._needUpdate=!0},i.prototype.getCurrentLuminance=function(){return this._hdrCurrentLuminance},i.prototype.getOutputLuminance=function(){return this._hdrOutputLuminance},i.prototype.dispose=function(){this._originalPostProcess=void 0,this._brightPassPostProcess=void 0,this._downSampleX4PostProcess=void 0,this._guassianBlurHPostProcess=void 0,this._guassianBlurVPostProcess=void 0,this._textureAdderPostProcess=void 0;for(var e=i.LUM_STEPS-1;e>=0;e--)this._downSamplePostProcesses[e]=void 0;this._hdrPostProcess=void 0,this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras)},i.prototype._createHDRPostProcess=function(t,i){var r=this,n=0;this._hdrOutputLuminance=-1,this._hdrCurrentLuminance=1,this._hdrPostProcess=new e.PostProcess("hdr","hdr",["exposure","avgLuminance"],["otherSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define HDR"),this._hdrPostProcess.onApply=function(i){if(r._hdrOutputLuminance<0)r._hdrOutputLuminance=r._hdrCurrentLuminance;else{var o=(n-(n+t.getEngine().getDeltaTime()))/1e3;r._hdrCurrentLuminance<r._hdrOutputLuminance+r.luminanceDecreaseRate*o?r._hdrOutputLuminance+=r.luminanceDecreaseRate*o:r._hdrCurrentLuminance>r._hdrOutputLuminance-r.luminanceIncreaserate*o?r._hdrOutputLuminance-=r.luminanceIncreaserate*o:r._hdrOutputLuminance=r._hdrCurrentLuminance}r._hdrOutputLuminance=e.MathTools.Clamp(r._hdrOutputLuminance,r.minimumLuminance,r.maximumLuminance),n+=t.getEngine().getDeltaTime(),i.setTextureFromPostProcess("textureSampler",r._textureAdderPostProcess),i.setTextureFromPostProcess("otherSampler",r._originalPostProcess),i.setFloat("exposure",r.exposure),i.setFloat("avgLuminance",r._hdrOutputLuminance),r._needUpdate=!1}},i.prototype._createTextureAdderPostProcess=function(t,i){var r=this;this._textureAdderPostProcess=new e.PostProcess("hdr","hdr",[],["otherSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define TEXTURE_ADDER"),this._textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r._originalPostProcess)}},i.prototype._createDownSampleX4PostProcess=function(t,i){var r=this,n=new Array(32);this._downSampleX4PostProcess=new e.PostProcess("hdr","hdr",["dsOffsets"],[],i/4,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define DOWN_SAMPLE_X4"),this._downSampleX4PostProcess.onApply=function(e){if(r._needUpdate)for(var t=0,i=-2;i<2;i++)for(var o=-2;o<2;o++)n[t]=(i+.5)*(1/r._downSampleX4PostProcess.width),n[t+1]=(o+.5)*(1/r._downSampleX4PostProcess.height),t+=2;e.setArray2("dsOffsets",n)}},i.prototype._createBrightPassPostProcess=function(t,i){var r=this,n=new Array(8),o=function(e){if(r._needUpdate){var t=1/r._brightPassPostProcess.width,i=1/r._brightPassPostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i}e.setArray2("dsOffsets",n),e.setFloat("brightThreshold",r.brightThreshold)};this._brightPassPostProcess=new e.PostProcess("hdr","hdr",["dsOffsets","brightThreshold"],[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define BRIGHT_PASS"),this._brightPassPostProcess.onApply=o},i.prototype._createLuminanceGeneratorPostProcess=function(t){var r,n=this,o=i.LUM_STEPS,s=new Array(8),a=new Array(18);this._downSamplePostProcesses=new Array(o);var h=function(e,t){var i=1/e,r=1/t;s[0]=-.5*i,s[1]=.5*r,s[2]=.5*i,s[3]=.5*r,s[4]=-.5*i,s[5]=-.5*r,s[6]=.5*i,s[7]=-.5*r},c=function(e,t){for(var i=0,r=-1;r<2;r++)for(var n=-1;n<2;n++)a[i]=r/e,a[i+1]=n/t,i+=2},l=function(e){n._needUpdate&&h(n._textureAdderPostProcess.width,n._textureAdderPostProcess.height),e.setTextureFromPostProcess("textureSampler",n._textureAdderPostProcess),e.setArray2("lumOffsets",s)},u=function(e){var t=e;return function(e){h(n._downSamplePostProcesses[t].width,n._downSamplePostProcesses[t].height),c(n._downSamplePostProcesses[t].width,n._downSamplePostProcesses[t].height),r=.5/n._downSamplePostProcesses[t].width,e.setTextureFromPostProcess("textureSampler",n._downSamplePostProcesses[t+1]),e.setFloat("halfDestPixelSize",r),e.setArray2("dsOffsets",a)}},d=function(i){var r=t.getEngine().readPixels(0,0,1,1),o=new e.Vector4(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(r[0]*o.x+r[1]*o.y+r[2]*o.z+r[3]*o.w)/100},f={width:Math.pow(3,o-1),height:Math.pow(3,o-1)};this._downSamplePostProcesses[o-1]=new e.PostProcess("hdr","hdr",["lumOffsets"],[],f,null,e.Texture.NEAREST_SAMPLINGMODE,t.getEngine(),(!1),"#define LUMINANCE_GENERATOR",e.Engine.TEXTURETYPE_FLOAT),this._downSamplePostProcesses[o-1].onApply=l;for(var p=o-2;p>=0;p--){var m=Math.pow(3,p);f={width:m,height:m};var _="#define DOWN_SAMPLE\n";0===p&&(_+="#define FINAL_DOWN_SAMPLE\n"),this._downSamplePostProcesses[p]=new e.PostProcess("hdr","hdr",["dsOffsets","halfDestPixelSize"],[],f,null,e.Texture.NEAREST_SAMPLINGMODE,t.getEngine(),(!1),_,e.Engine.TEXTURETYPE_FLOAT),this._downSamplePostProcesses[p].onApply=u(p),0===p&&(this._downSamplePostProcesses[p].onAfterRender=d)}},i.prototype._createGaussianBlurPostProcess=function(t,i){var r=this,n=new Array(9),o=new Array(9),s=new Array(9),a=["blurOffsets","blurWeights","multiplier"],h=function(e){for(var i={width:t.getEngine().getRenderWidth(),height:t.getEngine().getRenderHeight()},r=0;r<9;r++){var s=(r-4)*(1/(e===!0?i.height:i.width));e?o[r]=s:n[r]=s}},c=function(){for(var e=0,t=0;t<9;t++)e=(t-4)/4,s[t]=r.gaussCoeff*(1/Math.sqrt(2*Math.PI*r.gaussStandDev))*Math.exp(-((e-r.gaussMean)*(e-r.gaussMean))/(2*r.gaussStandDev*r.gaussStandDev))},l=function(e){return function(t){r._needUpdate&&(c(),h(e)),t.setArray("blurOffsets",e?o:n),t.setArray("blurWeights",s),t.setFloat("multiplier",r.gaussMultiplier)}};this._guassianBlurHPostProcess=new e.PostProcess("hdr","hdr",a,[],i/4,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_H"),this._guassianBlurHPostProcess.onApply=l(!1),this._guassianBlurVPostProcess=new e.PostProcess("hdr","hdr",a,[],i/4,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_V"),this._guassianBlurVPostProcess.onApply=l(!0)},i.LUM_STEPS=6,i})(e.PostProcessRenderPipeline);e.HDRRenderingPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.edges=new Array,this.edgesConnectedCount=0}return e})(),i=(function(){function i(e,t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),this._generateEdgesLines()}return i.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new e.ShaderMaterial("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},i.prototype.dispose=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[e.VertexBuffer.PositionKind]=null),t=this._buffers[e.VertexBuffer.NormalKind],t&&(t.dispose(),this._buffers[e.VertexBuffer.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},i.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},i.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)?1:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)?2:-1},i.prototype._checkEdge=function(t,i,r,n,o){var s;if(void 0===i)s=!0;else{var a=e.Vector3.Dot(r[t],r[i]);s=a<this._epsilon}if(s){var h=this._linesPositions.length/3,c=n.subtract(o);c.normalize(),this._linesPositions.push(n.x),this._linesPositions.push(n.y),this._linesPositions.push(n.z),this._linesPositions.push(n.x),this._linesPositions.push(n.y),this._linesPositions.push(n.z),this._linesPositions.push(o.x),this._linesPositions.push(o.y),this._linesPositions.push(o.z),this._linesPositions.push(o.x),this._linesPositions.push(o.y),this._linesPositions.push(o.z),this._linesNormals.push(o.x),this._linesNormals.push(o.y),this._linesNormals.push(o.z),this._linesNormals.push(-1),this._linesNormals.push(o.x),this._linesNormals.push(o.y),this._linesNormals.push(o.z),this._linesNormals.push(1),this._linesNormals.push(n.x),this._linesNormals.push(n.y),this._linesNormals.push(n.z),this._linesNormals.push(-1),this._linesNormals.push(n.x),this._linesNormals.push(n.y),this._linesNormals.push(n.z),this._linesNormals.push(1),this._linesIndices.push(h),this._linesIndices.push(h+1),this._linesIndices.push(h+2),this._linesIndices.push(h),this._linesIndices.push(h+2),this._linesIndices.push(h+3)}},i.prototype._generateEdgesLines=function(){var i,r,n=this._source.getVerticesData(e.VertexBuffer.PositionKind),o=this._source.getIndices(),s=new Array,a=new Array;for(i=0;i<o.length;i+=3){r=new t;var h=o[i],c=o[i+1],l=o[i+2];r.p0=new e.Vector3(n[3*h],n[3*h+1],n[3*h+2]),r.p1=new e.Vector3(n[3*c],n[3*c+1],n[3*c+2]),r.p2=new e.Vector3(n[3*l],n[3*l+1],n[3*l+2]);var u=e.Vector3.Cross(r.p1.subtract(r.p0),r.p2.subtract(r.p1));u.normalize(),a.push(u),s.push(r)}for(i=0;i<s.length;i++){r=s[i];for(var d=i+1;d<s.length;d++){var f=s[d];if(3===r.edgesConnectedCount)break;if(3!==f.edgesConnectedCount)for(var p=o[3*d],m=o[3*d+1],_=o[3*d+2],g=0;g<3;g++){var v;if(void 0===r.edges[g]){switch(g){case 0:v=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p0,r.p1,f.p0,f.p1,f.p2):this._processEdgeForAdjacencies(o[3*i],o[3*i+1],p,m,_);break;case 1:v=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p1,r.p2,f.p0,f.p1,f.p2):this._processEdgeForAdjacencies(o[3*i+1],o[3*i+2],p,m,_);break;case 2:v=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p2,r.p0,f.p0,f.p1,f.p2):this._processEdgeForAdjacencies(o[3*i+2],o[3*i],p,m,_)}if(v!==-1&&(r.edges[g]=d,f.edges[v]=i,r.edgesConnectedCount++,f.edgesConnectedCount++,3===r.edgesConnectedCount))break}}}}for(i=0;i<s.length;i++){var y=s[i];this._checkEdge(i,y.edges[0],a,y.p0,y.p1),this._checkEdge(i,y.edges[1],a,y.p1,y.p2),this._checkEdge(i,y.edges[2],a,y.p2,y.p0)}var x=this._source.getScene().getEngine();this._buffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(x,this._linesPositions,e.VertexBuffer.PositionKind,(!1)),this._buffers[e.VertexBuffer.NormalKind]=new e.VertexBuffer(x,this._linesNormals,e.VertexBuffer.NormalKind,(!1),(!1),4),this._ib=x.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length},i.prototype.render=function(){if(this._lineShader.isReady()){var t=this._source.getScene(),i=t.getEngine();this._lineShader._preBind(),i.bindBuffers(this._buffers,this._ib,this._lineShader.getEffect()),t.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),t.activeCamera.mode===e.Camera.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",i.getAspectRatio(t.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),i.draw(!0,0,this._indicesCount),this._lineShader.unbind(),i.setDepthWrite(!0)}},i})();e.EdgesRenderer=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"})(e.TonemappingOperator||(e.TonemappingOperator={}));var t=e.TonemappingOperator,i=(function(i){function r(r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),i.call(this,r,"tonemap",["_ExposureAdjustment"],null,1,s,a,h,!0,u,c),this._operator=n,this.exposureAdjustment=o;var u="#define ";this._operator===t.Hable?u+="HABLE_TONEMAPPING":this._operator===t.Reinhard?u+="REINHARD_TONEMAPPING":this._operator===t.HejiDawson?u+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===t.Photographic&&(u+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(u),this.onApply=function(e){e.setFloat("_ExposureAdjustment",l.exposureAdjustment)}}return __extends(r,i),r})(e.PostProcess);e.TonemapPostProcess=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){var o=this;void 0===n&&(n=!0),this.name=t,this._viewMatrix=e.Matrix.Identity(),this._target=e.Vector3.Zero(),this._add=e.Vector3.Zero(),this.invertYAxis=!1,this.position=e.Vector3.Zero(),this._scene=r,this._scene.reflectionProbes.push(this),this._renderTargetTexture=new e.RenderTargetTexture(t,i,r,n,(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT,(!0)),this._renderTargetTexture.onBeforeRenderObservable.add((function(t){switch(t){case 0:o._add.copyFromFloats(1,0,0);break;case 1:o._add.copyFromFloats(-1,0,0);break;case 2:o._add.copyFromFloats(0,o.invertYAxis?1:-1,0);break;case 3:o._add.copyFromFloats(0,o.invertYAxis?-1:1,0);break;case 4:o._add.copyFromFloats(0,0,1);break;case 5:o._add.copyFromFloats(0,0,-1)}o._attachedMesh&&o.position.copyFrom(o._attachedMesh.getAbsolutePosition()),o.position.addToRef(o._add,o._target),e.Matrix.LookAtLHToRef(o.position,o._target,e.Vector3.Up(),o._viewMatrix),r.setTransformMatrix(o._viewMatrix,o._projectionMatrix)})),this._renderTargetTexture.onAfterUnbindObservable.add((function(){r.updateTransformMatrix(!0)})),this._projectionMatrix=e.Matrix.PerspectiveFovLH(Math.PI/2,1,r.activeCamera.minZ,r.activeCamera.maxZ)}return Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(e){this._renderTargetTexture.refreshRate=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},enumerable:!0,configurable:!0}),t.prototype.attachToMesh=function(e){this._attachedMesh=e},t.prototype.dispose=function(){var e=this._scene.reflectionProbes.indexOf(this);e!==-1&&this._scene.reflectionProbes.splice(e,1),this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null)},t})();e.ReflectionProbe=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a){this.idx=0,this.color=new e.Color4(1,1,1,1),this.position=e.Vector3.Zero(),this.rotation=e.Vector3.Zero(),this.scaling=new e.Vector3(1,1,1),this.uvs=new e.Vector4(0,0,1,1),this.velocity=e.Vector3.Zero(),this.alive=!0,this.isVisible=!0,this._pos=0,this.shapeId=0,this.idxInShape=0,this.idx=t,this._pos=i,this._model=r,this.shapeId=n,this.idxInShape=o,this._sps=s,a&&(this._modelBoundingInfo=a,this._boundingInfo=new e.BoundingInfo(a.minimum,a.maximum))}return Object.defineProperty(t.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),t.prototype.intersectsMesh=function(t){return!(!this._boundingInfo||!t._boundingInfo)&&(this._sps._bSphereOnly?e.BoundingSphere.Intersects(this._boundingInfo.boundingSphere,t._boundingInfo.boundingSphere):this._boundingInfo.intersects(t._boundingInfo,!1))},t})();e.SolidParticle=t;var i=(function(){function e(e,t,i,r,n){this.shapeID=e,this._shape=t,this._shapeUV=i,this._positionFunction=r,this._vertexFunction=n}return e})();e.ModelShape=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!0,this.counter=0,this.vars={},this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._shapeCounter=0,this._copy=new e.SolidParticle(null,null,null,null,null,null),this._color=new e.Color4(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._cam_axisZ=e.Vector3.Zero(),this._cam_axisY=e.Vector3.Zero(),this._cam_axisX=e.Vector3.Zero(),this._axisX=e.Axis.X,this._axisY=e.Axis.Y,this._axisZ=e.Axis.Z,this._camDir=e.Vector3.Zero(),this._rotMatrix=new e.Matrix,this._invertMatrix=new e.Matrix,this._rotated=e.Vector3.Zero(),this._quaternion=new e.Quaternion,this._vertex=e.Vector3.Zero(),this._normal=e.Vector3.Zero(),this._yaw=0,this._pitch=0,this._roll=0,this._halfroll=0,this._halfpitch=0,this._halfyaw=0,this._sinRoll=0,this._cosRoll=0,this._sinPitch=0,this._cosPitch=0,this._sinYaw=0,this._cosYaw=0,this._w=0,this._minimum=e.Tmp.Vector3[0],this._maximum=e.Tmp.Vector3[1],this._scale=e.Tmp.Vector3[2],this._translation=e.Tmp.Vector3[3],this._minBbox=e.Tmp.Vector3[4],this._maxBbox=e.Tmp.Vector3[5],this._particlesIntersect=!1,this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this.name=t,this._scene=i,this._camera=i.activeCamera,this._pickable=!!r&&r.isPickable,this._particlesIntersect=!!r&&r.particleIntersection,this._bSphereOnly=!!r&&r.boundingSphereOnly,this._bSphereRadiusFactor=r&&r.bSphereRadiusFactor?r.bSphereRadiusFactor:1,r&&r.updatable?this._updatable=r.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[])}return t.prototype.buildMesh=function(){if(0===this.nbParticles){var t=e.MeshBuilder.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),this.recomputeNormals&&e.VertexData.ComputeNormals(this._positions32,this._indices,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals);var i=new e.VertexData;i.set(this._positions32,e.VertexBuffer.PositionKind),i.indices=this._indices,i.set(this._normals32,e.VertexBuffer.NormalKind),this._uvs32&&i.set(this._uvs32,e.VertexBuffer.UVKind),this._colors32&&i.set(this._colors32,e.VertexBuffer.ColorKind);var r=new e.Mesh(this.name,this._scene);return i.applyToMesh(r,this._updatable),this.mesh=r,this.mesh.isPickable=this._pickable,this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),r},t.prototype.digest=function(t,i){var r=i&&i.facetNb||1,n=i&&i.number,o=i&&i.delta||0,s=t.getVerticesData(e.VertexBuffer.PositionKind),a=t.getIndices(),h=t.getVerticesData(e.VertexBuffer.UVKind),c=t.getVerticesData(e.VertexBuffer.ColorKind),l=t.getVerticesData(e.VertexBuffer.NormalKind),u=0,d=a.length/3;n?(n=n>d?d:n,r=Math.round(d/n),o=0):r=r>d?d:r;for(var f=[],p=[],m=[],_=[],g=e.Tmp.Vector3[0],v=r;u<d;){r=v+Math.floor((1+o)*Math.random()),u>d-r&&(r=d-u),f.length=0,p.length=0,m.length=0,_.length=0;for(var y=0,x=3*u;x<3*(u+r);x++){p.push(y);var b=a[x];f.push(s[3*b],s[3*b+1],s[3*b+2]),h&&m.push(h[2*b],h[2*b+1]),c&&_.push(c[4*b],c[4*b+1],c[4*b+2],c[4*b+3]),y++}var T,A=this.nbParticles,E=this._posToShape(f),P=this._uvsToShapeUV(m);for(T=0;T<E.length;T++)g.addInPlace(E[T]);for(g.scaleInPlace(1/E.length),T=0;T<E.length;T++)E[T].subtractInPlace(g);var M;this._particlesIntersect&&(M=new e.BoundingInfo(g,g));var S=new e.ModelShape(this._shapeCounter,E,P,null,null);this._meshBuilder(this._index,E,this._positions,p,this._indices,m,this._uvs,_,this._colors,l,this._normals,A,0,null),this._addParticle(A,this._positions.length,S,this._shapeCounter,0,M),this.particles[this.nbParticles].position.addInPlace(g),this._index+=E.length,A++,this.nbParticles++,this._shapeCounter++,u+=r}return this},t.prototype._resetCopy=function(){this._copy.position.x=0,this._copy.position.y=0,this._copy.position.z=0,this._copy.rotation.x=0,this._copy.rotation.y=0,this._copy.rotation.z=0,this._copy.rotationQuaternion=null,this._copy.scaling.x=1,this._copy.scaling.y=1,this._copy.scaling.z=1,this._copy.uvs.x=0,this._copy.uvs.y=0,this._copy.uvs.z=1,this._copy.uvs.w=1,this._copy.color=null},t.prototype._meshBuilder=function(t,i,r,n,o,s,a,h,c,l,u,d,f,p){var m,_=0,g=0,v=0;for(this._resetCopy(),p&&p.positionFunction&&p.positionFunction(this._copy,d,f),this._copy.rotationQuaternion?this._quaternion.copyFrom(this._copy.rotationQuaternion):(this._yaw=this._copy.rotation.y,this._pitch=this._copy.rotation.x,this._roll=this._copy.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix(),m=0;m<i.length;m++)this._vertex.x=i[m].x,this._vertex.y=i[m].y,this._vertex.z=i[m].z,p&&p.vertexFunction&&p.vertexFunction(this._copy,this._vertex,m),this._vertex.x*=this._copy.scaling.x,this._vertex.y*=this._copy.scaling.y,this._vertex.z*=this._copy.scaling.z,e.Vector3.TransformCoordinatesToRef(this._vertex,this._rotMatrix,this._rotated),r.push(this._copy.position.x+this._rotated.x,this._copy.position.y+this._rotated.y,this._copy.position.z+this._rotated.z),s&&(a.push((this._copy.uvs.z-this._copy.uvs.x)*s[_]+this._copy.uvs.x,(this._copy.uvs.w-this._copy.uvs.y)*s[_+1]+this._copy.uvs.y),_+=2),this._copy.color?this._color=this._copy.color:h&&void 0!==h[g]?(this._color.r=h[g],this._color.g=h[g+1],this._color.b=h[g+2],this._color.a=h[g+3]):(this._color.r=1,this._color.g=1,this._color.b=1,this._color.a=1),c.push(this._color.r,this._color.g,this._color.b,this._color.a),g+=4,!this.recomputeNormals&&l&&(this._normal.x=l[v],this._normal.y=l[v+1],this._normal.z=l[v+2],e.Vector3.TransformCoordinatesToRef(this._normal,this._rotMatrix,this._normal),u.push(this._normal.x,this._normal.y,this._normal.z),v+=3);for(m=0;m<n.length;m++)o.push(t+n[m]);if(this._pickable){var y=n.length/3;for(m=0;m<y;m++)this.pickedParticles.push({idx:d,faceId:m})}},t.prototype._posToShape=function(t){for(var i=[],r=0;r<t.length;r+=3)i.push(new e.Vector3(t[r],t[r+1],t[r+2]));return i},t.prototype._uvsToShapeUV=function(e){var t=[];if(e)for(var i=0;i<e.length;i++)t.push(e[i]);return t},t.prototype._addParticle=function(t,i,r,n,o,s){this.particles.push(new e.SolidParticle(t,i,r,n,o,this,s))},t.prototype.addShape=function(t,i,r){var n,o=t.getVerticesData(e.VertexBuffer.PositionKind),s=t.getIndices(),a=t.getVerticesData(e.VertexBuffer.UVKind),h=t.getVerticesData(e.VertexBuffer.ColorKind),c=t.getVerticesData(e.VertexBuffer.NormalKind);this._particlesIntersect&&(n=t.getBoundingInfo());for(var l=this._posToShape(o),u=this._uvsToShapeUV(a),d=r?r.positionFunction:null,f=r?r.vertexFunction:null,p=new e.ModelShape(this._shapeCounter,l,u,d,f),m=this.nbParticles,_=0;_<i;_++)this._meshBuilder(this._index,l,this._positions,s,this._indices,a,this._uvs,h,this._colors,c,this._normals,m,_,r),this._updatable&&this._addParticle(m,this._positions.length,p,this._shapeCounter,_,n),this._index+=l.length,m++;return this.nbParticles+=i,this._shapeCounter++,this._shapeCounter-1},t.prototype._rebuildParticle=function(t){this._resetCopy(),t._model._positionFunction&&t._model._positionFunction(this._copy,t.idx,t.idxInShape),this._copy.rotationQuaternion?this._quaternion.copyFrom(this._copy.rotationQuaternion):(this._yaw=this._copy.rotation.y,this._pitch=this._copy.rotation.x,this._roll=this._copy.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix(),this._shape=t._model._shape;for(var i=0;i<this._shape.length;i++)this._vertex.x=this._shape[i].x,this._vertex.y=this._shape[i].y,this._vertex.z=this._shape[i].z,t._model._vertexFunction&&t._model._vertexFunction(this._copy,this._vertex,i),this._vertex.x*=this._copy.scaling.x,this._vertex.y*=this._copy.scaling.y,this._vertex.z*=this._copy.scaling.z,e.Vector3.TransformCoordinatesToRef(this._vertex,this._rotMatrix,this._rotated),this._positions32[t._pos+3*i]=this._copy.position.x+this._rotated.x,this._positions32[t._pos+3*i+1]=this._copy.position.y+this._rotated.y,this._positions32[t._pos+3*i+2]=this._copy.position.z+this._rotated.z;t.position.x=0,t.position.y=0,t.position.z=0,t.rotation.x=0,t.rotation.y=0,t.rotation.z=0,t.rotationQuaternion=null,t.scaling.x=1,t.scaling.y=1,t.scaling.z=1},t.prototype.rebuildMesh=function(){for(var t=0;t<this.particles.length;t++)this._rebuildParticle(this.particles[t]);this.mesh.updateVerticesData(e.VertexBuffer.PositionKind,this._positions32,!1,!1)},t.prototype.setParticles=function(t,i,r){if(void 0===t&&(t=0),void 0===i&&(i=this.nbParticles-1),void 0===r&&(r=!0),this._updatable){this.beforeUpdateParticles(t,i,r),this._cam_axisX.x=1,this._cam_axisX.y=0,this._cam_axisX.z=0,this._cam_axisY.x=0,this._cam_axisY.y=1,this._cam_axisY.z=0,this._cam_axisZ.x=0,this._cam_axisZ.y=0,this._cam_axisZ.z=1,this.billboard&&this.mesh._worldMatrix.decompose(this._scale,this._quaternion,this._translation)&&(this._quaternionToRotationMatrix(),this._rotMatrix.invertToRef(this._invertMatrix),this._camera._currentTarget.subtractToRef(this._camera.globalPosition,this._camDir),e.Vector3.TransformCoordinatesToRef(this._camDir,this._invertMatrix,this._cam_axisZ),this._cam_axisZ.normalize(),e.Vector3.CrossToRef(this._cam_axisZ,this._axisX,this._cam_axisY),e.Vector3.CrossToRef(this._cam_axisY,this._cam_axisZ,this._cam_axisX),this._cam_axisY.normalize(),this._cam_axisX.normalize()),e.Matrix.IdentityToRef(this._rotMatrix);var n=0,o=0,s=0,a=0,h=0,c=0,l=0;this._computeBoundingBox&&(e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this._minimum),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this._maximum)),i=i>this.nbParticles-1?this.nbParticles-1:i;for(var u=t;u<=i;u++){if(this._particle=this.particles[u],this._shape=this._particle._model._shape,this._shapeUV=this._particle._model._shapeUV,this.updateParticle(this._particle),this._particle.isVisible)for(this.billboard&&(this._particle.rotation.x=0,this._particle.rotation.y=0),(this._computeParticleRotation||this.billboard)&&(this._particle.rotationQuaternion?this._quaternion.copyFrom(this._particle.rotationQuaternion):(this._yaw=this._particle.rotation.y,this._pitch=this._particle.rotation.x,this._roll=this._particle.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix()),l=0;l<this._shape.length;l++)n=o+3*l,s=a+4*l,h=c+2*l,this._vertex.x=this._shape[l].x,this._vertex.y=this._shape[l].y,this._vertex.z=this._shape[l].z,this._computeParticleVertex&&this.updateParticleVertex(this._particle,this._vertex,l),this._vertex.x*=this._particle.scaling.x,this._vertex.y*=this._particle.scaling.y,this._vertex.z*=this._particle.scaling.z,this._w=this._vertex.x*this._rotMatrix.m[3]+this._vertex.y*this._rotMatrix.m[7]+this._vertex.z*this._rotMatrix.m[11]+this._rotMatrix.m[15],this._rotated.x=(this._vertex.x*this._rotMatrix.m[0]+this._vertex.y*this._rotMatrix.m[4]+this._vertex.z*this._rotMatrix.m[8]+this._rotMatrix.m[12])/this._w,this._rotated.y=(this._vertex.x*this._rotMatrix.m[1]+this._vertex.y*this._rotMatrix.m[5]+this._vertex.z*this._rotMatrix.m[9]+this._rotMatrix.m[13])/this._w,this._rotated.z=(this._vertex.x*this._rotMatrix.m[2]+this._vertex.y*this._rotMatrix.m[6]+this._vertex.z*this._rotMatrix.m[10]+this._rotMatrix.m[14])/this._w,this._positions32[n]=this._particle.position.x+this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._positions32[n+1]=this._particle.position.y+this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._positions32[n+2]=this._particle.position.z+this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z,this._computeBoundingBox&&(this._positions32[n]<this._minimum.x&&(this._minimum.x=this._positions32[n]),this._positions32[n]>this._maximum.x&&(this._maximum.x=this._positions32[n]),this._positions32[n+1]<this._minimum.y&&(this._minimum.y=this._positions32[n+1]),this._positions32[n+1]>this._maximum.y&&(this._maximum.y=this._positions32[n+1]),this._positions32[n+2]<this._minimum.z&&(this._minimum.z=this._positions32[n+2]),this._positions32[n+2]>this._maximum.z&&(this._maximum.z=this._positions32[n+2])),this._computeParticleVertex||(this._normal.x=this._fixedNormal32[n],this._normal.y=this._fixedNormal32[n+1],this._normal.z=this._fixedNormal32[n+2],this._w=this._normal.x*this._rotMatrix.m[3]+this._normal.y*this._rotMatrix.m[7]+this._normal.z*this._rotMatrix.m[11]+this._rotMatrix.m[15],this._rotated.x=(this._normal.x*this._rotMatrix.m[0]+this._normal.y*this._rotMatrix.m[4]+this._normal.z*this._rotMatrix.m[8]+this._rotMatrix.m[12])/this._w,this._rotated.y=(this._normal.x*this._rotMatrix.m[1]+this._normal.y*this._rotMatrix.m[5]+this._normal.z*this._rotMatrix.m[9]+this._rotMatrix.m[13])/this._w,this._rotated.z=(this._normal.x*this._rotMatrix.m[2]+this._normal.y*this._rotMatrix.m[6]+this._normal.z*this._rotMatrix.m[10]+this._rotMatrix.m[14])/this._w,this._normals32[n]=this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._normals32[n+1]=this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._normals32[n+2]=this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z),this._computeParticleColor&&(this._colors32[s]=this._particle.color.r,this._colors32[s+1]=this._particle.color.g,this._colors32[s+2]=this._particle.color.b,this._colors32[s+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[h]=this._shapeUV[2*l]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[h+1]=this._shapeUV[2*l+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);else for(l=0;l<this._shape.length;l++)n=o+3*l,s=a+4*l,h=c+2*l,this._positions32[n]=this._camera.position.x,this._positions32[n+1]=this._camera.position.y,this._positions32[n+2]=this._camera.position.z,this._normals32[n]=0,this._normals32[n+1]=0,this._normals32[n+2]=0,this._computeParticleColor&&(this._colors32[s]=this._particle.color.r,this._colors32[s+1]=this._particle.color.g,this._colors32[s+2]=this._particle.color.b,this._colors32[s+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[h]=this._shapeUV[2*l]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[h+1]=this._shapeUV[2*l+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);if(this._particlesIntersect){var d=this._particle._boundingInfo,f=d.boundingBox,p=d.boundingSphere;if(!this._bSphereOnly){for(var m=0;m<f.vectors.length;m++)this._vertex.x=this._particle._modelBoundingInfo.boundingBox.vectors[m].x*this._particle.scaling.x,this._vertex.y=this._particle._modelBoundingInfo.boundingBox.vectors[m].y*this._particle.scaling.y,
this._vertex.z=this._particle._modelBoundingInfo.boundingBox.vectors[m].z*this._particle.scaling.z,this._w=this._vertex.x*this._rotMatrix.m[3]+this._vertex.y*this._rotMatrix.m[7]+this._vertex.z*this._rotMatrix.m[11]+this._rotMatrix.m[15],this._rotated.x=(this._vertex.x*this._rotMatrix.m[0]+this._vertex.y*this._rotMatrix.m[4]+this._vertex.z*this._rotMatrix.m[8]+this._rotMatrix.m[12])/this._w,this._rotated.y=(this._vertex.x*this._rotMatrix.m[1]+this._vertex.y*this._rotMatrix.m[5]+this._vertex.z*this._rotMatrix.m[9]+this._rotMatrix.m[13])/this._w,this._rotated.z=(this._vertex.x*this._rotMatrix.m[2]+this._vertex.y*this._rotMatrix.m[6]+this._vertex.z*this._rotMatrix.m[10]+this._rotMatrix.m[14])/this._w,f.vectors[m].x=this._particle.position.x+this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,f.vectors[m].y=this._particle.position.y+this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,f.vectors[m].z=this._particle.position.z+this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z;f._update(this.mesh._worldMatrix)}this._minBbox.x=this._particle._modelBoundingInfo.minimum.x*this._particle.scaling.x,this._minBbox.y=this._particle._modelBoundingInfo.minimum.y*this._particle.scaling.y,this._minBbox.z=this._particle._modelBoundingInfo.minimum.z*this._particle.scaling.z,this._maxBbox.x=this._particle._modelBoundingInfo.maximum.x*this._particle.scaling.x,this._maxBbox.y=this._particle._modelBoundingInfo.maximum.y*this._particle.scaling.y,this._maxBbox.z=this._particle._modelBoundingInfo.maximum.z*this._particle.scaling.z,p.center.x=this._particle.position.x+.5*(this._minBbox.x+this._maxBbox.x),p.center.y=this._particle.position.y+.5*(this._minBbox.y+this._maxBbox.y),p.center.z=this._particle.position.z+.5*(this._minBbox.z+this._maxBbox.z),p.radius=.5*this._bSphereRadiusFactor*Math.sqrt((this._maxBbox.x-this._minBbox.x)*(this._maxBbox.x-this._minBbox.x)+(this._maxBbox.y-this._minBbox.y)*(this._maxBbox.y-this._minBbox.y)+(this._maxBbox.z-this._minBbox.z)*(this._maxBbox.z-this._minBbox.z)),p._update(this.mesh._worldMatrix)}o=n+3,a=s+4,c=h+2}if(r&&(this._computeParticleColor&&this.mesh.updateVerticesData(e.VertexBuffer.ColorKind,this._colors32,!1,!1),this._computeParticleTexture&&this.mesh.updateVerticesData(e.VertexBuffer.UVKind,this._uvs32,!1,!1),this.mesh.updateVerticesData(e.VertexBuffer.PositionKind,this._positions32,!1,!1),!this.mesh.areNormalsFrozen)){if(this._computeParticleVertex){e.VertexData.ComputeNormals(this._positions32,this._indices,this._normals32);for(var _=0;_<this._normals32.length;_++)this._fixedNormal32[_]=this._normals32[_]}this.mesh.updateVerticesData(e.VertexBuffer.NormalKind,this._normals32,!1,!1)}this._computeBoundingBox&&(this.mesh._boundingInfo=new e.BoundingInfo(this._minimum,this._maximum),this.mesh._boundingInfo.update(this.mesh._worldMatrix)),this.afterUpdateParticles(t,i,r)}},t.prototype._quaternionRotationYPR=function(){this._halfroll=.5*this._roll,this._halfpitch=.5*this._pitch,this._halfyaw=.5*this._yaw,this._sinRoll=Math.sin(this._halfroll),this._cosRoll=Math.cos(this._halfroll),this._sinPitch=Math.sin(this._halfpitch),this._cosPitch=Math.cos(this._halfpitch),this._sinYaw=Math.sin(this._halfyaw),this._cosYaw=Math.cos(this._halfyaw),this._quaternion.x=this._cosYaw*this._sinPitch*this._cosRoll+this._sinYaw*this._cosPitch*this._sinRoll,this._quaternion.y=this._sinYaw*this._cosPitch*this._cosRoll-this._cosYaw*this._sinPitch*this._sinRoll,this._quaternion.z=this._cosYaw*this._cosPitch*this._sinRoll-this._sinYaw*this._sinPitch*this._cosRoll,this._quaternion.w=this._cosYaw*this._cosPitch*this._cosRoll+this._sinYaw*this._sinPitch*this._sinRoll},t.prototype._quaternionToRotationMatrix=function(){this._rotMatrix.m[0]=1-2*(this._quaternion.y*this._quaternion.y+this._quaternion.z*this._quaternion.z),this._rotMatrix.m[1]=2*(this._quaternion.x*this._quaternion.y+this._quaternion.z*this._quaternion.w),this._rotMatrix.m[2]=2*(this._quaternion.z*this._quaternion.x-this._quaternion.y*this._quaternion.w),this._rotMatrix.m[3]=0,this._rotMatrix.m[4]=2*(this._quaternion.x*this._quaternion.y-this._quaternion.z*this._quaternion.w),this._rotMatrix.m[5]=1-2*(this._quaternion.z*this._quaternion.z+this._quaternion.x*this._quaternion.x),this._rotMatrix.m[6]=2*(this._quaternion.y*this._quaternion.z+this._quaternion.x*this._quaternion.w),this._rotMatrix.m[7]=0,this._rotMatrix.m[8]=2*(this._quaternion.z*this._quaternion.x+this._quaternion.y*this._quaternion.w),this._rotMatrix.m[9]=2*(this._quaternion.y*this._quaternion.z-this._quaternion.x*this._quaternion.w),this._rotMatrix.m[10]=1-2*(this._quaternion.y*this._quaternion.y+this._quaternion.x*this._quaternion.x),this._rotMatrix.m[11]=0,this._rotMatrix.m[12]=0,this._rotMatrix.m[13]=0,this._rotMatrix.m[14]=0,this._rotMatrix.m[15]=1},t.prototype.dispose=function(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._positions32=null,this._normals32=null,this._fixedNormal32=null,this._uvs32=null,this._colors32=null,this.pickedParticles=null},t.prototype.refreshVisibleSize=function(){this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo()},t.prototype.setVisibilityBox=function(t){var i=t/2;this.mesh._boundingInfo=new e.BoundingInfo(new e.Vector3((-i),(-i),(-i)),new e.Vector3(i,i,i))},Object.defineProperty(t.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(e){this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVisibilityBoxLocked",{get:function(){return this._isVisibilityBoxLocked},set:function(e){this._isVisibilityBoxLocked=e,this.mesh.getBoundingInfo().isLocked=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleRotation",{get:function(){return this._computeParticleRotation},set:function(e){this._computeParticleRotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(e){this._computeParticleColor=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(e){this._computeParticleTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleVertex",{get:function(){return this._computeParticleVertex},set:function(e){this._computeParticleVertex=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(e){this._computeBoundingBox=e},enumerable:!0,configurable:!0}),t.prototype.initParticles=function(){},t.prototype.recycleParticle=function(e){return e},t.prototype.updateParticle=function(e){return e},t.prototype.updateParticleVertex=function(e,t,i){return t},t.prototype.beforeUpdateParticles=function(e,t,i){},t.prototype.afterUpdateParticles=function(e,t,i){},t})();e.SolidParticleSystem=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function e(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}return e})(),r=(function(){function t(){}return t.ConvertCubeMapToSphericalPolynomial=function(t){for(var i=new e.SphericalHarmonics,r=0,n=2/t.size,o=n,s=.5*n-1,a=0;a<6;a++)for(var h=this.FileFaces[a],c=t[h.name],l=s,u=0;u<t.size;u++){for(var d=s,f=0;f<t.size;f++){var p=h.worldAxisForFileX.scale(d).add(h.worldAxisForFileY.scale(l)).add(h.worldAxisForNormal);p.normalize();var m,_=Math.pow(1+d*d+l*l,-1.5),g=c[u*t.size*3+3*f+0],v=c[u*t.size*3+3*f+1],y=c[u*t.size*3+3*f+2],m=new e.Color3(g,v,y);i.addLight(p,m,_),r+=_,d+=n}l+=o}var x=4*Math.PI,b=x/r;return i.scale(b),i.scale(1/Math.PI),e.SphericalPolynomial.getSphericalPolynomialFromHarmonics(i)},t.FileFaces=[new i("right",new e.Vector3(1,0,0),new e.Vector3(0,0,(-1)),new e.Vector3(0,(-1),0)),new i("left",new e.Vector3((-1),0,0),new e.Vector3(0,0,1),new e.Vector3(0,(-1),0)),new i("up",new e.Vector3(0,1,0),new e.Vector3(1,0,0),new e.Vector3(0,0,1)),new i("down",new e.Vector3(0,(-1),0),new e.Vector3(1,0,0),new e.Vector3(0,0,(-1))),new i("front",new e.Vector3(0,0,1),new e.Vector3(1,0,0),new e.Vector3(0,(-1),0)),new i("back",new e.Vector3(0,0,(-1)),new e.Vector3((-1),0,0),new e.Vector3(0,(-1),0))],t})();t.CubeMapToSphericalPolynomialTools=r})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){}return t.ConvertPanoramaToCubemap=function(e,t,i,r){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";var n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i),o=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i),s=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i),a=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i),c=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i);return{front:n,back:o,left:s,right:a,up:h,down:c,size:r}},t.CreateCubemapTexture=function(e,t,i,r,n){for(var o=new ArrayBuffer(e*e*4*3),s=new Float32Array(o),a=t[1].subtract(t[0]).scale(1/e),h=t[3].subtract(t[2]).scale(1/e),c=1/e,l=0,u=0;u<e;u++){for(var d=t[0],f=t[2],p=0;p<e;p++){var m=f.subtract(d).scale(l).add(d);m.normalize();var _=this.CalcProjectionSpherical(m,i,r,n);s[u*e*3+3*p+0]=_.r,s[u*e*3+3*p+1]=_.g,s[u*e*3+3*p+2]=_.b,d=d.add(a),f=f.add(h)}l+=c}return s},t.CalcProjectionSpherical=function(e,t,i,r){for(var n=Math.atan2(e.z,e.x),o=Math.acos(e.y);n<-Math.PI;)n+=2*Math.PI;for(;n>Math.PI;)n-=2*Math.PI;var s=n/Math.PI,a=o/Math.PI;s=.5*s+.5;var h=Math.round(s*i);h<0?h=0:h>=i&&(h=i-1);var c=Math.round(a*r);c<0?c=0:c>=r&&(c=r-1);var l=r-c-1,u=t[l*i*3+3*h+0],d=t[l*i*3+3*h+1],f=t[l*i*3+3*h+2];return{r:u,g:d,b:f}},t.FACE_FRONT=[new e.Vector3((-1),(-1),(-1)),new e.Vector3(1,(-1),(-1)),new e.Vector3((-1),1,(-1)),new e.Vector3(1,1,(-1))],t.FACE_BACK=[new e.Vector3(1,(-1),1),new e.Vector3((-1),(-1),1),new e.Vector3(1,1,1),new e.Vector3((-1),1,1)],t.FACE_RIGHT=[new e.Vector3(1,(-1),(-1)),new e.Vector3(1,(-1),1),new e.Vector3(1,1,(-1)),new e.Vector3(1,1,1)],t.FACE_LEFT=[new e.Vector3((-1),(-1),1),new e.Vector3((-1),(-1),(-1)),new e.Vector3((-1),1,1),new e.Vector3((-1),1,(-1))],t.FACE_DOWN=[new e.Vector3((-1),1,(-1)),new e.Vector3(1,1,(-1)),new e.Vector3((-1),1,1),new e.Vector3(1,1,1)],t.FACE_UP=[new e.Vector3((-1),(-1),1),new e.Vector3(1,(-1),1),new e.Vector3((-1),(-1),(-1)),new e.Vector3(1,(-1),(-1))],t})();t.PanoramaToCubeMapTools=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function t(){}return t.Ldexp=function(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},t.Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this.Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},t.readStringLine=function(e,t){for(var i="",r="",n=t;n<e.length-t&&(r=String.fromCharCode(e[n]),"\n"!=r);n++)i+=r;return i},t.RGBE_ReadHeader=function(e){var t=0,i=0,r=this.readStringLine(e,0);if("#"!=r[0]||"?"!=r[1])throw"Bad HDR Format.";var n=!1,o=!1,s=0;do s+=r.length+1,r=this.readStringLine(e,s),"FORMAT=32-bit_rle_rgbe"==r?o=!0:0==r.length&&(n=!0);while(!n);if(!o)throw"HDR Bad header format, unsupported FORMAT";s+=r.length+1,r=this.readStringLine(e,s);var a=/^\-Y (.*) \+X (.*)$/g,h=a.exec(r);if(h.length<3)throw"HDR Bad header format, no size";if(i=parseInt(h[2]),t=parseInt(h[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return s+=r.length+1,{height:t,width:i,dataPosition:s}},t.GetCubeMapTextureData=function(t,i){var r=new Uint8Array(t),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels_RLE(r,n),s=e.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o,n.width,n.height,i);return s},t.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},t.RGBE_ReadPixels_RLE=function(e,t){for(var i,r,n,o,s,a=t.height,h=t.width,c=t.dataPosition,l=0,u=0,d=0,f=new ArrayBuffer(4*h),p=new Uint8Array(f),m=new ArrayBuffer(t.width*t.height*4*3),_=new Float32Array(m);a>0;){if(i=e[c++],r=e[c++],n=e[c++],o=e[c++],2!=i||2!=r||128&n)throw"HDR Bad header format, not RLE";if((n<<8|o)!=h)throw"HDR Bad header format, wrong scan line width";for(l=0,d=0;d<4;d++)for(u=(d+1)*h;l<u;)if(i=e[c++],r=e[c++],i>128){if(s=i-128,0==s||s>u-l)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[l++]=r}else{if(s=i,0==s||s>u-l)throw"HDR Bad Format, bad scanline data (non-run)";if(p[l++]=r,--s>0)for(var g=0;g<s;g++)p[l++]=e[c++]}for(d=0;d<h;d++)i=p[d],r=p[d+h],n=p[d+2*h],o=p[d+3*h],this.Rgbe2float(_,i,r,n,o,(t.height-a)*h*3+3*d);a--}return _},t})();e.HDRTools=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){this.min=new e.Vector3(0,0,0),this.max=new e.Vector3(0,0,0),this.clear()}return t.prototype.clear=function(){this.min.x=t.MAX,this.min.y=t.MAX,this.min.z=t.MAX,this.max.x=t.MIN,this.max.y=t.MIN,this.max.z=t.MIN},t.prototype.augment=function(e,t,i){this.min.x=Math.min(this.min.x,e),this.min.y=Math.min(this.min.y,t),this.min.z=Math.min(this.min.z,i),this.max.x=Math.max(this.max.x,e),this.max.y=Math.max(this.max.y,t),this.max.z=Math.max(this.max.z,i)},t.prototype.clampMin=function(e,t,i){this.min.x=Math.max(this.min.x,e),this.min.y=Math.max(this.min.y,t),this.min.z=Math.max(this.min.z,i)},t.prototype.clampMax=function(e,t,i){this.max.x=Math.min(this.max.x,e),this.max.y=Math.min(this.max.y,t),this.max.z=Math.min(this.max.z,i)},t.prototype.empty=function(){return this.min.x>this.max.y||this.min.y>this.max.y||this.min.z>this.max.y},t.MAX=Number.MAX_VALUE,t.MIN=Number.MIN_VALUE,t})(),r=(function(){function t(e,t,i,r,n,o,s,a,h,c){this.input=e,this.inputSize=t,this.outputSize=i,this.maxNumMipLevels=r,this.numChannels=n,this.isFloat=o,this.specularPower=s,this.cosinePowerDropPerMip=a,this.excludeBase=h,this.fixup=c,this._outputSurface=[],this._numMipLevels=0}return t.prototype.filterCubeMap=function(){return this.init(),this.filterCubeMapMipChain(),this._outputSurface},t.prototype.init=function(){var e,i,r;for(0==this.maxNumMipLevels&&(this.maxNumMipLevels=t.CP_MAX_MIPLEVELS),r=this.outputSize,i=0;i<this.maxNumMipLevels;i++){for(this._outputSurface.length++,this._outputSurface[i]=[],e=0;e<6;e++)this._outputSurface[i].length++,this.isFloat?this._outputSurface[i][e]=new Float32Array(r*r*this.numChannels):this._outputSurface[i][e]=new Uint32Array(r*r*this.numChannels);if(r>>=1,this._numMipLevels++,0==r)return void(this.maxNumMipLevels=i)}},t.prototype.filterCubeMapMipChain=function(){var e=this.specularPower;this.precomputeFilterLookupTables(this.inputSize);for(var t=0;t<this._numMipLevels;t++){this.excludeBase&&0==t&&(e=1e5);var i=this.input,r=this._outputSurface[t],n=this.outputSize>>t,o=this.getBaseFilterAngle(e);this.filterCubeSurfaces(i,this.inputSize,r,n,o,e),this.fixup&&this.fixupCubeEdges(r,n),this.excludeBase&&0==t&&(e=this.specularPower),e*=this.cosinePowerDropPerMip}},t.prototype.getBaseFilterAngle=function(e){var t=1e-6,i=180;return i=Math.acos(Math.pow(t,1/e)),i*=180/Math.PI,i*=2},t.prototype.precomputeFilterLookupTables=function(e){this._normCubeMap=[],this.buildNormalizerSolidAngleCubemap(e)},t.prototype.buildNormalizerSolidAngleCubemap=function(e){var t,i,r;for(t=0;t<6;t++){this._normCubeMap.push(new Float32Array(e*e*4));this.input[t];for(r=0;r<e;r++)for(i=0;i<e;i++){var n=this.texelCoordToVect(t,i,r,e,this.fixup);this._normCubeMap[t][4*(r*e+i)+0]=n.x,this._normCubeMap[t][4*(r*e+i)+1]=n.y,this._normCubeMap[t][4*(r*e+i)+2]=n.z;var o=this.texelCoordSolidAngle(t,i,r,e);this._normCubeMap[t][4*(r*e+i)+4]=o}}},t.prototype.texelCoordToVect=function(e,i,r,n,o){var s,a;if(s=2*(i+.5)/n-1,a=2*(r+.5)/n-1,o&&n>1){var h=Math.pow(n,2)/Math.pow(n-1,3);s=h*Math.pow(s,3)+s,a=h*Math.pow(a,3)+a}var c=t._sgFace2DMapping[e][t.CP_UDIR];t._vectorTemp.x=c[0]*s,t._vectorTemp.y=c[1]*s,t._vectorTemp.z=c[2]*s;var l=t._sgFace2DMapping[e][t.CP_VDIR];t._vectorTemp.x+=l[0]*a,t._vectorTemp.y+=l[1]*a,t._vectorTemp.z+=l[2]*a;var u=t._sgFace2DMapping[e][t.CP_FACEAXIS];return t._vectorTemp.x+=u[0],t._vectorTemp.y+=u[1],t._vectorTemp.z+=u[2],t._vectorTemp.normalize(),t._vectorTemp},t.prototype.vectToTexelCoord=function(e,i,r,n){var o,s,a=Math.abs(e),h=Math.abs(i),c=Math.abs(r);a>=h&&a>=c?(o=a,s=e>=0?t.CP_FACE_X_POS:t.CP_FACE_X_NEG):h>=a&&h>=c?(o=h,s=i>=0?t.CP_FACE_Y_POS:t.CP_FACE_Y_NEG):(o=c,s=r>=0?t.CP_FACE_Z_POS:t.CP_FACE_Z_NEG);var l=1/o;e*=l,i*=l,r*=l;var u=t._sgFace2DMapping[s][t.CP_UDIR],d=u[0]*e+u[1]*i+u[2]*r;u=t._sgFace2DMapping[s][t.CP_VDIR];var f=u[0]*e+u[1]*i+u[2]*r,p=Math.floor(.5*(n-1)*(d+1)),m=Math.floor(.5*(n-1)*(f+1));return t._vectorTemp.x=s,t._vectorTemp.y=p,t._vectorTemp.z=m,t._vectorTemp},t.prototype.areaElement=function(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))},t.prototype.texelCoordSolidAngle=function(e,t,i,r){t=2*(t+.5)/r-1,i=2*(i+.5)/r-1;var n=1/r,o=t-n,s=i-n,a=t+n,h=i+n,c=this.areaElement(o,s)-this.areaElement(o,h)-this.areaElement(a,s)+this.areaElement(a,h);return c},t.prototype.filterCubeSurfaces=function(e,t,r,n,o,s){var a,h,c,l=[];for(a=0;a<6;a++)l.push(new i);var u=180/Math.PI*Math.atan2(1,t),d=o/2;d<u&&(d=u),d>90&&(d=90);var f=Math.ceil(d/u);f<1&&(f=1);var p=Math.cos(Math.PI/180*d);for(a=0;a<6;a++)for(c=0;c<n;c++)for(h=0;h<n;h++){var m=this.texelCoordToVect(a,h,c,n,this.fixup).clone();this.clearFilterExtents(l),this.determineFilterExtents(m,t,f,l);var _=this.processFilterExtents(m,p,l,e,t,s);r[a][(c*n+h)*this.numChannels+0]=_.x,r[a][(c*n+h)*this.numChannels+1]=_.y,r[a][(c*n+h)*this.numChannels+2]=_.z}},t.prototype.clearFilterExtents=function(e){for(var t=0;t<6;t++)e[t].clear()},t.prototype.determineFilterExtents=function(e,i,r,n){var o,s,a,h=[0,0,0,0],c=[0,0,0,0],l=[0,0,0,0],u=this.vectToTexelCoord(e.x,e.y,e.z,i),d=u.x,f=u.y,p=u.z;n[d].augment(f-r,p-r,0),n[d].augment(f+r,p+r,0),n[d].clampMin(0,0,0),n[d].clampMax(i-1,i-1,0);var m=n[d].min.x,_=n[d].min.y,g=n[d].max.x,v=n[d].max.y;h[0]=r-f,c[0]=_,l[0]=v,h[1]=f+r-(i-1),c[1]=_,l[1]=v,h[2]=r-p,c[2]=m,l[2]=g,h[3]=p+r-(i-1),c[3]=m,l[3]=g;for(var y=0;y<4;y++){if(h[y]>0){switch(o=t._sgCubeNgh[d][y][0],s=t._sgCubeNgh[d][y][1],y!=s&&y+s!=3||(c[y]=i-1-c[y],l[y]=i-1-l[y]),t._sgCubeNgh[d][y][1]){case t.CP_EDGE_LEFT:n[o].augment(0,c[y],0),n[o].augment(h[y],l[y],0);break;case t.CP_EDGE_RIGHT:n[o].augment(i-1,c[y],0),n[o].augment(i-1-h[y],l[y],0);break;case t.CP_EDGE_TOP:n[o].augment(c[y],0,0),n[o].augment(l[y],h[y],0);break;case t.CP_EDGE_BOTTOM:n[o].augment(c[y],i-1,0),n[o].augment(l[y],i-1-h[y],0)}n[o].clampMin(0,0,0),n[o].clampMax(i-1,i-1,0)}if(h[y]>i){switch(d){case t.CP_FACE_X_POS:a=t.CP_FACE_X_NEG;break;case t.CP_FACE_X_NEG:a=t.CP_FACE_X_POS;break;case t.CP_FACE_Y_POS:a=t.CP_FACE_Y_NEG;break;case t.CP_FACE_Y_NEG:a=t.CP_FACE_Y_POS;break;case t.CP_FACE_Z_POS:a=t.CP_FACE_Z_NEG;break;case t.CP_FACE_Z_NEG:a=t.CP_FACE_Z_POS}n[a].augment(0,0,0),n[a].augment(i-1,i-1,0)}}},t.prototype.processFilterExtents=function(e,i,r,n,o,s){for(var a=[0,0,0,0],h=0,c=0,l=this.numChannels,u=o,d=4*u,f=u*this.numChannels,p=1,m=0;m<6;m++)if(!r[m].empty())for(var _=r[m].min.x,g=r[m].min.y,v=r[m].max.x,y=r[m].max.y,x=4*(g*u+_),b=this.numChannels*(g*u+_),T=g;T<=y;T++){for(var A=0,E=0,P=_;P<=v;P++){var M=this._normCubeMap[m][x+A+0],S=this._normCubeMap[m][x+A+1],C=this._normCubeMap[m][x+A+2],R=M*e.x+S*e.y+C*e.z;if(R>=i&&R>0){var O=this._normCubeMap[m][x+A+3];for(O*=Math.pow(R,s+p),c=0;c<l;c++)a[c]+=O*n[m][b+E],E++;h+=O}else E+=l;A+=4}x+=d,b+=f}if(0!=h)t._vectorTemp.x=a[0]/h,t._vectorTemp.y=a[1]/h,t._vectorTemp.z=a[2]/h,this.numChannels>3&&(t._vectorTemp.w=a[3]/h);else{var D=this.vectToTexelCoord(e.x,e.y,e.z,o).clone();t._vectorTemp.x=n[D.x][this.numChannels*(D.z*o+D.y)+0],t._vectorTemp.y=n[D.x][this.numChannels*(D.z*o+D.y)+1],t._vectorTemp.z=n[D.x][this.numChannels*(D.z*o+D.y)+2],this.numChannels>3&&(t._vectorTemp.z=n[D.x][this.numChannels*(D.z*o+D.y)+3])}return t._vectorTemp},t.prototype.fixupCubeEdges=function(e,i){var r,n,o,s,a=0,h=[0,0,0,0,0,0,0,0],c=[[],[],[],[]],l=[[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]]];if(!(i<1))if(1!=i){for(s=0;s<6;s++)for(c[0]=[s,0],c[1]=[s,(i-1)*this.numChannels],c[2]=[s,i*(i-1)*this.numChannels],c[3]=[s,(i*(i-1)+(i-1))*this.numChannels],a=0;a<4;a++){var u=t._sgCubeCornerList[s][a];l[u][h[u]]=c[a],h[u]++}for(a=0;a<8;a++)for(r=0;r<this.numChannels;r++){var d=0;for(o=0;o<3;o++)d+=e[l[a][o][0]][l[a][o][1]+r];for(d*=1/3,o=0;o<3;o++)e[l[a][o][0]][l[a][o][1]+r]=d}for(o=0;o<12;o++){var f=t._sgCubeEdgeList[o][0],p=t._sgCubeEdgeList[o][1],m=t._sgCubeNgh[f][p][0],_=t._sgCubeNgh[f][p][1],g=0,v=0,y=0,x=0;switch(p){case t.CP_EDGE_LEFT:y=this.numChannels*i;break;case t.CP_EDGE_RIGHT:g+=(i-1)*this.numChannels,y=this.numChannels*i;break;case t.CP_EDGE_TOP:y=this.numChannels;break;case t.CP_EDGE_BOTTOM:g+=i*(i-1)*this.numChannels,y=this.numChannels}if(p==_||p+_==3)switch(_){case t.CP_EDGE_LEFT:v+=(i-1)*i*this.numChannels,x=-(this.numChannels*i);break;case t.CP_EDGE_RIGHT:v+=((i-1)*i+(i-1))*this.numChannels,x=-(this.numChannels*i);break;case t.CP_EDGE_TOP:v+=(i-1)*this.numChannels,x=-this.numChannels;break;case t.CP_EDGE_BOTTOM:v+=((i-1)*i+(i-1))*this.numChannels,x=-this.numChannels}else switch(_){case t.CP_EDGE_LEFT:x=this.numChannels*i;break;case t.CP_EDGE_RIGHT:v+=(i-1)*this.numChannels,x=this.numChannels*i;break;case t.CP_EDGE_TOP:x=this.numChannels;break;case t.CP_EDGE_BOTTOM:v+=i*(i-1)*this.numChannels,x=this.numChannels}for(g+=y,v+=x,n=1;n<i-1;n++){for(r=0;r<this.numChannels;r++){var b=e[f][g+r],T=e[m][v+r],A=.5*(b+T);e[f][g+r]=A,e[m][v+r]=A}g+=y,v+=x}}}else for(r=0;r<this.numChannels;r++){var E=0;for(s=0;s<6;s++)E+=e[s][r];for(E/=6,s=0;s<6;s++)e[s][r]=E}},t.CP_MAX_MIPLEVELS=16,t.CP_UDIR=0,t.CP_VDIR=1,t.CP_FACEAXIS=2,t.CP_FACE_X_POS=0,t.CP_FACE_X_NEG=1,t.CP_FACE_Y_POS=2,t.CP_FACE_Y_NEG=3,t.CP_FACE_Z_POS=4,t.CP_FACE_Z_NEG=5,t.CP_EDGE_LEFT=0,t.CP_EDGE_RIGHT=1,t.CP_EDGE_TOP=2,t.CP_EDGE_BOTTOM=3,t.CP_CORNER_NNN=0,t.CP_CORNER_NNP=1,t.CP_CORNER_NPN=2,t.CP_CORNER_NPP=3,t.CP_CORNER_PNN=4,t.CP_CORNER_PNP=5,t.CP_CORNER_PPN=6,t.CP_CORNER_PPP=7,t._vectorTemp=new e.Vector4(0,0,0,0),t._sgFace2DMapping=[[[0,0,-1],[0,-1,0],[1,0,0]],[[0,0,1],[0,-1,0],[-1,0,0]],[[1,0,0],[0,0,1],[0,1,0]],[[1,0,0],[0,0,-1],[0,-1,0]],[[1,0,0],[0,-1,0],[0,0,1]],[[-1,0,0],[0,-1,0],[0,0,-1]]],t._sgCubeNgh=[[[t.CP_FACE_Z_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_Z_NEG,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_Y_NEG,t.CP_EDGE_RIGHT]],[[t.CP_FACE_Z_NEG,t.CP_EDGE_RIGHT],[t.CP_FACE_Z_POS,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_LEFT],[t.CP_FACE_Y_NEG,t.CP_EDGE_LEFT]],[[t.CP_FACE_X_NEG,t.CP_EDGE_TOP],[t.CP_FACE_X_POS,t.CP_EDGE_TOP],[t.CP_FACE_Z_NEG,t.CP_EDGE_TOP],[t.CP_FACE_Z_POS,t.CP_EDGE_TOP]],[[t.CP_FACE_X_NEG,t.CP_EDGE_BOTTOM],[t.CP_FACE_X_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_NEG,t.CP_EDGE_BOTTOM]],[[t.CP_FACE_X_NEG,t.CP_EDGE_RIGHT],[t.CP_FACE_X_POS,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Y_NEG,t.CP_EDGE_TOP]],[[t.CP_FACE_X_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_X_NEG,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_TOP],[t.CP_FACE_Y_NEG,t.CP_EDGE_BOTTOM]]],t._sgCubeEdgeList=[[t.CP_FACE_X_POS,t.CP_EDGE_LEFT],[t.CP_FACE_X_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_X_POS,t.CP_EDGE_TOP],[t.CP_FACE_X_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_X_NEG,t.CP_EDGE_LEFT],[t.CP_FACE_X_NEG,t.CP_EDGE_RIGHT],[t.CP_FACE_X_NEG,t.CP_EDGE_TOP],[t.CP_FACE_X_NEG,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_POS,t.CP_EDGE_TOP],[t.CP_FACE_Z_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_NEG,t.CP_EDGE_TOP],[t.CP_FACE_Z_NEG,t.CP_EDGE_BOTTOM]],t._sgCubeCornerList=[[t.CP_CORNER_PPP,t.CP_CORNER_PPN,t.CP_CORNER_PNP,t.CP_CORNER_PNN],[t.CP_CORNER_NPN,t.CP_CORNER_NPP,t.CP_CORNER_NNN,t.CP_CORNER_NNP],[t.CP_CORNER_NPN,t.CP_CORNER_PPN,t.CP_CORNER_NPP,t.CP_CORNER_PPP],[t.CP_CORNER_NNP,t.CP_CORNER_PNP,t.CP_CORNER_NNN,t.CP_CORNER_PNN],[t.CP_CORNER_NPP,t.CP_CORNER_PPP,t.CP_CORNER_NNP,t.CP_CORNER_PNP],[t.CP_CORNER_PPN,t.CP_CORNER_NPN,t.CP_CORNER_PNN,t.CP_CORNER_NNN]],t})();t.PMREMGenerator=r})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=!1),t.call(this,r),this._useInGammaSpace=!1,this._generateHarmonics=!0,this._isBABYLONPreprocessed=!1,this.coordinatesMode=e.Texture.CUBIC_MODE,this.sphericalPolynomial=null,this.isPMREM=!1,i&&(this.name=i,this.url=i,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=e.Matrix.Identity(),n?(this._isBABYLONPreprocessed=!1,this._noMipmap=o,this._size=n,this._useInGammaSpace=a,this._usePMREMGenerator=h&&r.getEngine().getCaps().textureLOD&&this.getScene().getEngine().getCaps().textureFloat&&!this._useInGammaSpace):(this._isBABYLONPreprocessed=!0,this._noMipmap=!1,this._useInGammaSpace=!1,this._usePMREMGenerator=r.getEngine().getCaps().textureLOD&&this.getScene().getEngine().getCaps().textureFloat&&!this._useInGammaSpace),this.isPMREM=this._usePMREMGenerator,this._texture=this._getFromCache(i,this._noMipmap),this._texture||(r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this.loadTexture()))}return __extends(i,t),i.prototype.loadBabylonTexture=function(){var t=this,i=0,r=null,n=!this._useInGammaSpace&&this.getScene().getEngine().getCaps().textureFloat?function(e){for(var n=[],o=30,s=0;s<i;s++){n.push([]);for(var a=3*Math.pow(t._size>>s,2),h=0;h<6;h++){var c=r.subarray(o,o+a);n[s].push(c),o+=a}}return n}:null,o=function(o){var s=new Int32Array(o);r=new Float32Array(o);s[0];t._size=s[1],t.getScene().getEngine().updateTextureSize(t._texture,t._size,t._size),t.sphericalPolynomial=new e.SphericalPolynomial,t.sphericalPolynomial.x.copyFromFloats(r[2],r[3],r[4]),t.sphericalPolynomial.y.copyFromFloats(r[5],r[6],r[7]),t.sphericalPolynomial.z.copyFromFloats(r[8],r[9],r[10]),t.sphericalPolynomial.xx.copyFromFloats(r[11],r[12],r[13]),t.sphericalPolynomial.yy.copyFromFloats(r[14],r[15],r[16]),t.sphericalPolynomial.zz.copyFromFloats(r[17],r[18],r[19]),t.sphericalPolynomial.xy.copyFromFloats(r[20],r[21],r[22]),t.sphericalPolynomial.yz.copyFromFloats(r[23],r[24],r[25]),t.sphericalPolynomial.zx.copyFromFloats(r[26],r[27],r[28]),i=s[29];for(var a=30,h=[],c=3*Math.pow(t._size,2),l=0;l<6;l++)h.push(r.subarray(a,a+c)),a+=c;for(var u=[],d=null,f=0;f<6;f++){var p=null;if(n)p=h[f];else{var m=[0,2,4,1,3,5][f];if(p=h[m],!t.getScene().getEngine().getCaps().textureFloat){var _=new ArrayBuffer(c);d=new Uint8Array(_)}for(var g=0;g<t._size*t._size;g++)if(t._useInGammaSpace&&(p[3*g+0]=Math.pow(p[3*g+0],e.ToGammaSpace),p[3*g+1]=Math.pow(p[3*g+1],e.ToGammaSpace),p[3*g+2]=Math.pow(p[3*g+2],e.ToGammaSpace)),d){var v=Math.max(255*p[3*g+0],0),y=Math.max(255*p[3*g+1],0),x=Math.max(255*p[3*g+2],0),b=Math.max(Math.max(v,y),x);if(b>255){var T=255/b;v*=T,y*=T,x*=T}d[3*g+0]=v,d[3*g+1]=y,d[3*g+2]=x}}d?u.push(d):u.push(p)}return u};this._texture=this.getScene().getEngine().createRawCubeTexture(this.url,this.getScene(),this._size,e.Engine.TEXTUREFORMAT_RGB,this.getScene().getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,o,n)},i.prototype.loadHDRTexture=function(){var t=this,r=function(r){var n=e.Internals.HDRTools.GetCubeMapTextureData(r,t._size);t._generateHarmonics&&(t.sphericalPolynomial=e.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(n));for(var o=[],s=null,a=0;a<6;a++){if(!t.getScene().getEngine().getCaps().textureFloat){var h=new ArrayBuffer(t._size*t._size*3);s=new Uint8Array(h)}var c=n[i._facesMapping[a]];if(t._useInGammaSpace||s)for(var l=0;l<t._size*t._size;l++)if(t._useInGammaSpace&&(c[3*l+0]=Math.pow(c[3*l+0],e.ToGammaSpace),c[3*l+1]=Math.pow(c[3*l+1],e.ToGammaSpace),c[3*l+2]=Math.pow(c[3*l+2],e.ToGammaSpace)),s){var u=Math.max(255*c[3*l+0],0),d=Math.max(255*c[3*l+1],0),f=Math.max(255*c[3*l+2],0),p=Math.max(Math.max(u,d),f);if(p>255){var m=255/p;u*=m,d*=m,f*=m}s[3*l+0]=u,s[3*l+1]=d,s[3*l+2]=f}s?o.push(s):o.push(c)}return o},n=null;!this._noMipmap&&this._usePMREMGenerator&&(n=function(i){var r=new e.Internals.PMREMGenerator(i,t._size,t._size,0,3,t.getScene().getEngine().getCaps().textureFloat,2048,.25,(!1),(!0));return r.filterCubeMap()}),this._texture=this.getScene().getEngine().createRawCubeTexture(this.url,this.getScene(),this._size,e.Engine.TEXTUREFORMAT_RGB,this.getScene().getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,r,n)},i.prototype.loadTexture=function(){this._isBABYLONPreprocessed?this.loadBabylonTexture():this.loadHDRTexture()},i.prototype.clone=function(){var e=this._isBABYLONPreprocessed?null:this._size,t=new i(this.url,this.getScene(),e,this._noMipmap,this._generateHarmonics,this._useInGammaSpace,this._usePMREMGenerator);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.Parse=function(t,i,r){var n=null;if(t.name&&!t.isRenderTarget){var o=t.isBABYLONPreprocessed?null:t.size;n=new e.HDRCubeTexture(r+t.name,i,o,t.generateHarmonics,t.useInGammaSpace,t.usePMREMGenerator),n.name=t.name,n.hasAlpha=t.hasAlpha,n.level=t.level,n.coordinatesMode=t.coordinatesMode}return n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this._useInGammaSpace,e.generateHarmonics=this._generateHarmonics,e.usePMREMGenerator=this._usePMREMGenerator,e.isBABYLONPreprocessed=this._isBABYLONPreprocessed,e.customType="BABYLON.HDRCubeTexture",e},i.generateBabylonHDROnDisk=function(e,t,r){void 0===r&&(r=null);var n=function(e){var t=new Blob([e],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download="envmap.babylon.hdr",r.click()};i.generateBabylonHDR(e,t,n,r)},i.generateBabylonHDR=function(t,i,r,n){if(void 0===n&&(n=null),!t)return null;if(!e.Tools.IsExponentOfTwo(i))return null;var o=function(t){var n=e.Internals.HDRTools.GetCubeMapTextureData(t,i),o=e.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(n),s=[];s.push(n.right),s.push(n.left),s.push(n.up),s.push(n.down),s.push(n.front),s.push(n.back);var a=new e.Internals.PMREMGenerator(s,i,i,0,3,(!0),2048,.25,(!1),(!0)),h=a.filterCubeMap(),c=4;c+=4,c+=108,c+=4;for(var l=0;l<h.length;l++){var u=i>>l;c+=6*u*u*3*4}var d=new ArrayBuffer(c),f=new Int32Array(d),p=new Float32Array(d);f[0]=1,f[1]=i,o.x.toArray(p,2),o.y.toArray(p,5),o.z.toArray(p,8),o.xx.toArray(p,11),o.yy.toArray(p,14),o.zz.toArray(p,17),o.xy.toArray(p,20),o.yz.toArray(p,23),o.zx.toArray(p,26),f[29]=h.length;for(var m=30,l=0;l<h.length;l++)for(var _=3*Math.pow(i>>l,2),g=0;g<6;g++)p.set(h[l][g],m),m+=_;r(d)};e.Tools.LoadFile(t,(function(e){o(e)}),null,null,!0,n)},i._facesMapping=["right","up","front","left","down","back"],i})(e.BaseTexture);e.HDRCubeTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=1),this.skeleton=t,this.mesh=i,this.autoUpdateBonesMatrices=n,this.renderingGroupId=o,this.color=e.Color3.White(),this._debugLines=[],this._isEnabled=!1,this._scene=r,this.update(),this._renderFunction=this.update.bind(this)}return Object.defineProperty(t.prototype,"isEnabled",{
get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,e?this._scene.registerBeforeRender(this._renderFunction):this._scene.unregisterBeforeRender(this._renderFunction))},enumerable:!0,configurable:!0}),t.prototype._getBonePosition=function(t,i,r,n,o,s){void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=0);var a=e.Tmp.Matrix[0],h=i.getParent();if(a.copyFrom(i.getLocalMatrix()),0!==n||0!==o||0!==s){var c=e.Tmp.Matrix[1];e.Matrix.IdentityToRef(c),c.m[12]=n,c.m[13]=o,c.m[14]=s,c.multiplyToRef(a,a)}h&&a.multiplyToRef(h.getAbsoluteTransform(),a),a.multiplyToRef(r,a),t.x=a.m[12],t.y=a.m[13],t.z=a.m[14]},t.prototype._getLinesForBonesWithLength=function(t,i){for(var r=t.length,n=0;n<r;n++){var o=t[n],s=this._debugLines[n];s||(s=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=s),this._getBonePosition(s[0],o,i),this._getBonePosition(s[1],o,i,0,o.length,0)}},t.prototype._getLinesForBonesNoLength=function(t,i){for(var r=t.length,n=0,o=r-1;o>=0;o--){var s=t[o],a=s.getParent();if(a){var h=this._debugLines[n];h||(h=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=h),s.getAbsolutePositionToRef(this.mesh,h[0]),a.getAbsolutePositionToRef(this.mesh,h[1]),n++}}},t.prototype.update=function(){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,this.mesh.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix()),this._debugMesh?e.MeshBuilder.CreateLineSystem(null,{lines:this._debugLines,updatable:!0,instance:this._debugMesh},this._scene):(this._debugMesh=e.MeshBuilder.CreateLineSystem(null,{lines:this._debugLines,updatable:!0},this._scene),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.color=this.color},t.prototype.dispose=function(){this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null)},t})();t.SkeletonViewer=i})(t=e.Debug||(e.Debug={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(t,i){void 0===i&&(i=1),this._xline=[e.Vector3.Zero(),e.Vector3.Zero()],this._yline=[e.Vector3.Zero(),e.Vector3.Zero()],this._zline=[e.Vector3.Zero(),e.Vector3.Zero()],this.scaleLines=1,this.scaleLines=i,this._xmesh=e.Mesh.CreateLines("xline",this._xline,t,!0),this._ymesh=e.Mesh.CreateLines("yline",this._yline,t,!0),this._zmesh=e.Mesh.CreateLines("zline",this._zline,t,!0),this._xmesh.renderingGroupId=2,this._ymesh.renderingGroupId=2,this._zmesh.renderingGroupId=2,this._xmesh.material.checkReadyOnlyOnce=!0,this._xmesh.color=new e.Color3(1,0,0),this._ymesh.material.checkReadyOnlyOnce=!0,this._ymesh.color=new e.Color3(0,1,0),this._zmesh.material.checkReadyOnlyOnce=!0,this._zmesh.color=new e.Color3(0,0,1),this.scene=t}return t.prototype.update=function(t,i,r,n){var o=this.scaleLines,s=this._xline[0],a=this._xline[1];s.x=t.x,s.y=t.y,s.z=t.z,a.x=s.x+i.x*o,a.y=s.y+i.y*o,a.z=s.z+i.z*o,e.Mesh.CreateLines(null,this._xline,null,null,this._xmesh),s=this._yline[0],a=this._yline[1],s.x=t.x,s.y=t.y,s.z=t.z,a.x=s.x+r.x*o,a.y=s.y+r.y*o,a.z=s.z+r.z*o,e.Mesh.CreateLines(null,this._yline,null,null,this._ymesh),s=this._zline[0],a=this._zline[1],s.x=t.x,s.y=t.y,s.z=t.z,a.x=s.x+n.x*o,a.y=s.y+n.y*o,a.z=s.z+n.z*o,e.Mesh.CreateLines(null,this._zline,null,null,this._zmesh)},t.prototype.dispose=function(){this._xmesh&&(this._xmesh.dispose(),this._ymesh.dispose(),this._zmesh.dispose(),this._xmesh=null,this._ymesh=null,this._zmesh=null,this._xline=null,this._yline=null,this._zline=null,this.scene=null)},t})();t.AxesViewer=i})(t=e.Debug||(e.Debug={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(t){function i(i,r,n,o){void 0===o&&(o=1),t.call(this,i,o),this.pos=e.Vector3.Zero(),this.xaxis=e.Vector3.Zero(),this.yaxis=e.Vector3.Zero(),this.zaxis=e.Vector3.Zero(),this.mesh=n,this.bone=r}return __extends(i,t),i.prototype.update=function(){var i=this.bone;i.getAbsolutePositionToRef(this.mesh,this.pos),i.getDirectionToRef(e.Axis.X,this.mesh,this.xaxis),i.getDirectionToRef(e.Axis.Y,this.mesh,this.yaxis),i.getDirectionToRef(e.Axis.Z,this.mesh,this.zaxis),t.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)},i.prototype.dispose=function(){this.pos&&(this.pos=null,this.xaxis=null,this.yaxis=null,this.zaxis=null,this.mesh=null,this.bone=null,t.prototype.dispose.call(this))},i})(t.AxesViewer);t.BoneAxesViewer=i})(t=e.Debug||(e.Debug={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,r),i&&(this._textureMatrix=e.Matrix.Identity(),this.name=i,this.url=i,this.hasAlpha=!1,this.isCube=!1,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this.anisotropicFilteringLevel=1,this._texture=this._getFromCache(i,!0),this._texture||(r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this.loadTexture()))}return __extends(i,t),i.prototype.getTextureMatrix=function(){return this._textureMatrix},i.prototype.load3dlTexture=function(){var t=this,r=this.getScene().getEngine().createRawTexture(null,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE);this._texture=r;var n=function(n){for(var o,s,a,h=n.split("\n"),c=0,l=0,u=0,d=0,f=0,p=0;p<h.length;p++)if(a=h[p],i._noneEmptyLineRegex.test(a)&&0!==a.indexOf("#")){var m=a.split(" ");if(0!==c){if(0!=c){var _=Math.max(parseInt(m[0]),0),g=Math.max(parseInt(m[1]),0),v=Math.max(parseInt(m[2]),0);f=Math.max(_,f),f=Math.max(g,f),f=Math.max(v,f);var y=4*(l+d*c+u*c*c);s[y+0]=_,s[y+1]=g,s[y+2]=v,s[y+3]=0,d++,d%c==0&&(u++,d=0,u%c==0&&(l++,u=0))}}else c=m.length,o=new Uint8Array(c*c*c*4),s=new Float32Array(c*c*c*4)}for(var p=0;p<s.length;p++){var x=s[p];o[p]=x/f*255}t.getScene().getEngine().updateTextureSize(r,c*c,c),t.getScene().getEngine().updateRawTexture(r,o,e.Engine.TEXTUREFORMAT_RGBA,!1)};return e.Tools.LoadFile(this.url,n),this._texture},i.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},i.prototype.clone=function(){var e=new i(this.url,this.getScene());return e.level=this.level,e},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},i.Bind=function(e,t){t.setTexture("cameraColorGrading2DSampler",e);var i=e.level,r=e.getSize().height,n=r-1,o=1/r;t.setFloat4("vCameraColorGradingInfos",i,r,n,o);var s=o/r,a=o,h=n*s,c=n/r,l=.5*s,u=.5*a;t.setFloat4("vCameraColorGradingScaleOffset",h,c,l,u)},i.PrepareUniformsAndSamplers=function(e,t){e.push("vCameraColorGradingInfos","vCameraColorGradingScaleOffset"),t.push("cameraColorGrading2DSampler")},i.Parse=function(t,i,r){var n=null;return t.name&&!t.isRenderTarget&&(n=new e.ColorGradingTexture(t.name,i),n.name=t.name,n.level=t.level),n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},i._noneEmptyLineRegex=/\S+/,i})(e.BaseTexture);e.ColorGradingTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._dirty=!0,this._tempColor=new e.Color4(0,0,0,0),this._globalCurve=new e.Color4(0,0,0,0),this._highlightsCurve=new e.Color4(0,0,0,0),this._midtonesCurve=new e.Color4(0,0,0,0),this._shadowsCurve=new e.Color4(0,0,0,0),this._positiveCurve=new e.Color4(0,0,0,0),this._negativeCurve=new e.Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(t.prototype,"GlobalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"GlobalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"GlobalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),t.Bind=function(e,t){e._dirty&&(e._dirty=!1,e.getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e.getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e.getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e.getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t.setFloat4("vCameraColorCurvePositive",e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4("vCameraColorCurveNeutral",e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4("vCameraColorCurveNegative",e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a)},t.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},t.prototype.getColorGradingDataToRef=function(e,i,r,n,o){null!=e&&(e=t.clamp(e,0,360),i=t.clamp(i,-100,100),r=t.clamp(r,-100,100),n=t.clamp(n,-100,100),i=t.applyColorGradingSliderNonlinear(i),i*=.5,n=t.applyColorGradingSliderNonlinear(n),i<0&&(i*=-1,e=(e+180)%360),t.fromHSBToRef(e,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},t.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},t.fromHSBToRef=function(e,i,r,n){var o=t.clamp(e,0,360),s=t.clamp(i/100,0,1),a=t.clamp(r/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{o/=60;var h=Math.floor(o),c=o-h,l=a*(1-s),u=a*(1-s*c),d=a*(1-s*(1-c));switch(h){case 0:n.r=a,n.g=d,n.b=l;break;case 1:n.r=u,n.g=a,n.b=l;break;case 2:n.r=l,n.g=a,n.b=d;break;case 3:n.r=l,n.g=u,n.b=a;break;case 4:n.r=d,n.g=l,n.b=a;break;default:n.r=a,n.g=l,n.b=u}}n.a=1},t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.prototype.clone=function(){return e.SerializationHelper.Clone((function(){return new t}),this)},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.Parse=function(i){return e.SerializationHelper.Parse((function(){return new t}),i,null,null)},__decorate([e.serialize()],t.prototype,"_globalHue",void 0),__decorate([e.serialize()],t.prototype,"_globalDensity",void 0),__decorate([e.serialize()],t.prototype,"_globalSaturation",void 0),__decorate([e.serialize()],t.prototype,"_globalExposure",void 0),__decorate([e.serialize()],t.prototype,"_highlightsHue",void 0),__decorate([e.serialize()],t.prototype,"_highlightsDensity",void 0),__decorate([e.serialize()],t.prototype,"_highlightsSaturation",void 0),__decorate([e.serialize()],t.prototype,"_highlightsExposure",void 0),__decorate([e.serialize()],t.prototype,"_midtonesHue",void 0),__decorate([e.serialize()],t.prototype,"_midtonesDensity",void 0),__decorate([e.serialize()],t.prototype,"_midtonesSaturation",void 0),__decorate([e.serialize()],t.prototype,"_midtonesExposure",void 0),t})();e.ColorCurves=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(){e.call(this),this.ALBEDO=!1,this.AMBIENT=!1,this.OPACITY=!1,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.REFLECTIVITY=!1,this.BUMP=!1,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.ALPHATEST=!1,this.ALPHAFROMALBEDO=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.OPACITYFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHALBEDO=!1,this.LIGHTMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.CAMERATONEMAP=!1,this.CAMERACONTRAST=!1,this.CAMERACOLORGRADING=!1,this.CAMERACOLORCURVES=!1,this.OVERLOADEDVALUES=!1,this.OVERLOADEDSHADOWVALUES=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.LINKREFRACTIONTOTRANSPARENCY=!1,this.REFRACTIONMAPINLINEARSPACE=!1,this.LODBASEDMICROSFURACE=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.RADIANCEOVERALPHA=!1,this.USEPMREMREFLECTION=!1,this.USEPMREMREFRACTION=!1,this.OPENGLNORMALMAP=!1,this.INVERTNORMALMAPX=!1,this.INVERTNORMALMAPY=!1,this.SHADOWFULLFLOAT=!1,this.METALLICWORKFLOW=!1,this.METALLICROUGHNESSGSTOREINALPHA=!1,this.METALLICROUGHNESSGSTOREINGREEN=!1,this.rebuild()}return __extends(t,e),t})(e.MaterialDefines),i=(function(i){function r(r,n){var o=this;i.call(this,r,n),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this._lightingInfos=new e.Vector4(this.directIntensity,this.emissiveIntensity,this.environmentIntensity,this.specularIntensity),this.disableBumpMap=!1,this.overloadedShadowIntensity=1,this.overloadedShadeIntensity=1,this._overloadedShadowInfos=new e.Vector4(this.overloadedShadowIntensity,this.overloadedShadeIntensity,0,0),this.cameraExposure=1,this.cameraContrast=1,this.cameraColorGradingTexture=null,this.cameraColorCurves=null,this._cameraInfos=new e.Vector4(1,1,0,0),this._microsurfaceTextureLods=new e.Vector2(0,0),this.overloadedAmbient=e.Color3.White(),this.overloadedAmbientIntensity=0,this.overloadedAlbedo=e.Color3.White(),this.overloadedAlbedoIntensity=0,this.overloadedReflectivity=new e.Color3(.3,.3,.3),this.overloadedReflectivityIntensity=0,this.overloadedEmissive=e.Color3.White(),this.overloadedEmissiveIntensity=0,this._overloadedIntensity=new e.Vector4(this.overloadedAmbientIntensity,this.overloadedAlbedoIntensity,this.overloadedReflectivityIntensity,this.overloadedEmissiveIntensity),this.overloadedReflection=e.Color3.White(),this.overloadedReflectionIntensity=0,this.overloadedMicroSurface=0,this.overloadedMicroSurfaceIntensity=0,this._overloadedMicroSurface=new e.Vector3(this.overloadedMicroSurface,this.overloadedMicroSurfaceIntensity,this.overloadedReflectionIntensity),this.ambientTextureStrength=1,this.ambientColor=new e.Color3(0,0,0),this.albedoColor=new e.Color3(1,1,1),this.reflectivityColor=new e.Color3(1,1,1),this.reflectionColor=new e.Color3(.5,.5,.5),this.emissiveColor=new e.Color3(0,0,0),this.microSurface=.9,this.indexOfRefraction=.66,this.invertRefractionY=!1,this.linkRefractionWithTransparency=!1,this.linkEmissiveWithAlbedo=!1,this.useLightmapAsShadowmap=!1,this.useEmissiveAsIllumination=!1,this.useAlphaFromAlbedoTexture=!1,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useScalarInLinearSpace=!1,this.usePhysicalLightFalloff=!0,this.useRadianceOverAlpha=!0,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this._renderTargets=new e.SmartArray(16),this._worldViewProjectionMatrix=e.Matrix.Zero(),this._globalAmbientColor=new e.Color3(0,0,0),this._tempColor=new e.Color3,this._defines=new t,this._cachedDefines=new t,this._myScene=null,this._myShadowGenerator=null,this._cachedDefines.BonesPerMesh=-1,this.getRenderTargetTextures=function(){return o._renderTargets.reset(),o.reflectionTexture&&o.reflectionTexture.isRenderTarget&&o._renderTargets.push(o.reflectionTexture),o.refractionTexture&&o.refractionTexture.isRenderTarget&&o._renderTargets.push(o.refractionTexture),o._renderTargets}}return __extends(r,i),Object.defineProperty(r.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),r.prototype.needAlphaBlending=function(){return!this.linkRefractionWithTransparency&&(this.alpha<1||null!=this.opacityTexture||this._shouldUseAlphaFromAlbedoTexture()||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled)},r.prototype.needAlphaTesting=function(){return!this.linkRefractionWithTransparency&&(null!=this.albedoTexture&&this.albedoTexture.hasAlpha)},r.prototype._shouldUseAlphaFromAlbedoTexture=function(){return null!=this.albedoTexture&&this.albedoTexture.hasAlpha&&this.useAlphaFromAlbedoTexture},r.prototype.getAlphaTestTexture=function(){return this.albedoTexture},r.prototype._checkCache=function(e,t,i){return!t||this._defines.INSTANCES===i&&!(!t._materialDefines||!t._materialDefines.isEqual(this._defines))},r.prototype.convertColorToLinearSpaceToRef=function(e,t){r.convertColorToLinearSpaceToRef(e,t,this.useScalarInLinearSpace)},r.convertColorToLinearSpaceToRef=function(e,t,i){i?(t.r=e.r,t.g=e.g,t.b=e.b):e.toLinearSpaceToRef(t)},r.BindLights=function(t,i,n,o,s,a,h){for(var c=0,l=!1,u=0;u<t.lights.length;u++){var d=t.lights[u];if(d.isEnabled()&&d.canAffectMesh(i)&&(e.MaterialHelper.BindLightProperties(d,n,c),this.convertColorToLinearSpaceToRef(d.diffuse,r._scaledAlbedo,s),r._scaledAlbedo.scaleToRef(d.intensity,r._scaledAlbedo),n.setColor4("vLightDiffuse"+c,r._scaledAlbedo,h?d.radius:d.range),o.SPECULARTERM&&(this.convertColorToLinearSpaceToRef(d.specular,r._scaledReflectivity,s),r._scaledReflectivity.scaleToRef(d.intensity,r._scaledReflectivity),n.setColor3("vLightSpecular"+c,r._scaledReflectivity)),t.shadowsEnabled&&(l=e.MaterialHelper.BindLightShadow(d,t,i,c,n,l)),c++,c===a))break}},r.prototype.isReady=function(i,r){if(this.checkReadyOnlyOnce&&this._wasPreviouslyReady)return!0;var n=this.getScene(),o=n.getEngine(),s=!1,a=!1;if(this._defines.reset(),n.lightsEnabled&&!this.disableLighting&&(s=e.MaterialHelper.PrepareDefinesForLights(n,i,this._defines,this.maxSimultaneousLights)||s),!this.checkReadyOnEveryCall&&this._renderId===n.getRenderId()&&this._checkCache(n,i,r))return!0;if(n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(this._defines.LODBASEDMICROSFURACE=!0),this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.albedoTexture.isReady())return!1;a=!0,this._defines.ALBEDO=!0}if(this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled){if(!this.ambientTexture.isReady())return!1;a=!0,this._defines.AMBIENT=!0}if(this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled){if(!this.opacityTexture.isReady())return!1;a=!0,this._defines.OPACITY=!0,this.opacityTexture.getAlphaFromRGB&&(this._defines.OPACITYRGB=!0)}if(this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady())return!1;switch(s=!0,this._defines.REFLECTION=!0,this.reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE&&(this._defines.INVERTCUBICMAP=!0),this._defines.REFLECTIONMAP_3D=this.reflectionTexture.isCube,this.reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:this._defines.REFLECTIONMAP_CUBIC=!0;break;case e.Texture.EXPLICIT_MODE:this._defines.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:this._defines.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:this._defines.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:this._defines.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:this._defines.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR=!0}this.reflectionTexture instanceof e.HDRCubeTexture&&this.reflectionTexture&&(this._defines.USESPHERICALFROMREFLECTIONMAP=!0,s=!0,this.reflectionTexture.isPMREM&&(this._defines.USEPMREMREFLECTION=!0))}if(this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled){if(!this.lightmapTexture.isReady())return!1;a=!0,this._defines.LIGHTMAP=!0,this._defines.USELIGHTMAPASSHADOWMAP=this.useLightmapAsShadowmap}if(this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady())return!1;a=!0,this._defines.EMISSIVE=!0}if(e.StandardMaterial.SpecularTextureEnabled)if(this.metallicTexture){if(!this.metallicTexture.isReady())return!1;a=!0,this._defines.METALLICWORKFLOW=!0,this._defines.METALLICROUGHNESSGSTOREINALPHA=this.useRoughnessFromMetallicTextureAlpha,this._defines.METALLICROUGHNESSGSTOREINGREEN=!this.useRoughnessFromMetallicTextureAlpha&&this.useRoughnessFromMetallicTextureGreen}else if(this.reflectivityTexture){if(!this.reflectivityTexture.isReady())return!1;a=!0,this._defines.REFLECTIVITY=!0,this._defines.MICROSURFACEFROMREFLECTIVITYMAP=this.useMicroSurfaceFromReflectivityMapAlpha,this._defines.MICROSURFACEAUTOMATIC=this.useAutoMicroSurfaceFromReflectivityMap}if(n.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap){if(!this.bumpTexture.isReady())return!1;a=!0,this._defines.BUMP=!0,this.useParallax&&this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._defines.PARALLAX=!0,this.useParallaxOcclusion&&(this._defines.PARALLAXOCCLUSION=!0)),this.invertNormalMapX&&(this._defines.INVERTNORMALMAPX=!0),this.invertNormalMapY&&(this._defines.INVERTNORMALMAPY=!0)}if(this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled){if(!this.refractionTexture.isReady())return!1;a=!0,this._defines.REFRACTION=!0,this._defines.REFRACTIONMAP_3D=this.refractionTexture.isCube,this.linkRefractionWithTransparency&&(this._defines.LINKREFRACTIONTOTRANSPARENCY=!0),this.refractionTexture instanceof e.HDRCubeTexture&&(this._defines.REFRACTIONMAPINLINEARSPACE=!0,this.refractionTexture.isPMREM&&(this._defines.USEPMREMREFRACTION=!0))}if(this.cameraColorGradingTexture&&e.StandardMaterial.ColorGradingTextureEnabled){if(!this.cameraColorGradingTexture.isReady())return!1;this._defines.CAMERACOLORGRADING=!0}}if(n.clipPlane&&(this._defines.CLIPPLANE=!0),o.getAlphaTesting()&&(this._defines.ALPHATEST=!0),this._shouldUseAlphaFromAlbedoTexture()&&(this._defines.ALPHAFROMALBEDO=!0),this.useEmissiveAsIllumination&&(this._defines.EMISSIVEASILLUMINATION=!0),this.linkEmissiveWithAlbedo&&(this._defines.LINKEMISSIVEWITHALBEDO=!0),this.useLogarithmicDepth&&(this._defines.LOGARITHMICDEPTH=!0),1!=this.cameraContrast&&(this._defines.CAMERACONTRAST=!0),1!=this.cameraExposure&&(this._defines.CAMERATONEMAP=!0),this.cameraColorCurves&&(this._defines.CAMERACOLORCURVES=!0),1==this.overloadedShadeIntensity&&1==this.overloadedShadowIntensity||(this._defines.OVERLOADEDSHADOWVALUES=!0),(this.overloadedMicroSurfaceIntensity>0||this.overloadedEmissiveIntensity>0||this.overloadedReflectivityIntensity>0||this.overloadedAlbedoIntensity>0||this.overloadedAmbientIntensity>0||this.overloadedReflectionIntensity>0)&&(this._defines.OVERLOADEDVALUES=!0),(this.pointsCloud||n.forcePointsCloud)&&(this._defines.POINTSIZE=!0),n.fogEnabled&&i&&i.applyFog&&n.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(this._defines.FOG=!0),e.StandardMaterial.FresnelEnabled&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled||this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled)&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&(this._defines.OPACITYFRESNEL=!0),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._defines.EMISSIVEFRESNEL=!0),s=!0,this._defines.FRESNEL=!0),this._defines.SPECULARTERM&&this.useSpecularOverAlpha&&(this._defines.SPECULAROVERALPHA=!0),this.usePhysicalLightFalloff&&(this._defines.USEPHYSICALLIGHTFALLOFF=!0),this.useRadianceOverAlpha&&(this._defines.RADIANCEOVERALPHA=!0),i&&(s&&i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(this._defines.NORMAL=!0),a&&(i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(this._defines.UV1=!0),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(this._defines.UV2=!0)),i.useVertexColors&&i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(this._defines.VERTEXCOLOR=!0,i.hasVertexAlpha&&(this._defines.VERTEXALPHA=!0)),i.useBones&&i.computeBonesUsingShaders&&(this._defines.NUM_BONE_INFLUENCERS=i.numBoneInfluencers,this._defines.BonesPerMesh=i.skeleton.bones.length+1),r&&(this._defines.INSTANCES=!0)),!this._defines.isEqual(this._cachedDefines)){this._defines.cloneTo(this._cachedDefines),n.resetCachedMaterial();var h=new e.EffectFallbacks;this._defines.REFLECTION&&h.addFallback(0,"REFLECTION"),this._defines.REFRACTION&&h.addFallback(0,"REFRACTION"),this._defines.REFLECTIVITY&&h.addFallback(0,"REFLECTIVITY"),this._defines.BUMP&&h.addFallback(0,"BUMP"),this._defines.PARALLAX&&h.addFallback(1,"PARALLAX"),this._defines.PARALLAXOCCLUSION&&h.addFallback(0,"PARALLAXOCCLUSION"),this._defines.SPECULAROVERALPHA&&h.addFallback(0,"SPECULAROVERALPHA"),this._defines.FOG&&h.addFallback(1,"FOG"),this._defines.POINTSIZE&&h.addFallback(0,"POINTSIZE"),this._defines.LOGARITHMICDEPTH&&h.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(this._defines,h,this.maxSimultaneousLights),this._defines.SPECULARTERM&&h.addFallback(0,"SPECULARTERM"),this._defines.OPACITYFRESNEL&&h.addFallback(1,"OPACITYFRESNEL"),this._defines.EMISSIVEFRESNEL&&h.addFallback(2,"EMISSIVEFRESNEL"),this._defines.FRESNEL&&h.addFallback(3,"FRESNEL"),this._defines.NUM_BONE_INFLUENCERS>0&&h.addCPUSkinningFallback(0,i);var c=[e.VertexBuffer.PositionKind];this._defines.NORMAL&&c.push(e.VertexBuffer.NormalKind),this._defines.UV1&&c.push(e.VertexBuffer.UVKind),this._defines.UV2&&c.push(e.VertexBuffer.UV2Kind),this._defines.VERTEXCOLOR&&c.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(c,i,this._defines,h),e.MaterialHelper.PrepareAttributesForInstances(c,this._defines);var l=this._defines.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vReflectivityInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","depthValues","opacityParts","emissiveLeftColor","emissiveRightColor","vLightingIntensity","vOverloadedShadowIntensity","vOverloadedIntensity","vOverloadedAlbedo","vOverloadedReflection","vOverloadedReflectivity","vOverloadedEmissive","vOverloadedMicroSurface","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vMicrosurfaceTextureLods","vCameraInfos"],d=["albedoSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","reflectivitySampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"];e.ColorCurves.PrepareUniforms(u),e.ColorGradingTexture.PrepareUniformsAndSamplers(u,d),e.MaterialHelper.PrepareUniformsAndSamplersList(u,d,this._defines,this.maxSimultaneousLights),this._effect=n.getEngine().createEffect("pbr",c,u,d,l,h,this.onCompiled,this.onError,{maxSimultaneousLights:this.maxSimultaneousLights})}return!!this._effect.isReady()&&(this._renderId=n.getRenderId(),this._wasPreviouslyReady=!0,i&&(i._materialDefines||(i._materialDefines=new t),this._defines.cloneTo(i._materialDefines)),!0)},r.prototype.unbind=function(){this.reflectionTexture&&this.reflectionTexture.isRenderTarget&&this._effect.setTexture("reflection2DSampler",null),this.refractionTexture&&this.refractionTexture.isRenderTarget&&this._effect.setTexture("refraction2DSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._effect.setMatrix("world",e)},r.prototype.bind=function(t,n){if(this._myScene=this.getScene(),this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(n,this._effect),this._myScene.getCachedMaterial()!==this){if(this._effect.setMatrix("viewProjection",this._myScene.getTransformMatrix()),e.StandardMaterial.FresnelEnabled&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._effect.setColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._effect.setColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._effect.setColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),this._myScene.texturesEnabled){if(this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._effect.setTexture("albedoSampler",this.albedoTexture),this._effect.setFloat2("vAlbedoInfos",this.albedoTexture.coordinatesIndex,this.albedoTexture.level),
this._effect.setMatrix("albedoMatrix",this.albedoTexture.getTextureMatrix())),this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._effect.setTexture("ambientSampler",this.ambientTexture),this._effect.setFloat3("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level,this.ambientTextureStrength),this._effect.setMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix())),this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._effect.setTexture("opacitySampler",this.opacityTexture),this._effect.setFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level),this._effect.setMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix())),this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled&&(this._microsurfaceTextureLods.x=Math.round(Math.log(this.reflectionTexture.getSize().width)*Math.LOG2E),this.reflectionTexture.isCube?this._effect.setTexture("reflectionCubeSampler",this.reflectionTexture):this._effect.setTexture("reflection2DSampler",this.reflectionTexture),this._effect.setMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix()),this._effect.setFloat2("vReflectionInfos",this.reflectionTexture.level,0),this._defines.USESPHERICALFROMREFLECTIONMAP&&(this._effect.setFloat3("vSphericalX",this.reflectionTexture.sphericalPolynomial.x.x,this.reflectionTexture.sphericalPolynomial.x.y,this.reflectionTexture.sphericalPolynomial.x.z),this._effect.setFloat3("vSphericalY",this.reflectionTexture.sphericalPolynomial.y.x,this.reflectionTexture.sphericalPolynomial.y.y,this.reflectionTexture.sphericalPolynomial.y.z),this._effect.setFloat3("vSphericalZ",this.reflectionTexture.sphericalPolynomial.z.x,this.reflectionTexture.sphericalPolynomial.z.y,this.reflectionTexture.sphericalPolynomial.z.z),this._effect.setFloat3("vSphericalXX",this.reflectionTexture.sphericalPolynomial.xx.x,this.reflectionTexture.sphericalPolynomial.xx.y,this.reflectionTexture.sphericalPolynomial.xx.z),this._effect.setFloat3("vSphericalYY",this.reflectionTexture.sphericalPolynomial.yy.x,this.reflectionTexture.sphericalPolynomial.yy.y,this.reflectionTexture.sphericalPolynomial.yy.z),this._effect.setFloat3("vSphericalZZ",this.reflectionTexture.sphericalPolynomial.zz.x,this.reflectionTexture.sphericalPolynomial.zz.y,this.reflectionTexture.sphericalPolynomial.zz.z),this._effect.setFloat3("vSphericalXY",this.reflectionTexture.sphericalPolynomial.xy.x,this.reflectionTexture.sphericalPolynomial.xy.y,this.reflectionTexture.sphericalPolynomial.xy.z),this._effect.setFloat3("vSphericalYZ",this.reflectionTexture.sphericalPolynomial.yz.x,this.reflectionTexture.sphericalPolynomial.yz.y,this.reflectionTexture.sphericalPolynomial.yz.z),this._effect.setFloat3("vSphericalZX",this.reflectionTexture.sphericalPolynomial.zx.x,this.reflectionTexture.sphericalPolynomial.zx.y,this.reflectionTexture.sphericalPolynomial.zx.z))),this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._effect.setTexture("emissiveSampler",this.emissiveTexture),this._effect.setFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level),this._effect.setMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix())),this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._effect.setTexture("lightmapSampler",this.lightmapTexture),this._effect.setFloat2("vLightmapInfos",this.lightmapTexture.coordinatesIndex,this.lightmapTexture.level),this._effect.setMatrix("lightmapMatrix",this.lightmapTexture.getTextureMatrix())),e.StandardMaterial.SpecularTextureEnabled&&(this.metallicTexture?(this._effect.setTexture("reflectivitySampler",this.metallicTexture),this._effect.setFloat2("vReflectivityInfos",this.metallicTexture.coordinatesIndex,this.metallicTexture.level),this._effect.setMatrix("reflectivityMatrix",this.metallicTexture.getTextureMatrix())):this.reflectivityTexture&&(this._effect.setTexture("reflectivitySampler",this.reflectivityTexture),this._effect.setFloat2("vReflectivityInfos",this.reflectivityTexture.coordinatesIndex,this.reflectivityTexture.level),this._effect.setMatrix("reflectivityMatrix",this.reflectivityTexture.getTextureMatrix()))),this.bumpTexture&&this._myScene.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap&&(this._effect.setTexture("bumpSampler",this.bumpTexture),this._effect.setFloat3("vBumpInfos",this.bumpTexture.coordinatesIndex,1/this.bumpTexture.level,this.parallaxScaleBias),this._effect.setMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix())),this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled){this._microsurfaceTextureLods.y=Math.round(Math.log(this.refractionTexture.getSize().width)*Math.LOG2E);var o=1;this.refractionTexture.isCube?this._effect.setTexture("refractionCubeSampler",this.refractionTexture):(this._effect.setTexture("refraction2DSampler",this.refractionTexture),this._effect.setMatrix("refractionMatrix",this.refractionTexture.getReflectionTextureMatrix()),this.refractionTexture.depth&&(o=this.refractionTexture.depth)),this._effect.setFloat4("vRefractionInfos",this.refractionTexture.level,this.indexOfRefraction,o,this.invertRefractionY?-1:1)}(this.reflectionTexture||this.refractionTexture)&&this._effect.setFloat2("vMicrosurfaceTextureLods",this._microsurfaceTextureLods.x,this._microsurfaceTextureLods.y),this.cameraColorGradingTexture&&e.StandardMaterial.ColorGradingTextureEnabled&&e.ColorGradingTexture.Bind(this.cameraColorGradingTexture,this._effect)}e.MaterialHelper.BindClipPlane(this._effect,this._myScene),this.pointsCloud&&this._effect.setFloat("pointSize",this.pointSize),this._myScene.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),this.convertColorToLinearSpaceToRef(this.reflectivityColor,r._scaledReflectivity),this._effect.setVector3("vEyePosition",this._myScene._mirroredCameraPosition?this._myScene._mirroredCameraPosition:this._myScene.activeCamera.position),this._effect.setColor3("vAmbientColor",this._globalAmbientColor),this._effect.setColor4("vReflectivityColor",r._scaledReflectivity,this.microSurface),this.convertColorToLinearSpaceToRef(this.emissiveColor,r._scaledEmissive),this._effect.setColor3("vEmissiveColor",r._scaledEmissive),this.convertColorToLinearSpaceToRef(this.reflectionColor,r._scaledReflection),this._effect.setColor3("vReflectionColor",r._scaledReflection)}this._myScene.getCachedMaterial()===this&&this.isFrozen||(this.convertColorToLinearSpaceToRef(this.albedoColor,r._scaledAlbedo),this._effect.setColor4("vAlbedoColor",r._scaledAlbedo,this.alpha*n.visibility),this._myScene.lightsEnabled&&!this.disableLighting&&r.BindLights(this._myScene,n,this._effect,this._defines,this.useScalarInLinearSpace,this.maxSimultaneousLights,this.usePhysicalLightFalloff),(this._myScene.fogEnabled&&n.applyFog&&this._myScene.fogMode!==e.Scene.FOGMODE_NONE||this.reflectionTexture)&&this._effect.setMatrix("view",this._myScene.getViewMatrix()),e.MaterialHelper.BindFogParameters(this._myScene,n,this._effect),this._lightingInfos.x=this.directIntensity,this._lightingInfos.y=this.emissiveIntensity,this._lightingInfos.z=this.environmentIntensity,this._lightingInfos.w=this.specularIntensity,this._effect.setVector4("vLightingIntensity",this._lightingInfos),this._overloadedShadowInfos.x=this.overloadedShadowIntensity,this._overloadedShadowInfos.y=this.overloadedShadeIntensity,this._effect.setVector4("vOverloadedShadowIntensity",this._overloadedShadowInfos),this._cameraInfos.x=this.cameraExposure,this._cameraInfos.y=this.cameraContrast,this._effect.setVector4("vCameraInfos",this._cameraInfos),this.cameraColorCurves&&e.ColorCurves.Bind(this.cameraColorCurves,this._effect),this._overloadedIntensity.x=this.overloadedAmbientIntensity,this._overloadedIntensity.y=this.overloadedAlbedoIntensity,this._overloadedIntensity.z=this.overloadedReflectivityIntensity,this._overloadedIntensity.w=this.overloadedEmissiveIntensity,this._effect.setVector4("vOverloadedIntensity",this._overloadedIntensity),this.convertColorToLinearSpaceToRef(this.overloadedAmbient,this._tempColor),this._effect.setColor3("vOverloadedAmbient",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedAlbedo,this._tempColor),this._effect.setColor3("vOverloadedAlbedo",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedReflectivity,this._tempColor),this._effect.setColor3("vOverloadedReflectivity",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedEmissive,this._tempColor),this._effect.setColor3("vOverloadedEmissive",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedReflection,this._tempColor),this._effect.setColor3("vOverloadedReflection",this._tempColor),this._overloadedMicroSurface.x=this.overloadedMicroSurface,this._overloadedMicroSurface.y=this.overloadedMicroSurfaceIntensity,this._overloadedMicroSurface.z=this.overloadedReflectionIntensity,this._effect.setVector3("vOverloadedMicroSurface",this._overloadedMicroSurface),e.MaterialHelper.BindLogDepth(this._defines,this._effect,this._myScene)),i.prototype.bind.call(this,t,n),this._myScene=null},r.prototype.getAnimatables=function(){var e=[];return this.albedoTexture&&this.albedoTexture.animations&&this.albedoTexture.animations.length>0&&e.push(this.albedoTexture),this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0&&e.push(this.ambientTexture),this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0&&e.push(this.opacityTexture),this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0&&e.push(this.reflectionTexture),this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0&&e.push(this.emissiveTexture),this.metallicTexture&&this.metallicTexture.animations&&this.metallicTexture.animations.length>0?e.push(this.metallicTexture):this.reflectivityTexture&&this.reflectivityTexture.animations&&this.reflectivityTexture.animations.length>0&&e.push(this.reflectivityTexture),this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this.lightmapTexture&&this.lightmapTexture.animations&&this.lightmapTexture.animations.length>0&&e.push(this.lightmapTexture),this.refractionTexture&&this.refractionTexture.animations&&this.refractionTexture.animations.length>0&&e.push(this.refractionTexture),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.animations&&this.cameraColorGradingTexture.animations.length>0&&e.push(this.cameraColorGradingTexture),e},r.prototype.dispose=function(e,t){t&&(this.albedoTexture&&this.albedoTexture.dispose(),this.ambientTexture&&this.ambientTexture.dispose(),this.opacityTexture&&this.opacityTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose(),this.emissiveTexture&&this.emissiveTexture.dispose(),this.metallicTexture&&this.metallicTexture.dispose(),this.reflectivityTexture&&this.reflectivityTexture.dispose(),this.bumpTexture&&this.bumpTexture.dispose(),this.lightmapTexture&&this.lightmapTexture.dispose(),this.refractionTexture&&this.refractionTexture.dispose(),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.dispose()),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMaterial",t},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r._scaledAlbedo=new e.Color3,r._scaledReflectivity=new e.Color3,r._scaledEmissive=new e.Color3,r._scaledReflection=new e.Color3,__decorate([e.serialize()],r.prototype,"directIntensity",void 0),__decorate([e.serialize()],r.prototype,"emissiveIntensity",void 0),__decorate([e.serialize()],r.prototype,"environmentIntensity",void 0),__decorate([e.serialize()],r.prototype,"specularIntensity",void 0),__decorate([e.serialize()],r.prototype,"disableBumpMap",void 0),__decorate([e.serialize()],r.prototype,"overloadedShadowIntensity",void 0),__decorate([e.serialize()],r.prototype,"overloadedShadeIntensity",void 0),__decorate([e.serialize()],r.prototype,"cameraExposure",void 0),__decorate([e.serialize()],r.prototype,"cameraContrast",void 0),__decorate([e.serializeAsTexture()],r.prototype,"cameraColorGradingTexture",void 0),__decorate([e.serializeAsColorCurves()],r.prototype,"cameraColorCurves",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedAmbient",void 0),__decorate([e.serialize()],r.prototype,"overloadedAmbientIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedAlbedo",void 0),__decorate([e.serialize()],r.prototype,"overloadedAlbedoIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedReflectivity",void 0),__decorate([e.serialize()],r.prototype,"overloadedReflectivityIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedEmissive",void 0),__decorate([e.serialize()],r.prototype,"overloadedEmissiveIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedReflection",void 0),__decorate([e.serialize()],r.prototype,"overloadedReflectionIntensity",void 0),__decorate([e.serialize()],r.prototype,"overloadedMicroSurface",void 0),__decorate([e.serialize()],r.prototype,"overloadedMicroSurfaceIntensity",void 0),__decorate([e.serializeAsTexture()],r.prototype,"albedoTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"ambientTexture",void 0),__decorate([e.serialize()],r.prototype,"ambientTextureStrength",void 0),__decorate([e.serializeAsTexture()],r.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectivityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"metallicTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("albedo")],r.prototype,"albedoColor",void 0),__decorate([e.serializeAsColor3("reflectivity")],r.prototype,"reflectivityColor",void 0),__decorate([e.serializeAsColor3("reflection")],r.prototype,"reflectionColor",void 0),__decorate([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),__decorate([e.serialize()],r.prototype,"microSurface",void 0),__decorate([e.serialize()],r.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],r.prototype,"invertRefractionY",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize()],r.prototype,"linkRefractionWithTransparency",void 0),__decorate([e.serialize()],r.prototype,"linkEmissiveWithAlbedo",void 0),__decorate([e.serialize()],r.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serialize()],r.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize()],r.prototype,"useAlphaFromAlbedoTexture",void 0),__decorate([e.serialize()],r.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),__decorate([e.serialize()],r.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),__decorate([e.serialize()],r.prototype,"useRoughnessFromMetallicTextureGreen",void 0),__decorate([e.serialize()],r.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),__decorate([e.serialize()],r.prototype,"useScalarInLinearSpace",void 0),__decorate([e.serialize()],r.prototype,"usePhysicalLightFalloff",void 0),__decorate([e.serialize()],r.prototype,"useRadianceOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useParallax",void 0),__decorate([e.serialize()],r.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],r.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize()],r.prototype,"disableLighting",void 0),__decorate([e.serialize()],r.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapX",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapY",void 0),__decorate([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.Material);e.PBRMaterial=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){var i=this;this._transformationMatrix=e.Matrix.Identity(),this._enabled=!1,this._labelsEnabled=!1,this._displayStatistics=!0,this._displayTree=!1,this._displayLogs=!1,this._skeletonViewers=new Array,this._identityMatrix=e.Matrix.Identity(),this.axisRatio=.02,this.accentColor="orange",this._scene=t,this._syncPositions=function(){var e=i._scene.getEngine(),t=e.getRenderingCanvasClientRect();i._showUI&&(i._statsDiv.style.left=t.width-410+"px",i._statsDiv.style.top=t.height-290+"px",i._statsDiv.style.width="400px",i._statsDiv.style.height="auto",i._statsSubsetDiv.style.maxHeight="240px",i._optionsDiv.style.left="0px",i._optionsDiv.style.top="10px",i._optionsDiv.style.width="200px",i._optionsDiv.style.height="auto",i._optionsSubsetDiv.style.maxHeight=t.height-225+"px",i._logDiv.style.left="0px",i._logDiv.style.top=t.height-170+"px",i._logDiv.style.width="600px",i._logDiv.style.height="160px",i._treeDiv.style.left=t.width-310+"px",i._treeDiv.style.top="10px",i._treeDiv.style.width="300px",i._treeDiv.style.height="auto",i._treeSubsetDiv.style.maxHeight=t.height-340+"px"),i._globalDiv.style.left=t.left+"px",i._globalDiv.style.top=t.top+"px",i._drawingCanvas.style.left="0px",i._drawingCanvas.style.top="0px",i._drawingCanvas.style.width=e.getRenderWidth()+"px",i._drawingCanvas.style.height=e.getRenderHeight()+"px";var r=window.devicePixelRatio||1,n=i._drawingContext,o=n.webkitBackingStorePixelRatio||n.mozBackingStorePixelRatio||n.msBackingStorePixelRatio||n.oBackingStorePixelRatio||n.backingStorePixelRatio||1;i._ratio=r/o,i._drawingCanvas.width=e.getRenderWidth()*i._ratio,i._drawingCanvas.height=e.getRenderHeight()*i._ratio},this._onCanvasClick=function(e){i._clickPosition={x:e.clientX*i._ratio,y:e.clientY*i._ratio}},this._syncUI=function(){i._showUI&&(i._displayStatistics?(i._displayStats(),i._statsDiv.style.display=""):i._statsDiv.style.display="none",i._displayLogs?i._logDiv.style.display="":i._logDiv.style.display="none",i._displayTree?(i._treeDiv.style.display="",i._needToRefreshMeshesTree&&(i._needToRefreshMeshesTree=!1,i._refreshMeshesTreeContent())):i._treeDiv.style.display="none")},this._syncData=function(){if(i._labelsEnabled||!i._showUI){i._camera.getViewMatrix().multiplyToRef(i._camera.getProjectionMatrix(),i._transformationMatrix),i._drawingContext.clearRect(0,0,i._drawingCanvas.width,i._drawingCanvas.height);var t,r,n=i._scene.getEngine(),o=i._camera.viewport,s=o.toGlobal(n.getRenderWidth(),n.getRenderHeight()),a=i._camera.getActiveMeshes();for(t=0;t<a.length;t++){var h=a.data[t],c=h.getBoundingInfo().boundingSphere.center;r=e.Vector3.Project(c,h.getWorldMatrix(),i._transformationMatrix,s),(h.renderOverlay||i.shouldDisplayAxis&&i.shouldDisplayAxis(h))&&i._renderAxis(r,h,s),i.shouldDisplayLabel&&!i.shouldDisplayLabel(h)||i._renderLabel(h.name,r,12,(function(){h.renderOverlay=!h.renderOverlay}),(function(){return h.renderOverlay?"red":"black"}))}var l=i._scene.cameras;for(t=0;t<l.length;t++){var u=l[t];u!==i._camera&&(r=e.Vector3.Project(e.Vector3.Zero(),u.getWorldMatrix(),i._transformationMatrix,s),i.shouldDisplayLabel&&!i.shouldDisplayLabel(u)||i._renderLabel(u.name,r,12,(function(){i._camera.detachControl(n.getRenderingCanvas()),i._camera=u,i._camera.attachControl(n.getRenderingCanvas())}),(function(){return"purple"})))}var d=i._scene.lights;for(t=0;t<d.length;t++){var f=d[t];f.position&&(r=e.Vector3.Project(f.getAbsolutePosition(),i._identityMatrix,i._transformationMatrix,s),i.shouldDisplayLabel&&!i.shouldDisplayLabel(f)||i._renderLabel(f.name,r,-20,(function(){f.setEnabled(!f.isEnabled())}),(function(){return f.isEnabled()?"orange":"gray"})))}}i._clickPosition=void 0}}return t.prototype._refreshMeshesTreeContent=function(){for(;this._treeSubsetDiv.hasChildNodes();)this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);var e=this._scene.meshes.slice(0,this._scene.meshes.length);e.sort((function(e,t){return e.name===t.name?0:e.name>t.name?1:-1}));for(var t=0;t<e.length;t++){var i=e[t];i.isEnabled()&&this._generateAdvancedCheckBox(this._treeSubsetDiv,i.name,i.getTotalVertices()+" verts",i.isVisible,(function(e,t){t.isVisible=e.checked}),i)}},t.prototype._renderSingleAxis=function(e,t,i,r,n){this._drawingContext.beginPath(),this._drawingContext.moveTo(e.x,e.y),this._drawingContext.lineTo(t.x,t.y),this._drawingContext.strokeStyle=n,this._drawingContext.lineWidth=4,this._drawingContext.stroke(),this._drawingContext.font="normal 14px Segoe UI",this._drawingContext.fillStyle=n,this._drawingContext.fillText(r,i.x,i.y)},t.prototype._renderAxis=function(t,i,r){var n=i.getBoundingInfo().boundingSphere.center,o=i.getWorldMatrix(),s=e.Vector3.UnprojectFromTransform(t.add(new e.Vector3(this._drawingCanvas.width*this.axisRatio,0,0)),r.width,r.height,o,this._transformationMatrix),a=s.subtract(n).length(),h=e.Vector3.Project(n.add(new e.Vector3(a,0,0)),o,this._transformationMatrix,r),c=e.Vector3.Project(n.add(new e.Vector3(1.5*a,0,0)),o,this._transformationMatrix,r);this._renderSingleAxis(t,h,c,"x","#FF0000");var l=e.Vector3.Project(n.add(new e.Vector3(0,a,0)),o,this._transformationMatrix,r),u=e.Vector3.Project(n.add(new e.Vector3(0,1.5*a,0)),o,this._transformationMatrix,r);this._renderSingleAxis(t,l,u,"y","#00FF00");var d=e.Vector3.Project(n.add(new e.Vector3(0,0,a)),o,this._transformationMatrix,r),f=e.Vector3.Project(n.add(new e.Vector3(0,0,1.5*a)),o,this._transformationMatrix,r);this._renderSingleAxis(t,d,f,"z","#0000FF")},t.prototype._renderLabel=function(e,t,i,r,n){if(t.z>0&&t.z<1){this._drawingContext.font="normal 12px Segoe UI";var o=this._drawingContext.measureText(e),s=t.x-o.width/2,a=t.y,h=this._drawingCanvas.getBoundingClientRect();this._showUI&&this._isClickInsideRect(h.left*this._ratio+s-5,h.top*this._ratio+a-i-12,o.width+10,17)&&r(),this._drawingContext.beginPath(),this._drawingContext.rect(s-5,a-i-12,o.width+10,17),this._drawingContext.fillStyle=n(),this._drawingContext.globalAlpha=.5,this._drawingContext.fill(),this._drawingContext.globalAlpha=1,this._drawingContext.strokeStyle="#FFFFFF",this._drawingContext.lineWidth=1,this._drawingContext.stroke(),this._drawingContext.fillStyle="#FFFFFF",this._drawingContext.fillText(e,s,a-i),this._drawingContext.beginPath(),this._drawingContext.arc(t.x,a,5,0,2*Math.PI,!1),this._drawingContext.fill()}},t.prototype._isClickInsideRect=function(e,t,i,r){return!!this._clickPosition&&(!(this._clickPosition.x<e||this._clickPosition.x>e+i)&&!(this._clickPosition.y<t||this._clickPosition.y>t+r))},t.prototype.isVisible=function(){return this._enabled},t.prototype.hide=function(){if(this._enabled){this._enabled=!1;var t=this._scene.getEngine();this._scene.unregisterBeforeRender(this._syncData),this._scene.unregisterAfterRender(this._syncUI),this._rootElement.removeChild(this._globalDiv),this._scene.forceShowBoundingBoxes=!1,this._scene.forceWireframe=!1,e.StandardMaterial.DiffuseTextureEnabled=!0,e.StandardMaterial.AmbientTextureEnabled=!0,e.StandardMaterial.SpecularTextureEnabled=!0,e.StandardMaterial.EmissiveTextureEnabled=!0,e.StandardMaterial.BumpTextureEnabled=!0,e.StandardMaterial.OpacityTextureEnabled=!0,e.StandardMaterial.ReflectionTextureEnabled=!0,e.StandardMaterial.LightmapTextureEnabled=!0,e.StandardMaterial.RefractionTextureEnabled=!0,e.StandardMaterial.ColorGradingTextureEnabled=!0,this._scene.shadowsEnabled=!0,this._scene.particlesEnabled=!0,this._scene.postProcessesEnabled=!0,this._scene.collisionsEnabled=!0,this._scene.lightsEnabled=!0,this._scene.texturesEnabled=!0,this._scene.lensFlaresEnabled=!0,this._scene.proceduralTexturesEnabled=!0,this._scene.renderTargetsEnabled=!0,this._scene.probesEnabled=!0,t.getRenderingCanvas().removeEventListener("click",this._onCanvasClick),this._clearSkeletonViewers()}},t.prototype._clearSkeletonViewers=function(){for(var e=0;e<this._skeletonViewers.length;e++)this._skeletonViewers[e].dispose();this._skeletonViewers=[]},t.prototype.show=function(e,t,i){if(void 0===e&&(e=!0),void 0===t&&(t=null),void 0===i&&(i=null),!this._enabled){this._enabled=!0,t?this._camera=t:this._camera=this._scene.activeCamera,this._showUI=e;var r=this._scene.getEngine();this._globalDiv=document.createElement("div"),this._rootElement=i||document.body,this._rootElement.appendChild(this._globalDiv),this._generateDOMelements(),r.getRenderingCanvas().addEventListener("click",this._onCanvasClick),this._syncPositions(),this._scene.registerBeforeRender(this._syncData),this._scene.registerAfterRender(this._syncUI)}},t.prototype._clearLabels=function(){this._drawingContext.clearRect(0,0,this._drawingCanvas.width,this._drawingCanvas.height);for(var e=0;e<this._scene.meshes.length;e++){var t=this._scene.meshes[e];t.renderOverlay=!1}},t.prototype._generateheader=function(e,t){var i=document.createElement("div");i.innerHTML=t+"&nbsp;",i.style.textAlign="right",i.style.width="100%",i.style.color="white",i.style.backgroundColor="Black",i.style.padding="5px 5px 4px 0px",i.style.marginLeft="-5px",i.style.fontWeight="bold",e.appendChild(i)},t.prototype._generateTexBox=function(e,t,i){var r=document.createElement("label");r.style.display="inline",r.innerHTML=t,r.style.color=i,e.appendChild(r),e.appendChild(document.createElement("br"))},t.prototype._generateAdvancedCheckBox=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=document.createElement("label");s.style.display="inline";var a=document.createElement("input");a.type="checkbox",a.checked=r,a.style.display="inline",a.style.margin="0px 5px 0px 0px",a.style.verticalAlign="sub",a.addEventListener("change",(function(e){n(e.target,o)})),s.appendChild(a);var h=document.createElement("span"),c=document.createElement("span"),l=document.createElement("span");l.style.cssFloat="right",c.innerHTML=t,l.innerHTML=i,l.style.fontSize="12px",l.style.maxWidth="200px",h.appendChild(c),h.appendChild(l),s.appendChild(h),e.appendChild(s),e.appendChild(document.createElement("br"))},t.prototype._generateCheckBox=function(e,t,i,r,n){void 0===n&&(n=null);var o=document.createElement("label");o.style.display="inline";var s=document.createElement("input");s.type="checkbox",s.checked=i,s.style.display="inline",s.style.margin="0px 5px 0px 0px",s.style.verticalAlign="sub",s.addEventListener("change",(function(e){r(e.target,n)})),o.appendChild(s),o.appendChild(document.createTextNode(t)),e.appendChild(o),e.appendChild(document.createElement("br"))},t.prototype._generateButton=function(e,t,i,r){void 0===r&&(r=null);var n=document.createElement("button");n.innerHTML=t,n.style.height="24px",n.style.width="150px",n.style.marginBottom="5px",n.style.color="#444444",n.style.border="1px solid white",n.className="debugLayerButton",n.addEventListener("click",(function(e){i(e.target,r)})),e.appendChild(n),e.appendChild(document.createElement("br"))},t.prototype._generateRadio=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=document.createElement("label");s.style.display="inline";var a=document.createElement("input");a.type="radio",a.name=i,a.checked=r,a.style.display="inline",a.style.margin="0px 5px 0px 0px",a.style.verticalAlign="sub",a.addEventListener("change",(function(e){n(e.target,o)})),s.appendChild(a),s.appendChild(document.createTextNode(t)),e.appendChild(s),e.appendChild(document.createElement("br"))},t.prototype._generateDOMelements=function(){var t=this;if(this._globalDiv.id="DebugLayer",this._globalDiv.style.position="absolute",this._globalDiv.style.fontFamily="Segoe UI, Arial",this._globalDiv.style.fontSize="14px",this._globalDiv.style.color="white",this._drawingCanvas=document.createElement("canvas"),this._drawingCanvas.id="DebugLayerDrawingCanvas",this._drawingCanvas.style.position="absolute",this._drawingCanvas.style.pointerEvents="none",this._drawingCanvas.style.backgroundColor="transparent",this._drawingContext=this._drawingCanvas.getContext("2d"),this._globalDiv.appendChild(this._drawingCanvas),this._showUI){var i="rgba(128, 128, 128, 0.4)",r="rgb(180, 180, 180) solid 1px";this._statsDiv=document.createElement("div"),this._statsDiv.id="DebugLayerStats",this._statsDiv.style.border=r,this._statsDiv.style.position="absolute",this._statsDiv.style.background=i,this._statsDiv.style.padding="0px 0px 0px 5px",this._generateheader(this._statsDiv,"STATISTICS"),this._statsSubsetDiv=document.createElement("div"),this._statsSubsetDiv.style.paddingTop="5px",this._statsSubsetDiv.style.paddingBottom="5px",this._statsSubsetDiv.style.overflowY="auto",this._statsDiv.appendChild(this._statsSubsetDiv),this._treeDiv=document.createElement("div"),this._treeDiv.id="DebugLayerTree",this._treeDiv.style.border=r,this._treeDiv.style.position="absolute",this._treeDiv.style.background=i,this._treeDiv.style.padding="0px 0px 0px 5px",this._treeDiv.style.display="none",this._generateheader(this._treeDiv,"MESHES TREE"),this._treeSubsetDiv=document.createElement("div"),this._treeSubsetDiv.style.paddingTop="5px",this._treeSubsetDiv.style.paddingRight="5px",this._treeSubsetDiv.style.overflowY="auto",this._treeSubsetDiv.style.maxHeight="300px",this._treeDiv.appendChild(this._treeSubsetDiv),this._needToRefreshMeshesTree=!0,this._logDiv=document.createElement("div"),this._logDiv.style.border=r,this._logDiv.id="DebugLayerLogs",this._logDiv.style.position="absolute",this._logDiv.style.background=i,this._logDiv.style.padding="0px 0px 0px 5px",this._logDiv.style.display="none",this._generateheader(this._logDiv,"LOGS"),this._logSubsetDiv=document.createElement("div"),this._logSubsetDiv.style.height="127px",this._logSubsetDiv.style.paddingTop="5px",this._logSubsetDiv.style.overflowY="auto",this._logSubsetDiv.style.fontSize="12px",this._logSubsetDiv.style.fontFamily="consolas",this._logSubsetDiv.innerHTML=e.Tools.LogCache,this._logDiv.appendChild(this._logSubsetDiv),e.Tools.OnNewCacheEntry=function(e){t._logSubsetDiv.innerHTML=e+t._logSubsetDiv.innerHTML},this._optionsDiv=document.createElement("div"),this._optionsDiv.id="DebugLayerOptions",this._optionsDiv.style.border=r,this._optionsDiv.style.position="absolute",this._optionsDiv.style.background=i,this._optionsDiv.style.padding="0px 0px 0px 5px",this._optionsDiv.style.overflowY="auto",this._generateheader(this._optionsDiv,"OPTIONS"),this._optionsSubsetDiv=document.createElement("div"),this._optionsSubsetDiv.style.paddingTop="5px",this._optionsSubsetDiv.style.paddingBottom="5px",this._optionsSubsetDiv.style.overflowY="auto",this._optionsSubsetDiv.style.maxHeight="200px",this._optionsDiv.appendChild(this._optionsSubsetDiv),this._generateTexBox(this._optionsSubsetDiv,"<b>Windows:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Statistics",this._displayStatistics,(function(e){t._displayStatistics=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Logs",this._displayLogs,(function(e){t._displayLogs=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Meshes tree",this._displayTree,(function(e){t._displayTree=e.checked,t._needToRefreshMeshesTree=!0})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>General:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Bounding boxes",this._scene.forceShowBoundingBoxes,(function(e){t._scene.forceShowBoundingBoxes=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Clickable labels",this._labelsEnabled,(function(e){t._labelsEnabled=e.checked,t._labelsEnabled||t._clearLabels()})),
this._generateCheckBox(this._optionsSubsetDiv,"Generate user marks (F12)",e.Tools.PerformanceLogLevel===e.Tools.PerformanceUserMarkLogLevel,(function(t){t.checked?e.Tools.PerformanceLogLevel=e.Tools.PerformanceUserMarkLogLevel:e.Tools.PerformanceLogLevel=e.Tools.PerformanceNoneLogLevel})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Rendering mode:</b>",this.accentColor),this._generateRadio(this._optionsSubsetDiv,"Solid","renderMode",!this._scene.forceWireframe&&!this._scene.forcePointsCloud,(function(e){e.checked&&(t._scene.forceWireframe=!1,t._scene.forcePointsCloud=!1)})),this._generateRadio(this._optionsSubsetDiv,"Wireframe","renderMode",this._scene.forceWireframe,(function(e){e.checked&&(t._scene.forceWireframe=!0,t._scene.forcePointsCloud=!1)})),this._generateRadio(this._optionsSubsetDiv,"Point","renderMode",this._scene.forcePointsCloud,(function(e){e.checked&&(t._scene.forceWireframe=!1,t._scene.forcePointsCloud=!0)})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Texture channels:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Diffuse",e.StandardMaterial.DiffuseTextureEnabled,(function(t){e.StandardMaterial.DiffuseTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Ambient",e.StandardMaterial.AmbientTextureEnabled,(function(t){e.StandardMaterial.AmbientTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Specular",e.StandardMaterial.SpecularTextureEnabled,(function(t){e.StandardMaterial.SpecularTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Emissive",e.StandardMaterial.EmissiveTextureEnabled,(function(t){e.StandardMaterial.EmissiveTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Bump",e.StandardMaterial.BumpTextureEnabled,(function(t){e.StandardMaterial.BumpTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Opacity",e.StandardMaterial.OpacityTextureEnabled,(function(t){e.StandardMaterial.OpacityTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Reflection",e.StandardMaterial.ReflectionTextureEnabled,(function(t){e.StandardMaterial.ReflectionTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Refraction",e.StandardMaterial.RefractionTextureEnabled,(function(t){e.StandardMaterial.RefractionTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"ColorGrading",e.StandardMaterial.ColorGradingTextureEnabled,(function(t){e.StandardMaterial.ColorGradingTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Lightmap",e.StandardMaterial.LightmapTextureEnabled,(function(t){e.StandardMaterial.LightmapTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Fresnel",e.StandardMaterial.FresnelEnabled,(function(t){e.StandardMaterial.FresnelEnabled=t.checked})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Options:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Animations",this._scene.animationsEnabled,(function(e){t._scene.animationsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Collisions",this._scene.collisionsEnabled,(function(e){t._scene.collisionsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Fog",this._scene.fogEnabled,(function(e){t._scene.fogEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Lens flares",this._scene.lensFlaresEnabled,(function(e){t._scene.lensFlaresEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Lights",this._scene.lightsEnabled,(function(e){t._scene.lightsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Particles",this._scene.particlesEnabled,(function(e){t._scene.particlesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Post-processes",this._scene.postProcessesEnabled,(function(e){t._scene.postProcessesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Probes",this._scene.probesEnabled,(function(e){t._scene.probesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Procedural textures",this._scene.proceduralTexturesEnabled,(function(e){t._scene.proceduralTexturesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Render targets",this._scene.renderTargetsEnabled,(function(e){t._scene.renderTargetsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Shadows",this._scene.shadowsEnabled,(function(e){t._scene.shadowsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Skeletons",this._scene.skeletonsEnabled,(function(e){t._scene.skeletonsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Sprites",this._scene.spritesEnabled,(function(e){t._scene.spritesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Textures",this._scene.texturesEnabled,(function(e){t._scene.texturesEnabled=e.checked})),e.AudioEngine&&e.Engine.audioEngine.canUseWebAudio&&(this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Audio:</b>",this.accentColor),this._generateRadio(this._optionsSubsetDiv,"Headphones","panningModel",this._scene.headphone,(function(e){e.checked&&(t._scene.headphone=!0)})),this._generateRadio(this._optionsSubsetDiv,"Normal Speakers","panningModel",!this._scene.headphone,(function(e){e.checked&&(t._scene.headphone=!1)})),this._generateCheckBox(this._optionsSubsetDiv,"Disable audio",!this._scene.audioEnabled,(function(e){t._scene.audioEnabled=!e.checked}))),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Viewers:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Skeletons",!1,(function(i){if(!i.checked)return void t._clearSkeletonViewers();for(var r=0;r<t._scene.meshes.length;r++){var n=t._scene.meshes[r];if(n.skeleton){for(var o=!1,s=0;s<t._skeletonViewers.length;s++)if(t._skeletonViewers[s].skeleton===n.skeleton){o=!0;break}if(o)continue;var a=new e.Debug.SkeletonViewer(n.skeleton,n,t._scene);a.isEnabled=!0,t._skeletonViewers.push(a)}}})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Tools:</b>",this.accentColor),this._generateButton(this._optionsSubsetDiv,"Dump rendertargets",(function(e){t._scene.dumpNextRenderTargets=!0})),this._generateButton(this._optionsSubsetDiv,"Run SceneOptimizer",(function(i){e.SceneOptimizer.OptimizeAsync(t._scene)})),this._generateButton(this._optionsSubsetDiv,"Log camera object",(function(e){t._camera?console.log(t._camera):console.warn("No camera defined, or debug layer created before camera creation!")})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._globalDiv.appendChild(this._statsDiv),this._globalDiv.appendChild(this._logDiv),this._globalDiv.appendChild(this._optionsDiv),this._globalDiv.appendChild(this._treeDiv)}},t.prototype._displayStats=function(){var t=this._scene,i=t.getEngine(),r=i.getGlInfo();this._statsSubsetDiv.innerHTML="Babylon.js v"+e.Engine.Version+" - <b>"+e.Tools.Format(i.getFps(),0)+" fps</b><br><br><div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'><b>Count</b><br>Total meshes: "+t.meshes.length+"<br>Total lights: "+t.lights.length+"<br>Total vertices: "+t.getTotalVertices()+"<br>Total materials: "+t.materials.length+"<br>Total textures: "+t.textures.length+"<br>Active meshes: "+t.getActiveMeshes().length+"<br>Active indices: "+t.getActiveIndices()+"<br>Active bones: "+t.getActiveBones()+"<br>Active particles: "+t.getActiveParticles()+"<br><b>Draw calls: "+i.drawCalls+"</b><br><br><b>Duration</b><br>Meshes selection:</i> "+e.Tools.Format(t.getEvaluateActiveMeshesDuration())+" ms<br>Render Targets: "+e.Tools.Format(t.getRenderTargetsDuration())+" ms<br>Particles: "+e.Tools.Format(t.getParticlesDuration())+" ms<br>Sprites: "+e.Tools.Format(t.getSpritesDuration())+" ms<br><br>Render: <b>"+e.Tools.Format(t.getRenderDuration())+" ms</b><br>Frame: "+e.Tools.Format(t.getLastFrameDuration())+" ms<br>Potential FPS: "+e.Tools.Format(1e3/t.getLastFrameDuration(),0)+"<br>Resolution: "+i.getRenderWidth()+"x"+i.getRenderHeight()+"<br><br></div><div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'><b>Extensions</b><br>Std derivatives: "+(i.getCaps().standardDerivatives?"Yes":"No")+"<br>Compressed textures: "+(i.getCaps().s3tc?"Yes":"No")+"<br>Hardware instances: "+(i.getCaps().instancedArrays?"Yes":"No")+"<br>Texture float: "+(i.getCaps().textureFloat?"Yes":"No")+"<br><br>32bits indices: "+(i.getCaps().uintIndices?"Yes":"No")+"<br>Fragment depth: "+(i.getCaps().fragmentDepthSupported?"Yes":"No")+"<br>High precision shaders: "+(i.getCaps().highPrecisionShaderSupported?"Yes":"No")+"<br>Draw buffers: "+(i.getCaps().drawBuffersExtension?"Yes":"No")+"<br></div><br><div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'><b>Caps.</b><br>Stencil: "+(i.isStencilEnable?"Enabled":"Disabled")+"<br>Max textures units: "+i.getCaps().maxTexturesImageUnits+"<br>Max textures size: "+i.getCaps().maxTextureSize+"<br>Max anisotropy: "+i.getCaps().maxAnisotropy+"<br><b>Info</b><br>WebGL feature level: "+i.webGLVersion+"<br>"+r.version+"<br></div><br>"+r.renderer+"<br>",this.customStatsFunction&&(this._statsSubsetDiv.innerHTML+=this.customStatsFunction())},t})();e.DebugLayer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this;void 0===o&&(o=null),t.call(this,r.getEngine(),i),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.gaussianBlurHPostProcesses=[],this.gaussianBlurVPostProcesses=[],this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.depthOfFieldPostProcess=null,this.brightThreshold=1,this.blurWidth=2,this.gaussianCoefficient=.25,this.gaussianMean=1,this.gaussianStandardDeviation=1,this.exposure=1,this.lensTexture=null,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.animations=[],this._depthRenderer=null,this._depthOfFieldEnabled=!0,this._lensFlareEnabled=!0,this._scene=r,o?this.originalPostProcess=o:this.originalPostProcess=new e.PostProcess("HDRPass","standard",[],[],n,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),(!0),"#define PASS_POST_PROCESS",e.Engine.TEXTURETYPE_FLOAT),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),"HDRPassPostProcess",function(){return a.originalPostProcess},(!0))),this._createDownSampleX4PostProcess(r,n/2),this._createBrightPassPostProcess(r,n/2),this._createGaussianBlurPostProcesses(r,n/2,0),this._createGaussianBlurPostProcesses(r,n/4,1),this._createGaussianBlurPostProcesses(r,n/8,2),this._createGaussianBlurPostProcesses(r,n/16,3),this._createTextureAdderPostProcess(r,n),this.textureAdderFinalPostProcess=new e.PostProcess("HDRDepthOfFieldSource","standard",[],[],n,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),(!0),"#define PASS_POST_PROCESS",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),"HDRDepthOfFieldSource",function(){return a.textureAdderFinalPostProcess},(!0))),this._createLensFlarePostProcess(r,n),this._createGaussianBlurPostProcesses(r,n/2,5),this._createDepthOfFieldPostProcess(r,n),r.postProcessRenderPipelineManager.addPipeline(this),null!==s&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,s),this.LensFlareEnabled=!1,this.DepthOfFieldEnabled=!1}return __extends(i,t),Object.defineProperty(i.prototype,"DepthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){var t=this.gaussianBlurHPostProcesses.length-1;e&&!this._depthOfFieldEnabled?(this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRDepthOfField",this._scene.cameras),this._depthRenderer=this._scene.enableDepthRenderer()):!e&&this._depthOfFieldEnabled&&(this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRDepthOfField",this._scene.cameras)),this._depthOfFieldEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"LensFlareEnabled",{get:function(){return this._lensFlareEnabled},set:function(e){var t=this.gaussianBlurHPostProcesses.length-2;e&&!this._lensFlareEnabled?(this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRLensFlare",this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRLensFlareShift",this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRLensFlareCompose",this._scene.cameras)):!e&&this._lensFlareEnabled&&(this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRLensFlare",this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRLensFlareShift",this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRLensFlareCompose",this._scene.cameras)),this._lensFlareEnabled=e},enumerable:!0,configurable:!0}),i.prototype._createDownSampleX4PostProcess=function(t,i){var r=this,n=new Array(32);this.downSampleX4PostProcess=new e.PostProcess("HDRDownSampleX4","standard",["dsOffsets"],[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define DOWN_SAMPLE_X4",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.downSampleX4PostProcess.onApply=function(e){for(var t=0,i=-2;i<2;i++)for(var o=-2;o<2;o++)n[t]=(i+.5)*(1/r.downSampleX4PostProcess.width),n[t+1]=(o+.5)*(1/r.downSampleX4PostProcess.height),t+=2;e.setArray2("dsOffsets",n)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDownSampleX4",function(){return r.downSampleX4PostProcess},(!0)))},i.prototype._createBrightPassPostProcess=function(t,i){var r=this,n=new Array(8);this.brightPassPostProcess=new e.PostProcess("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define BRIGHT_PASS",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.brightPassPostProcess.onApply=function(e){var t=1/r.brightPassPostProcess.width,i=1/r.brightPassPostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i,e.setArray2("dsOffsets",n),e.setFloat("brightThreshold",r.brightThreshold)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRBrightPass",function(){return r.brightPassPostProcess},(!0)))},i.prototype._createGaussianBlurPostProcesses=function(t,i,r){var n=this,o=new Array(9),s=new Array(9),a=["blurOffsets","blurWeights","blurWidth"],h=function(e){return function(i){for(var r=0,a=0;a<9;a++)r=(a-4)/4,s[a]=n.gaussianCoefficient*(1/Math.sqrt(2*Math.PI*n.gaussianStandardDeviation))*Math.exp(-((r-n.gaussianMean)*(r-n.gaussianMean))/(2*n.gaussianStandardDeviation*n.gaussianStandardDeviation));for(var h={width:t.getEngine().getRenderWidth(),height:t.getEngine().getRenderHeight()},a=0;a<9;a++){var c=(a-4)*(1/(e===!0?h.height:h.width));o[a]=c}i.setArray("blurOffsets",o),i.setArray("blurWeights",s),i.setFloat("blurWidth",n.blurWidth)}},c=new e.PostProcess("HDRGaussianBlurH"+i,"standard",a,[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_H",e.Engine.TEXTURETYPE_UNSIGNED_INT);c.onApply=h(!1);var l=new e.PostProcess("HDRGaussianBlurV"+i,"standard",a,[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_V",e.Engine.TEXTURETYPE_UNSIGNED_INT);l.onApply=h(!0),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRGaussianBlurH"+r,function(){return c},(!0))),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRGaussianBlurV"+r,function(){return l},(!0))),this.gaussianBlurHPostProcesses.push(c),this.gaussianBlurVPostProcesses.push(l)},i.prototype._createTextureAdderPostProcess=function(t,i){var r=this;this.gaussianBlurVPostProcesses[3];this.textureAdderPostProcess=new e.PostProcess("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define TEXTURE_ADDER",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r.originalPostProcess),e.setTexture("lensSampler",r.lensTexture),e.setFloat("exposure",r.exposure)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRTextureAdder",function(){return r.textureAdderPostProcess},(!0)))},i.prototype._createLensFlarePostProcess=function(t,i){var r=this;this.lensFlarePostProcess=new e.PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],i/2,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!0),"#define LENS_FLARE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlare",function(){return r.lensFlarePostProcess},(!1))),this._createGaussianBlurPostProcesses(t,i/4,4),this.lensFlareComposePostProcess=new e.PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define LENS_FLARE_COMPOSE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlareCompose",function(){return r.lensFlareComposePostProcess},(!1)));var n=new e.Vector2(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",r.gaussianBlurHPostProcesses[0]),e.setTexture("lensColorSampler",r.lensColorTexture),e.setFloat("strength",r.lensFlareStrength),e.setFloat("ghostDispersal",r.lensFlareGhostDispersal),e.setFloat("haloWidth",r.lensFlareHaloWidth),n.x=r.lensFlarePostProcess.width,n.y=r.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",r.lensFlareDistortionStrength)};var o=e.Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=e.Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(t){t.setTextureFromPostProcess("otherSampler",r.textureAdderFinalPostProcess),t.setTexture("lensDirtSampler",r.lensFlareDirtTexture),t.setTexture("lensStarSampler",r.lensStarTexture);var i=r._scene.activeCamera.getViewMatrix().getRow(0),n=r._scene.activeCamera.getViewMatrix().getRow(2),a=e.Vector3.Dot(i.toVector3(),new e.Vector3(1,0,0))+e.Vector3.Dot(n.toVector3(),new e.Vector3(0,0,1));a*=4;var h=e.Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),c=s.multiply(h).multiply(o);t.setMatrix("lensStarMatrix",c)}},i.prototype._createDepthOfFieldPostProcess=function(t,i){var r=this;this.depthOfFieldPostProcess=new e.PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define DEPTH_OF_FIELD",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r.textureAdderFinalPostProcess),e.setTexture("depthSampler",r._depthRenderer.getDepthMap()),e.setFloat("distance",r.depthOfFieldDistance)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDepthOfField",function(){return r.depthOfFieldPostProcess},(!0)))},i.prototype.dispose=function(){for(var e=0;e<this._scene.cameras.length;e++){var i=this._scene.cameras[e];this.originalPostProcess.dispose(i),this.downSampleX4PostProcess.dispose(i),this.brightPassPostProcess.dispose(i),this.textureAdderPostProcess.dispose(i);for(var r=0;r<this.gaussianBlurHPostProcesses.length;r++)this.gaussianBlurHPostProcesses[r].dispose(i);for(var r=0;r<this.gaussianBlurVPostProcesses.length;r++)this.gaussianBlurVPostProcesses[r].dispose(i);this.textureAdderFinalPostProcess.dispose(i),this.lensFlarePostProcess.dispose(i),this.lensFlareComposePostProcess.dispose(i),this.depthOfFieldPostProcess.dispose(i)}this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),t.prototype.dispose.call(this)},i})(e.PostProcessRenderPipeline);e.StandardRenderingPipeline=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore={anaglyphPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}",blackAndWhitePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}",blurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",chromaticAberrationPixelShader:"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}",colorPixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",colorVertexShader:"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}",colorCorrectionPixelShader:"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}",convolutionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}",defaultPixelShader:"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}",
defaultVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}",depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",depthOfFieldPixelShader:"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n",displayPassPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}",filterPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}",fxaaPixelShader:"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}",glowBlurPostProcessPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",glowMapGenerationPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}",glowMapGenerationVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",glowMapMergePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}",glowMapMergeVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",hdrPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n",layerPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}",layerVertexShader:"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}",lensFlarePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}",lensFlareVertexShader:"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}",lensHighlightsPixelShader:"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}",linePixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",lineVertexShader:"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}",outlinePixelShader:"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}",outlineVertexShader:"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",pbrPixelShader:"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}",
pbrVertexShader:"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",refractionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}",shadowMapPixelShader:"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n",ssaoCombinePixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n",standardPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n",stereoscopicInterlacePixelShader:"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}",tonemapPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}",volumetricLightScatteringPixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n",volumetricLightScatteringPassPixelShader:"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n",vrDistortionCorrectionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"},BABYLON.Effect.IncludesShadersStore={bonesDeclaration:"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif",bonesVertex:"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif",bumpFragment:"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif",bumpFragmentFunctions:"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif",clipPlaneFragment:"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif",clipPlaneFragmentDeclaration:"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif",clipPlaneVertex:"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif",clipPlaneVertexDeclaration:"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif",colorCurves:"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}",colorCurvesDefinition:"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;",colorGrading:"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}",colorGradingDefinition:"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;",fogFragment:"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif",fogFragmentDeclaration:"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif",fogVertex:"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif",fogVertexDeclaration:"#ifdef FOG\nvarying float fFogDistance;\n#endif",fresnelFunction:"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif",harmonicsFunctions:"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif",helperFunctions:"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}",instancesDeclaration:"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif",instancesVertex:"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif",lightFragment:"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif",lightFragmentDeclaration:"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif",lightsFragmentFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n",
logDepthDeclaration:"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif",logDepthFragment:"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif",logDepthVertex:"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif",pbrFunctions:"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif",pbrLightFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}",pbrLightFunctionsCall:"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif",pbrShadowFunctions:"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif",pointCloudVertex:"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif",pointCloudVertexDeclaration:"#ifdef POINTSIZE\nuniform float pointSize;\n#endif",reflectionFunction:"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}",shadowsFragmentFunctions:"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif",shadowsVertex:"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif",shadowsVertexDeclaration:"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"},BABYLON.CollisionWorker='var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log("no mesh geometry id");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log("couldn\'t find geometry",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts("./babylon.collisionCoordinator.js"),importScripts("./babylon.collider.js"),importScripts("../Math/babylon.math.js"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log("single worker init")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker="",function(e){e[e.INIT=0]="INIT",e[e.UPDATE=1]="UPDATE",e[e.COLLIDE=2]="COLLIDE"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.UNKNOWN_ERROR=1]="UNKNOWN_ERROR"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},t.ToHex=function(t){var i=t.toString(16);return t<=15?("0"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},n.prototype.getClassName=function(){return"Color3"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return"#"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if("#"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},t.prototype.getClassName=function(){return"Color4"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return"#"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if("#"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+"}"},n.prototype.getClassName=function(){return"Vector2"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},n.prototype.getClassName=function(){return"Vector3"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},n.prototype.getClassName=function(){return"Vector4"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},t.prototype.getClassName=function(){return"Size"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},t.prototype.getClassName=function(){return"Quaternion"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t="YZX");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i="YZX");var n=this.z,r=this.x,o=this.y,e=this.w,s=e*e,h=n*n,a=r*r,u=o*o,m=o*n-r*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(r*o+n*e),-h-a+u+s),t.x=Math.asin(-2*(n*o-r*e)),t.y=Math.atan2(2*(n*r+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o=t.Identity();return t.SlerpToRef(i,n,r,o),o},t.SlerpToRef=function(t,i,n,r){var o,e,s=n,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}r.x=e*t.x+o*i.x,r.y=e*t.y+o*i.y,r.z=e*t.z+o*i.z,r.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+n*_+r*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,q=s*y-h*m,D=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*q)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*H-n*D+o*N)*b,t.m[15]=(i*q-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this;\n},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return"Matrix"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.prototype.getRotationMatrix=function(){var i=t.Identity();return this.getRotationMatrixToRef(i),i},t.prototype.getRotationMatrixToRef=function(i){var n=this.m,r=n[0]*n[1]*n[2]*n[3]<0?-1:1,o=n[4]*n[5]*n[6]*n[7]<0?-1:1,e=n[8]*n[9]*n[10]*n[11]<0?-1:1,s=r*Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),h=o*Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),a=e*Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]);t.FromValuesToRef(n[0]/s,n[1]/s,n[2]/s,0,n[4]/h,n[5]/h,n[6]/h,0,n[8]/a,n[9]/a,n[10]/a,0,0,0,0,1,i)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t.FromXYZAxesToRef=function(t,i,n,r){r.m[0]=t.x,r.m[1]=t.y,r.m[2]=t.z,r.m[3]=0,r.m[4]=i.x,r.m[5]=i.y,r.m[6]=i.z,r.m[7]=0,r.m[8]=n.x,r.m[9]=n.y,r.m[10]=n.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.FromQuaternionToRef=function(t,i){var n=t.x*t.x,r=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(r+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+n),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(r+n),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return"Plane"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return n<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]="LOCAL",t[t.WORLD=1]="WORLD"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]="CW",t[t.CCW=1]="CCW"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype["continue"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));',
("undefined"!=typeof window&&window.module||"undefined"!=typeof module)&&"undefined"!=typeof module.exports&&(module.exports=BABYLON);
 
Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.max.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.max.js

Statements: 3.26% (1127 / 34615)      Branches: 0.24% (32 / 13260)      Functions: 1.19% (56 / 4722)      Lines: 3.29% (1122 / 34087)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920 19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947 19948 19949 19950 19951 19952 19953 19954 19955 19956 19957 19958 19959 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971 19972 19973 19974 19975 19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036 20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074 20075 20076 20077 20078 20079 20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102 20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114 20115 20116 20117 20118 20119 20120 20121 20122 20123 20124 20125 20126 20127 20128 20129 20130 20131 20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146 20147 20148 20149 20150 20151 20152 20153 20154 20155 20156 20157 20158 20159 20160 20161 20162 20163 20164 20165 20166 20167 20168 20169 20170 20171 20172 20173 20174 20175 20176 20177 20178 20179 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207 20208 20209 20210 20211 20212 20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241 20242 20243 20244 20245 20246 20247 20248 20249 20250 20251 20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267 20268 20269 20270 20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283 20284 20285 20286 20287 20288 20289 20290 20291 20292 20293 20294 20295 20296 20297 20298 20299 20300 20301 20302 20303 20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314 20315 20316 20317 20318 20319 20320 20321 20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340 20341 20342 20343 20344 20345 20346 20347 20348 20349 20350 20351 20352 20353 20354 20355 20356 20357 20358 20359 20360 20361 20362 20363 20364 20365 20366 20367 20368 20369 20370 20371 20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385 20386 20387 20388 20389 20390 20391 20392 20393 20394 20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414 20415 20416 20417 20418 20419 20420 20421 20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439 20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450 20451 20452 20453 20454 20455 20456 20457 20458 20459 20460 20461 20462 20463 20464 20465 20466 20467 20468 20469 20470 20471 20472 20473 20474 20475 20476 20477 20478 20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489 20490 20491 20492 20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506 20507 20508 20509 20510 20511 20512 20513 20514 20515 20516 20517 20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557 20558 20559 20560 20561 20562 20563 20564 20565 20566 20567 20568 20569 20570 20571 20572 20573 20574 20575 20576 20577 20578 20579 20580 20581 20582 20583 20584 20585 20586 20587 20588 20589 20590 20591 20592 20593 20594 20595 20596 20597 20598 20599 20600 20601 20602 20603 20604 20605 20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701 20702 20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765 20766 20767 20768 20769 20770 20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783 20784 20785 20786 20787 20788 20789 20790 20791 20792 20793 20794 20795 20796 20797 20798 20799 20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815 20816 20817 20818 20819 20820 20821 20822 20823 20824 20825 20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838 20839 20840 20841 20842 20843 20844 20845 20846 20847 20848 20849 20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869 20870 20871 20872 20873 20874 20875 20876 20877 20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904 20905 20906 20907 20908 20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934 20935 20936 20937 20938 20939 20940 20941 20942 20943 20944 20945 20946 20947 20948 20949 20950 20951 20952 20953 20954 20955 20956 20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968 20969 20970 20971 20972 20973 20974 20975 20976 20977 20978 20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991 20992 20993 20994 20995 20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006 21007 21008 21009 21010 21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025 21026 21027 21028 21029 21030 21031 21032 21033 21034 21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132 21133 21134 21135 21136 21137 21138 21139 21140 21141 21142 21143 21144 21145 21146 21147 21148 21149 21150 21151 21152 21153 21154 21155 21156 21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182 21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251 21252 21253 21254 21255 21256 21257 21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291 21292 21293 21294 21295 21296 21297 21298 21299 21300 21301 21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314 21315 21316 21317 21318 21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336 21337 21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388 21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403 21404 21405 21406 21407 21408 21409 21410 21411 21412 21413 21414 21415 21416 21417 21418 21419 21420 21421 21422 21423 21424 21425 21426 21427 21428 21429 21430 21431 21432 21433 21434 21435 21436 21437 21438 21439 21440 21441 21442 21443 21444 21445 21446 21447 21448 21449 21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480 21481 21482 21483 21484 21485 21486 21487 21488 21489 21490 21491 21492 21493 21494 21495 21496 21497 21498 21499 21500 21501 21502 21503 21504 21505 21506 21507 21508 21509 21510 21511 21512 21513 21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533 21534 21535 21536 21537 21538 21539 21540 21541 21542 21543 21544 21545 21546 21547 21548 21549 21550 21551 21552 21553 21554 21555 21556 21557 21558 21559 21560 21561 21562 21563 21564 21565 21566 21567 21568 21569 21570 21571 21572 21573 21574 21575 21576 21577 21578 21579 21580 21581 21582 21583 21584 21585 21586 21587 21588 21589 21590 21591 21592 21593 21594 21595 21596 21597 21598 21599 21600 21601 21602 21603 21604 21605 21606 21607 21608 21609 21610 21611 21612 21613 21614 21615 21616 21617 21618 21619 21620 21621 21622 21623 21624 21625 21626 21627 21628 21629 21630 21631 21632 21633 21634 21635 21636 21637 21638 21639 21640 21641 21642 21643 21644 21645 21646 21647 21648 21649 21650 21651 21652 21653 21654 21655 21656 21657 21658 21659 21660 21661 21662 21663 21664 21665 21666 21667 21668 21669 21670 21671 21672 21673 21674 21675 21676 21677 21678 21679 21680 21681 21682 21683 21684 21685 21686 21687 21688 21689 21690 21691 21692 21693 21694 21695 21696 21697 21698 21699 21700 21701 21702 21703 21704 21705 21706 21707 21708 21709 21710 21711 21712 21713 21714 21715 21716 21717 21718 21719 21720 21721 21722 21723 21724 21725 21726 21727 21728 21729 21730 21731 21732 21733 21734 21735 21736 21737 21738 21739 21740 21741 21742 21743 21744 21745 21746 21747 21748 21749 21750 21751 21752 21753 21754 21755 21756 21757 21758 21759 21760 21761 21762 21763 21764 21765 21766 21767 21768 21769 21770 21771 21772 21773 21774 21775 21776 21777 21778 21779 21780 21781 21782 21783 21784 21785 21786 21787 21788 21789 21790 21791 21792 21793 21794 21795 21796 21797 21798 21799 21800 21801 21802 21803 21804 21805 21806 21807 21808 21809 21810 21811 21812 21813 21814 21815 21816 21817 21818 21819 21820 21821 21822 21823 21824 21825 21826 21827 21828 21829 21830 21831 21832 21833 21834 21835 21836 21837 21838 21839 21840 21841 21842 21843 21844 21845 21846 21847 21848 21849 21850 21851 21852 21853 21854 21855 21856 21857 21858 21859 21860 21861 21862 21863 21864 21865 21866 21867 21868 21869 21870 21871 21872 21873 21874 21875 21876 21877 21878 21879 21880 21881 21882 21883 21884 21885 21886 21887 21888 21889 21890 21891 21892 21893 21894 21895 21896 21897 21898 21899 21900 21901 21902 21903 21904 21905 21906 21907 21908 21909 21910 21911 21912 21913 21914 21915 21916 21917 21918 21919 21920 21921 21922 21923 21924 21925 21926 21927 21928 21929 21930 21931 21932 21933 21934 21935 21936 21937 21938 21939 21940 21941 21942 21943 21944 21945 21946 21947 21948 21949 21950 21951 21952 21953 21954 21955 21956 21957 21958 21959 21960 21961 21962 21963 21964 21965 21966 21967 21968 21969 21970 21971 21972 21973 21974 21975 21976 21977 21978 21979 21980 21981 21982 21983 21984 21985 21986 21987 21988 21989 21990 21991 21992 21993 21994 21995 21996 21997 21998 21999 22000 22001 22002 22003 22004 22005 22006 22007 22008 22009 22010 22011 22012 22013 22014 22015 22016 22017 22018 22019 22020 22021 22022 22023 22024 22025 22026 22027 22028 22029 22030 22031 22032 22033 22034 22035 22036 22037 22038 22039 22040 22041 22042 22043 22044 22045 22046 22047 22048 22049 22050 22051 22052 22053 22054 22055 22056 22057 22058 22059 22060 22061 22062 22063 22064 22065 22066 22067 22068 22069 22070 22071 22072 22073 22074 22075 22076 22077 22078 22079 22080 22081 22082 22083 22084 22085 22086 22087 22088 22089 22090 22091 22092 22093 22094 22095 22096 22097 22098 22099 22100 22101 22102 22103 22104 22105 22106 22107 22108 22109 22110 22111 22112 22113 22114 22115 22116 22117 22118 22119 22120 22121 22122 22123 22124 22125 22126 22127 22128 22129 22130 22131 22132 22133 22134 22135 22136 22137 22138 22139 22140 22141 22142 22143 22144 22145 22146 22147 22148 22149 22150 22151 22152 22153 22154 22155 22156 22157 22158 22159 22160 22161 22162 22163 22164 22165 22166 22167 22168 22169 22170 22171 22172 22173 22174 22175 22176 22177 22178 22179 22180 22181 22182 22183 22184 22185 22186 22187 22188 22189 22190 22191 22192 22193 22194 22195 22196 22197 22198 22199 22200 22201 22202 22203 22204 22205 22206 22207 22208 22209 22210 22211 22212 22213 22214 22215 22216 22217 22218 22219 22220 22221 22222 22223 22224 22225 22226 22227 22228 22229 22230 22231 22232 22233 22234 22235 22236 22237 22238 22239 22240 22241 22242 22243 22244 22245 22246 22247 22248 22249 22250 22251 22252 22253 22254 22255 22256 22257 22258 22259 22260 22261 22262 22263 22264 22265 22266 22267 22268 22269 22270 22271 22272 22273 22274 22275 22276 22277 22278 22279 22280 22281 22282 22283 22284 22285 22286 22287 22288 22289 22290 22291 22292 22293 22294 22295 22296 22297 22298 22299 22300 22301 22302 22303 22304 22305 22306 22307 22308 22309 22310 22311 22312 22313 22314 22315 22316 22317 22318 22319 22320 22321 22322 22323 22324 22325 22326 22327 22328 22329 22330 22331 22332 22333 22334 22335 22336 22337 22338 22339 22340 22341 22342 22343 22344 22345 22346 22347 22348 22349 22350 22351 22352 22353 22354 22355 22356 22357 22358 22359 22360 22361 22362 22363 22364 22365 22366 22367 22368 22369 22370 22371 22372 22373 22374 22375 22376 22377 22378 22379 22380 22381 22382 22383 22384 22385 22386 22387 22388 22389 22390 22391 22392 22393 22394 22395 22396 22397 22398 22399 22400 22401 22402 22403 22404 22405 22406 22407 22408 22409 22410 22411 22412 22413 22414 22415 22416 22417 22418 22419 22420 22421 22422 22423 22424 22425 22426 22427 22428 22429 22430 22431 22432 22433 22434 22435 22436 22437 22438 22439 22440 22441 22442 22443 22444 22445 22446 22447 22448 22449 22450 22451 22452 22453 22454 22455 22456 22457 22458 22459 22460 22461 22462 22463 22464 22465 22466 22467 22468 22469 22470 22471 22472 22473 22474 22475 22476 22477 22478 22479 22480 22481 22482 22483 22484 22485 22486 22487 22488 22489 22490 22491 22492 22493 22494 22495 22496 22497 22498 22499 22500 22501 22502 22503 22504 22505 22506 22507 22508 22509 22510 22511 22512 22513 22514 22515 22516 22517 22518 22519 22520 22521 22522 22523 22524 22525 22526 22527 22528 22529 22530 22531 22532 22533 22534 22535 22536 22537 22538 22539 22540 22541 22542 22543 22544 22545 22546 22547 22548 22549 22550 22551 22552 22553 22554 22555 22556 22557 22558 22559 22560 22561 22562 22563 22564 22565 22566 22567 22568 22569 22570 22571 22572 22573 22574 22575 22576 22577 22578 22579 22580 22581 22582 22583 22584 22585 22586 22587 22588 22589 22590 22591 22592 22593 22594 22595 22596 22597 22598 22599 22600 22601 22602 22603 22604 22605 22606 22607 22608 22609 22610 22611 22612 22613 22614 22615 22616 22617 22618 22619 22620 22621 22622 22623 22624 22625 22626 22627 22628 22629 22630 22631 22632 22633 22634 22635 22636 22637 22638 22639 22640 22641 22642 22643 22644 22645 22646 22647 22648 22649 22650 22651 22652 22653 22654 22655 22656 22657 22658 22659 22660 22661 22662 22663 22664 22665 22666 22667 22668 22669 22670 22671 22672 22673 22674 22675 22676 22677 22678 22679 22680 22681 22682 22683 22684 22685 22686 22687 22688 22689 22690 22691 22692 22693 22694 22695 22696 22697 22698 22699 22700 22701 22702 22703 22704 22705 22706 22707 22708 22709 22710 22711 22712 22713 22714 22715 22716 22717 22718 22719 22720 22721 22722 22723 22724 22725 22726 22727 22728 22729 22730 22731 22732 22733 22734 22735 22736 22737 22738 22739 22740 22741 22742 22743 22744 22745 22746 22747 22748 22749 22750 22751 22752 22753 22754 22755 22756 22757 22758 22759 22760 22761 22762 22763 22764 22765 22766 22767 22768 22769 22770 22771 22772 22773 22774 22775 22776 22777 22778 22779 22780 22781 22782 22783 22784 22785 22786 22787 22788 22789 22790 22791 22792 22793 22794 22795 22796 22797 22798 22799 22800 22801 22802 22803 22804 22805 22806 22807 22808 22809 22810 22811 22812 22813 22814 22815 22816 22817 22818 22819 22820 22821 22822 22823 22824 22825 22826 22827 22828 22829 22830 22831 22832 22833 22834 22835 22836 22837 22838 22839 22840 22841 22842 22843 22844 22845 22846 22847 22848 22849 22850 22851 22852 22853 22854 22855 22856 22857 22858 22859 22860 22861 22862 22863 22864 22865 22866 22867 22868 22869 22870 22871 22872 22873 22874 22875 22876 22877 22878 22879 22880 22881 22882 22883 22884 22885 22886 22887 22888 22889 22890 22891 22892 22893 22894 22895 22896 22897 22898 22899 22900 22901 22902 22903 22904 22905 22906 22907 22908 22909 22910 22911 22912 22913 22914 22915 22916 22917 22918 22919 22920 22921 22922 22923 22924 22925 22926 22927 22928 22929 22930 22931 22932 22933 22934 22935 22936 22937 22938 22939 22940 22941 22942 22943 22944 22945 22946 22947 22948 22949 22950 22951 22952 22953 22954 22955 22956 22957 22958 22959 22960 22961 22962 22963 22964 22965 22966 22967 22968 22969 22970 22971 22972 22973 22974 22975 22976 22977 22978 22979 22980 22981 22982 22983 22984 22985 22986 22987 22988 22989 22990 22991 22992 22993 22994 22995 22996 22997 22998 22999 23000 23001 23002 23003 23004 23005 23006 23007 23008 23009 23010 23011 23012 23013 23014 23015 23016 23017 23018 23019 23020 23021 23022 23023 23024 23025 23026 23027 23028 23029 23030 23031 23032 23033 23034 23035 23036 23037 23038 23039 23040 23041 23042 23043 23044 23045 23046 23047 23048 23049 23050 23051 23052 23053 23054 23055 23056 23057 23058 23059 23060 23061 23062 23063 23064 23065 23066 23067 23068 23069 23070 23071 23072 23073 23074 23075 23076 23077 23078 23079 23080 23081 23082 23083 23084 23085 23086 23087 23088 23089 23090 23091 23092 23093 23094 23095 23096 23097 23098 23099 23100 23101 23102 23103 23104 23105 23106 23107 23108 23109 23110 23111 23112 23113 23114 23115 23116 23117 23118 23119 23120 23121 23122 23123 23124 23125 23126 23127 23128 23129 23130 23131 23132 23133 23134 23135 23136 23137 23138 23139 23140 23141 23142 23143 23144 23145 23146 23147 23148 23149 23150 23151 23152 23153 23154 23155 23156 23157 23158 23159 23160 23161 23162 23163 23164 23165 23166 23167 23168 23169 23170 23171 23172 23173 23174 23175 23176 23177 23178 23179 23180 23181 23182 23183 23184 23185 23186 23187 23188 23189 23190 23191 23192 23193 23194 23195 23196 23197 23198 23199 23200 23201 23202 23203 23204 23205 23206 23207 23208 23209 23210 23211 23212 23213 23214 23215 23216 23217 23218 23219 23220 23221 23222 23223 23224 23225 23226 23227 23228 23229 23230 23231 23232 23233 23234 23235 23236 23237 23238 23239 23240 23241 23242 23243 23244 23245 23246 23247 23248 23249 23250 23251 23252 23253 23254 23255 23256 23257 23258 23259 23260 23261 23262 23263 23264 23265 23266 23267 23268 23269 23270 23271 23272 23273 23274 23275 23276 23277 23278 23279 23280 23281 23282 23283 23284 23285 23286 23287 23288 23289 23290 23291 23292 23293 23294 23295 23296 23297 23298 23299 23300 23301 23302 23303 23304 23305 23306 23307 23308 23309 23310 23311 23312 23313 23314 23315 23316 23317 23318 23319 23320 23321 23322 23323 23324 23325 23326 23327 23328 23329 23330 23331 23332 23333 23334 23335 23336 23337 23338 23339 23340 23341 23342 23343 23344 23345 23346 23347 23348 23349 23350 23351 23352 23353 23354 23355 23356 23357 23358 23359 23360 23361 23362 23363 23364 23365 23366 23367 23368 23369 23370 23371 23372 23373 23374 23375 23376 23377 23378 23379 23380 23381 23382 23383 23384 23385 23386 23387 23388 23389 23390 23391 23392 23393 23394 23395 23396 23397 23398 23399 23400 23401 23402 23403 23404 23405 23406 23407 23408 23409 23410 23411 23412 23413 23414 23415 23416 23417 23418 23419 23420 23421 23422 23423 23424 23425 23426 23427 23428 23429 23430 23431 23432 23433 23434 23435 23436 23437 23438 23439 23440 23441 23442 23443 23444 23445 23446 23447 23448 23449 23450 23451 23452 23453 23454 23455 23456 23457 23458 23459 23460 23461 23462 23463 23464 23465 23466 23467 23468 23469 23470 23471 23472 23473 23474 23475 23476 23477 23478 23479 23480 23481 23482 23483 23484 23485 23486 23487 23488 23489 23490 23491 23492 23493 23494 23495 23496 23497 23498 23499 23500 23501 23502 23503 23504 23505 23506 23507 23508 23509 23510 23511 23512 23513 23514 23515 23516 23517 23518 23519 23520 23521 23522 23523 23524 23525 23526 23527 23528 23529 23530 23531 23532 23533 23534 23535 23536 23537 23538 23539 23540 23541 23542 23543 23544 23545 23546 23547 23548 23549 23550 23551 23552 23553 23554 23555 23556 23557 23558 23559 23560 23561 23562 23563 23564 23565 23566 23567 23568 23569 23570 23571 23572 23573 23574 23575 23576 23577 23578 23579 23580 23581 23582 23583 23584 23585 23586 23587 23588 23589 23590 23591 23592 23593 23594 23595 23596 23597 23598 23599 23600 23601 23602 23603 23604 23605 23606 23607 23608 23609 23610 23611 23612 23613 23614 23615 23616 23617 23618 23619 23620 23621 23622 23623 23624 23625 23626 23627 23628 23629 23630 23631 23632 23633 23634 23635 23636 23637 23638 23639 23640 23641 23642 23643 23644 23645 23646 23647 23648 23649 23650 23651 23652 23653 23654 23655 23656 23657 23658 23659 23660 23661 23662 23663 23664 23665 23666 23667 23668 23669 23670 23671 23672 23673 23674 23675 23676 23677 23678 23679 23680 23681 23682 23683 23684 23685 23686 23687 23688 23689 23690 23691 23692 23693 23694 23695 23696 23697 23698 23699 23700 23701 23702 23703 23704 23705 23706 23707 23708 23709 23710 23711 23712 23713 23714 23715 23716 23717 23718 23719 23720 23721 23722 23723 23724 23725 23726 23727 23728 23729 23730 23731 23732 23733 23734 23735 23736 23737 23738 23739 23740 23741 23742 23743 23744 23745 23746 23747 23748 23749 23750 23751 23752 23753 23754 23755 23756 23757 23758 23759 23760 23761 23762 23763 23764 23765 23766 23767 23768 23769 23770 23771 23772 23773 23774 23775 23776 23777 23778 23779 23780 23781 23782 23783 23784 23785 23786 23787 23788 23789 23790 23791 23792 23793 23794 23795 23796 23797 23798 23799 23800 23801 23802 23803 23804 23805 23806 23807 23808 23809 23810 23811 23812 23813 23814 23815 23816 23817 23818 23819 23820 23821 23822 23823 23824 23825 23826 23827 23828 23829 23830 23831 23832 23833 23834 23835 23836 23837 23838 23839 23840 23841 23842 23843 23844 23845 23846 23847 23848 23849 23850 23851 23852 23853 23854 23855 23856 23857 23858 23859 23860 23861 23862 23863 23864 23865 23866 23867 23868 23869 23870 23871 23872 23873 23874 23875 23876 23877 23878 23879 23880 23881 23882 23883 23884 23885 23886 23887 23888 23889 23890 23891 23892 23893 23894 23895 23896 23897 23898 23899 23900 23901 23902 23903 23904 23905 23906 23907 23908 23909 23910 23911 23912 23913 23914 23915 23916 23917 23918 23919 23920 23921 23922 23923 23924 23925 23926 23927 23928 23929 23930 23931 23932 23933 23934 23935 23936 23937 23938 23939 23940 23941 23942 23943 23944 23945 23946 23947 23948 23949 23950 23951 23952 23953 23954 23955 23956 23957 23958 23959 23960 23961 23962 23963 23964 23965 23966 23967 23968 23969 23970 23971 23972 23973 23974 23975 23976 23977 23978 23979 23980 23981 23982 23983 23984 23985 23986 23987 23988 23989 23990 23991 23992 23993 23994 23995 23996 23997 23998 23999 24000 24001 24002 24003 24004 24005 24006 24007 24008 24009 24010 24011 24012 24013 24014 24015 24016 24017 24018 24019 24020 24021 24022 24023 24024 24025 24026 24027 24028 24029 24030 24031 24032 24033 24034 24035 24036 24037 24038 24039 24040 24041 24042 24043 24044 24045 24046 24047 24048 24049 24050 24051 24052 24053 24054 24055 24056 24057 24058 24059 24060 24061 24062 24063 24064 24065 24066 24067 24068 24069 24070 24071 24072 24073 24074 24075 24076 24077 24078 24079 24080 24081 24082 24083 24084 24085 24086 24087 24088 24089 24090 24091 24092 24093 24094 24095 24096 24097 24098 24099 24100 24101 24102 24103 24104 24105 24106 24107 24108 24109 24110 24111 24112 24113 24114 24115 24116 24117 24118 24119 24120 24121 24122 24123 24124 24125 24126 24127 24128 24129 24130 24131 24132 24133 24134 24135 24136 24137 24138 24139 24140 24141 24142 24143 24144 24145 24146 24147 24148 24149 24150 24151 24152 24153 24154 24155 24156 24157 24158 24159 24160 24161 24162 24163 24164 24165 24166 24167 24168 24169 24170 24171 24172 24173 24174 24175 24176 24177 24178 24179 24180 24181 24182 24183 24184 24185 24186 24187 24188 24189 24190 24191 24192 24193 24194 24195 24196 24197 24198 24199 24200 24201 24202 24203 24204 24205 24206 24207 24208 24209 24210 24211 24212 24213 24214 24215 24216 24217 24218 24219 24220 24221 24222 24223 24224 24225 24226 24227 24228 24229 24230 24231 24232 24233 24234 24235 24236 24237 24238 24239 24240 24241 24242 24243 24244 24245 24246 24247 24248 24249 24250 24251 24252 24253 24254 24255 24256 24257 24258 24259 24260 24261 24262 24263 24264 24265 24266 24267 24268 24269 24270 24271 24272 24273 24274 24275 24276 24277 24278 24279 24280 24281 24282 24283 24284 24285 24286 24287 24288 24289 24290 24291 24292 24293 24294 24295 24296 24297 24298 24299 24300 24301 24302 24303 24304 24305 24306 24307 24308 24309 24310 24311 24312 24313 24314 24315 24316 24317 24318 24319 24320 24321 24322 24323 24324 24325 24326 24327 24328 24329 24330 24331 24332 24333 24334 24335 24336 24337 24338 24339 24340 24341 24342 24343 24344 24345 24346 24347 24348 24349 24350 24351 24352 24353 24354 24355 24356 24357 24358 24359 24360 24361 24362 24363 24364 24365 24366 24367 24368 24369 24370 24371 24372 24373 24374 24375 24376 24377 24378 24379 24380 24381 24382 24383 24384 24385 24386 24387 24388 24389 24390 24391 24392 24393 24394 24395 24396 24397 24398 24399 24400 24401 24402 24403 24404 24405 24406 24407 24408 24409 24410 24411 24412 24413 24414 24415 24416 24417 24418 24419 24420 24421 24422 24423 24424 24425 24426 24427 24428 24429 24430 24431 24432 24433 24434 24435 24436 24437 24438 24439 24440 24441 24442 24443 24444 24445 24446 24447 24448 24449 24450 24451 24452 24453 24454 24455 24456 24457 24458 24459 24460 24461 24462 24463 24464 24465 24466 24467 24468 24469 24470 24471 24472 24473 24474 24475 24476 24477 24478 24479 24480 24481 24482 24483 24484 24485 24486 24487 24488 24489 24490 24491 24492 24493 24494 24495 24496 24497 24498 24499 24500 24501 24502 24503 24504 24505 24506 24507 24508 24509 24510 24511 24512 24513 24514 24515 24516 24517 24518 24519 24520 24521 24522 24523 24524 24525 24526 24527 24528 24529 24530 24531 24532 24533 24534 24535 24536 24537 24538 24539 24540 24541 24542 24543 24544 24545 24546 24547 24548 24549 24550 24551 24552 24553 24554 24555 24556 24557 24558 24559 24560 24561 24562 24563 24564 24565 24566 24567 24568 24569 24570 24571 24572 24573 24574 24575 24576 24577 24578 24579 24580 24581 24582 24583 24584 24585 24586 24587 24588 24589 24590 24591 24592 24593 24594 24595 24596 24597 24598 24599 24600 24601 24602 24603 24604 24605 24606 24607 24608 24609 24610 24611 24612 24613 24614 24615 24616 24617 24618 24619 24620 24621 24622 24623 24624 24625 24626 24627 24628 24629 24630 24631 24632 24633 24634 24635 24636 24637 24638 24639 24640 24641 24642 24643 24644 24645 24646 24647 24648 24649 24650 24651 24652 24653 24654 24655 24656 24657 24658 24659 24660 24661 24662 24663 24664 24665 24666 24667 24668 24669 24670 24671 24672 24673 24674 24675 24676 24677 24678 24679 24680 24681 24682 24683 24684 24685 24686 24687 24688 24689 24690 24691 24692 24693 24694 24695 24696 24697 24698 24699 24700 24701 24702 24703 24704 24705 24706 24707 24708 24709 24710 24711 24712 24713 24714 24715 24716 24717 24718 24719 24720 24721 24722 24723 24724 24725 24726 24727 24728 24729 24730 24731 24732 24733 24734 24735 24736 24737 24738 24739 24740 24741 24742 24743 24744 24745 24746 24747 24748 24749 24750 24751 24752 24753 24754 24755 24756 24757 24758 24759 24760 24761 24762 24763 24764 24765 24766 24767 24768 24769 24770 24771 24772 24773 24774 24775 24776 24777 24778 24779 24780 24781 24782 24783 24784 24785 24786 24787 24788 24789 24790 24791 24792 24793 24794 24795 24796 24797 24798 24799 24800 24801 24802 24803 24804 24805 24806 24807 24808 24809 24810 24811 24812 24813 24814 24815 24816 24817 24818 24819 24820 24821 24822 24823 24824 24825 24826 24827 24828 24829 24830 24831 24832 24833 24834 24835 24836 24837 24838 24839 24840 24841 24842 24843 24844 24845 24846 24847 24848 24849 24850 24851 24852 24853 24854 24855 24856 24857 24858 24859 24860 24861 24862 24863 24864 24865 24866 24867 24868 24869 24870 24871 24872 24873 24874 24875 24876 24877 24878 24879 24880 24881 24882 24883 24884 24885 24886 24887 24888 24889 24890 24891 24892 24893 24894 24895 24896 24897 24898 24899 24900 24901 24902 24903 24904 24905 24906 24907 24908 24909 24910 24911 24912 24913 24914 24915 24916 24917 24918 24919 24920 24921 24922 24923 24924 24925 24926 24927 24928 24929 24930 24931 24932 24933 24934 24935 24936 24937 24938 24939 24940 24941 24942 24943 24944 24945 24946 24947 24948 24949 24950 24951 24952 24953 24954 24955 24956 24957 24958 24959 24960 24961 24962 24963 24964 24965 24966 24967 24968 24969 24970 24971 24972 24973 24974 24975 24976 24977 24978 24979 24980 24981 24982 24983 24984 24985 24986 24987 24988 24989 24990 24991 24992 24993 24994 24995 24996 24997 24998 24999 25000 25001 25002 25003 25004 25005 25006 25007 25008 25009 25010 25011 25012 25013 25014 25015 25016 25017 25018 25019 25020 25021 25022 25023 25024 25025 25026 25027 25028 25029 25030 25031 25032 25033 25034 25035 25036 25037 25038 25039 25040 25041 25042 25043 25044 25045 25046 25047 25048 25049 25050 25051 25052 25053 25054 25055 25056 25057 25058 25059 25060 25061 25062 25063 25064 25065 25066 25067 25068 25069 25070 25071 25072 25073 25074 25075 25076 25077 25078 25079 25080 25081 25082 25083 25084 25085 25086 25087 25088 25089 25090 25091 25092 25093 25094 25095 25096 25097 25098 25099 25100 25101 25102 25103 25104 25105 25106 25107 25108 25109 25110 25111 25112 25113 25114 25115 25116 25117 25118 25119 25120 25121 25122 25123 25124 25125 25126 25127 25128 25129 25130 25131 25132 25133 25134 25135 25136 25137 25138 25139 25140 25141 25142 25143 25144 25145 25146 25147 25148 25149 25150 25151 25152 25153 25154 25155 25156 25157 25158 25159 25160 25161 25162 25163 25164 25165 25166 25167 25168 25169 25170 25171 25172 25173 25174 25175 25176 25177 25178 25179 25180 25181 25182 25183 25184 25185 25186 25187 25188 25189 25190 25191 25192 25193 25194 25195 25196 25197 25198 25199 25200 25201 25202 25203 25204 25205 25206 25207 25208 25209 25210 25211 25212 25213 25214 25215 25216 25217 25218 25219 25220 25221 25222 25223 25224 25225 25226 25227 25228 25229 25230 25231 25232 25233 25234 25235 25236 25237 25238 25239 25240 25241 25242 25243 25244 25245 25246 25247 25248 25249 25250 25251 25252 25253 25254 25255 25256 25257 25258 25259 25260 25261 25262 25263 25264 25265 25266 25267 25268 25269 25270 25271 25272 25273 25274 25275 25276 25277 25278 25279 25280 25281 25282 25283 25284 25285 25286 25287 25288 25289 25290 25291 25292 25293 25294 25295 25296 25297 25298 25299 25300 25301 25302 25303 25304 25305 25306 25307 25308 25309 25310 25311 25312 25313 25314 25315 25316 25317 25318 25319 25320 25321 25322 25323 25324 25325 25326 25327 25328 25329 25330 25331 25332 25333 25334 25335 25336 25337 25338 25339 25340 25341 25342 25343 25344 25345 25346 25347 25348 25349 25350 25351 25352 25353 25354 25355 25356 25357 25358 25359 25360 25361 25362 25363 25364 25365 25366 25367 25368 25369 25370 25371 25372 25373 25374 25375 25376 25377 25378 25379 25380 25381 25382 25383 25384 25385 25386 25387 25388 25389 25390 25391 25392 25393 25394 25395 25396 25397 25398 25399 25400 25401 25402 25403 25404 25405 25406 25407 25408 25409 25410 25411 25412 25413 25414 25415 25416 25417 25418 25419 25420 25421 25422 25423 25424 25425 25426 25427 25428 25429 25430 25431 25432 25433 25434 25435 25436 25437 25438 25439 25440 25441 25442 25443 25444 25445 25446 25447 25448 25449 25450 25451 25452 25453 25454 25455 25456 25457 25458 25459 25460 25461 25462 25463 25464 25465 25466 25467 25468 25469 25470 25471 25472 25473 25474 25475 25476 25477 25478 25479 25480 25481 25482 25483 25484 25485 25486 25487 25488 25489 25490 25491 25492 25493 25494 25495 25496 25497 25498 25499 25500 25501 25502 25503 25504 25505 25506 25507 25508 25509 25510 25511 25512 25513 25514 25515 25516 25517 25518 25519 25520 25521 25522 25523 25524 25525 25526 25527 25528 25529 25530 25531 25532 25533 25534 25535 25536 25537 25538 25539 25540 25541 25542 25543 25544 25545 25546 25547 25548 25549 25550 25551 25552 25553 25554 25555 25556 25557 25558 25559 25560 25561 25562 25563 25564 25565 25566 25567 25568 25569 25570 25571 25572 25573 25574 25575 25576 25577 25578 25579 25580 25581 25582 25583 25584 25585 25586 25587 25588 25589 25590 25591 25592 25593 25594 25595 25596 25597 25598 25599 25600 25601 25602 25603 25604 25605 25606 25607 25608 25609 25610 25611 25612 25613 25614 25615 25616 25617 25618 25619 25620 25621 25622 25623 25624 25625 25626 25627 25628 25629 25630 25631 25632 25633 25634 25635 25636 25637 25638 25639 25640 25641 25642 25643 25644 25645 25646 25647 25648 25649 25650 25651 25652 25653 25654 25655 25656 25657 25658 25659 25660 25661 25662 25663 25664 25665 25666 25667 25668 25669 25670 25671 25672 25673 25674 25675 25676 25677 25678 25679 25680 25681 25682 25683 25684 25685 25686 25687 25688 25689 25690 25691 25692 25693 25694 25695 25696 25697 25698 25699 25700 25701 25702 25703 25704 25705 25706 25707 25708 25709 25710 25711 25712 25713 25714 25715 25716 25717 25718 25719 25720 25721 25722 25723 25724 25725 25726 25727 25728 25729 25730 25731 25732 25733 25734 25735 25736 25737 25738 25739 25740 25741 25742 25743 25744 25745 25746 25747 25748 25749 25750 25751 25752 25753 25754 25755 25756 25757 25758 25759 25760 25761 25762 25763 25764 25765 25766 25767 25768 25769 25770 25771 25772 25773 25774 25775 25776 25777 25778 25779 25780 25781 25782 25783 25784 25785 25786 25787 25788 25789 25790 25791 25792 25793 25794 25795 25796 25797 25798 25799 25800 25801 25802 25803 25804 25805 25806 25807 25808 25809 25810 25811 25812 25813 25814 25815 25816 25817 25818 25819 25820 25821 25822 25823 25824 25825 25826 25827 25828 25829 25830 25831 25832 25833 25834 25835 25836 25837 25838 25839 25840 25841 25842 25843 25844 25845 25846 25847 25848 25849 25850 25851 25852 25853 25854 25855 25856 25857 25858 25859 25860 25861 25862 25863 25864 25865 25866 25867 25868 25869 25870 25871 25872 25873 25874 25875 25876 25877 25878 25879 25880 25881 25882 25883 25884 25885 25886 25887 25888 25889 25890 25891 25892 25893 25894 25895 25896 25897 25898 25899 25900 25901 25902 25903 25904 25905 25906 25907 25908 25909 25910 25911 25912 25913 25914 25915 25916 25917 25918 25919 25920 25921 25922 25923 25924 25925 25926 25927 25928 25929 25930 25931 25932 25933 25934 25935 25936 25937 25938 25939 25940 25941 25942 25943 25944 25945 25946 25947 25948 25949 25950 25951 25952 25953 25954 25955 25956 25957 25958 25959 25960 25961 25962 25963 25964 25965 25966 25967 25968 25969 25970 25971 25972 25973 25974 25975 25976 25977 25978 25979 25980 25981 25982 25983 25984 25985 25986 25987 25988 25989 25990 25991 25992 25993 25994 25995 25996 25997 25998 25999 26000 26001 26002 26003 26004 26005 26006 26007 26008 26009 26010 26011 26012 26013 26014 26015 26016 26017 26018 26019 26020 26021 26022 26023 26024 26025 26026 26027 26028 26029 26030 26031 26032 26033 26034 26035 26036 26037 26038 26039 26040 26041 26042 26043 26044 26045 26046 26047 26048 26049 26050 26051 26052 26053 26054 26055 26056 26057 26058 26059 26060 26061 26062 26063 26064 26065 26066 26067 26068 26069 26070 26071 26072 26073 26074 26075 26076 26077 26078 26079 26080 26081 26082 26083 26084 26085 26086 26087 26088 26089 26090 26091 26092 26093 26094 26095 26096 26097 26098 26099 26100 26101 26102 26103 26104 26105 26106 26107 26108 26109 26110 26111 26112 26113 26114 26115 26116 26117 26118 26119 26120 26121 26122 26123 26124 26125 26126 26127 26128 26129 26130 26131 26132 26133 26134 26135 26136 26137 26138 26139 26140 26141 26142 26143 26144 26145 26146 26147 26148 26149 26150 26151 26152 26153 26154 26155 26156 26157 26158 26159 26160 26161 26162 26163 26164 26165 26166 26167 26168 26169 26170 26171 26172 26173 26174 26175 26176 26177 26178 26179 26180 26181 26182 26183 26184 26185 26186 26187 26188 26189 26190 26191 26192 26193 26194 26195 26196 26197 26198 26199 26200 26201 26202 26203 26204 26205 26206 26207 26208 26209 26210 26211 26212 26213 26214 26215 26216 26217 26218 26219 26220 26221 26222 26223 26224 26225 26226 26227 26228 26229 26230 26231 26232 26233 26234 26235 26236 26237 26238 26239 26240 26241 26242 26243 26244 26245 26246 26247 26248 26249 26250 26251 26252 26253 26254 26255 26256 26257 26258 26259 26260 26261 26262 26263 26264 26265 26266 26267 26268 26269 26270 26271 26272 26273 26274 26275 26276 26277 26278 26279 26280 26281 26282 26283 26284 26285 26286 26287 26288 26289 26290 26291 26292 26293 26294 26295 26296 26297 26298 26299 26300 26301 26302 26303 26304 26305 26306 26307 26308 26309 26310 26311 26312 26313 26314 26315 26316 26317 26318 26319 26320 26321 26322 26323 26324 26325 26326 26327 26328 26329 26330 26331 26332 26333 26334 26335 26336 26337 26338 26339 26340 26341 26342 26343 26344 26345 26346 26347 26348 26349 26350 26351 26352 26353 26354 26355 26356 26357 26358 26359 26360 26361 26362 26363 26364 26365 26366 26367 26368 26369 26370 26371 26372 26373 26374 26375 26376 26377 26378 26379 26380 26381 26382 26383 26384 26385 26386 26387 26388 26389 26390 26391 26392 26393 26394 26395 26396 26397 26398 26399 26400 26401 26402 26403 26404 26405 26406 26407 26408 26409 26410 26411 26412 26413 26414 26415 26416 26417 26418 26419 26420 26421 26422 26423 26424 26425 26426 26427 26428 26429 26430 26431 26432 26433 26434 26435 26436 26437 26438 26439 26440 26441 26442 26443 26444 26445 26446 26447 26448 26449 26450 26451 26452 26453 26454 26455 26456 26457 26458 26459 26460 26461 26462 26463 26464 26465 26466 26467 26468 26469 26470 26471 26472 26473 26474 26475 26476 26477 26478 26479 26480 26481 26482 26483 26484 26485 26486 26487 26488 26489 26490 26491 26492 26493 26494 26495 26496 26497 26498 26499 26500 26501 26502 26503 26504 26505 26506 26507 26508 26509 26510 26511 26512 26513 26514 26515 26516 26517 26518 26519 26520 26521 26522 26523 26524 26525 26526 26527 26528 26529 26530 26531 26532 26533 26534 26535 26536 26537 26538 26539 26540 26541 26542 26543 26544 26545 26546 26547 26548 26549 26550 26551 26552 26553 26554 26555 26556 26557 26558 26559 26560 26561 26562 26563 26564 26565 26566 26567 26568 26569 26570 26571 26572 26573 26574 26575 26576 26577 26578 26579 26580 26581 26582 26583 26584 26585 26586 26587 26588 26589 26590 26591 26592 26593 26594 26595 26596 26597 26598 26599 26600 26601 26602 26603 26604 26605 26606 26607 26608 26609 26610 26611 26612 26613 26614 26615 26616 26617 26618 26619 26620 26621 26622 26623 26624 26625 26626 26627 26628 26629 26630 26631 26632 26633 26634 26635 26636 26637 26638 26639 26640 26641 26642 26643 26644 26645 26646 26647 26648 26649 26650 26651 26652 26653 26654 26655 26656 26657 26658 26659 26660 26661 26662 26663 26664 26665 26666 26667 26668 26669 26670 26671 26672 26673 26674 26675 26676 26677 26678 26679 26680 26681 26682 26683 26684 26685 26686 26687 26688 26689 26690 26691 26692 26693 26694 26695 26696 26697 26698 26699 26700 26701 26702 26703 26704 26705 26706 26707 26708 26709 26710 26711 26712 26713 26714 26715 26716 26717 26718 26719 26720 26721 26722 26723 26724 26725 26726 26727 26728 26729 26730 26731 26732 26733 26734 26735 26736 26737 26738 26739 26740 26741 26742 26743 26744 26745 26746 26747 26748 26749 26750 26751 26752 26753 26754 26755 26756 26757 26758 26759 26760 26761 26762 26763 26764 26765 26766 26767 26768 26769 26770 26771 26772 26773 26774 26775 26776 26777 26778 26779 26780 26781 26782 26783 26784 26785 26786 26787 26788 26789 26790 26791 26792 26793 26794 26795 26796 26797 26798 26799 26800 26801 26802 26803 26804 26805 26806 26807 26808 26809 26810 26811 26812 26813 26814 26815 26816 26817 26818 26819 26820 26821 26822 26823 26824 26825 26826 26827 26828 26829 26830 26831 26832 26833 26834 26835 26836 26837 26838 26839 26840 26841 26842 26843 26844 26845 26846 26847 26848 26849 26850 26851 26852 26853 26854 26855 26856 26857 26858 26859 26860 26861 26862 26863 26864 26865 26866 26867 26868 26869 26870 26871 26872 26873 26874 26875 26876 26877 26878 26879 26880 26881 26882 26883 26884 26885 26886 26887 26888 26889 26890 26891 26892 26893 26894 26895 26896 26897 26898 26899 26900 26901 26902 26903 26904 26905 26906 26907 26908 26909 26910 26911 26912 26913 26914 26915 26916 26917 26918 26919 26920 26921 26922 26923 26924 26925 26926 26927 26928 26929 26930 26931 26932 26933 26934 26935 26936 26937 26938 26939 26940 26941 26942 26943 26944 26945 26946 26947 26948 26949 26950 26951 26952 26953 26954 26955 26956 26957 26958 26959 26960 26961 26962 26963 26964 26965 26966 26967 26968 26969 26970 26971 26972 26973 26974 26975 26976 26977 26978 26979 26980 26981 26982 26983 26984 26985 26986 26987 26988 26989 26990 26991 26992 26993 26994 26995 26996 26997 26998 26999 27000 27001 27002 27003 27004 27005 27006 27007 27008 27009 27010 27011 27012 27013 27014 27015 27016 27017 27018 27019 27020 27021 27022 27023 27024 27025 27026 27027 27028 27029 27030 27031 27032 27033 27034 27035 27036 27037 27038 27039 27040 27041 27042 27043 27044 27045 27046 27047 27048 27049 27050 27051 27052 27053 27054 27055 27056 27057 27058 27059 27060 27061 27062 27063 27064 27065 27066 27067 27068 27069 27070 27071 27072 27073 27074 27075 27076 27077 27078 27079 27080 27081 27082 27083 27084 27085 27086 27087 27088 27089 27090 27091 27092 27093 27094 27095 27096 27097 27098 27099 27100 27101 27102 27103 27104 27105 27106 27107 27108 27109 27110 27111 27112 27113 27114 27115 27116 27117 27118 27119 27120 27121 27122 27123 27124 27125 27126 27127 27128 27129 27130 27131 27132 27133 27134 27135 27136 27137 27138 27139 27140 27141 27142 27143 27144 27145 27146 27147 27148 27149 27150 27151 27152 27153 27154 27155 27156 27157 27158 27159 27160 27161 27162 27163 27164 27165 27166 27167 27168 27169 27170 27171 27172 27173 27174 27175 27176 27177 27178 27179 27180 27181 27182 27183 27184 27185 27186 27187 27188 27189 27190 27191 27192 27193 27194 27195 27196 27197 27198 27199 27200 27201 27202 27203 27204 27205 27206 27207 27208 27209 27210 27211 27212 27213 27214 27215 27216 27217 27218 27219 27220 27221 27222 27223 27224 27225 27226 27227 27228 27229 27230 27231 27232 27233 27234 27235 27236 27237 27238 27239 27240 27241 27242 27243 27244 27245 27246 27247 27248 27249 27250 27251 27252 27253 27254 27255 27256 27257 27258 27259 27260 27261 27262 27263 27264 27265 27266 27267 27268 27269 27270 27271 27272 27273 27274 27275 27276 27277 27278 27279 27280 27281 27282 27283 27284 27285 27286 27287 27288 27289 27290 27291 27292 27293 27294 27295 27296 27297 27298 27299 27300 27301 27302 27303 27304 27305 27306 27307 27308 27309 27310 27311 27312 27313 27314 27315 27316 27317 27318 27319 27320 27321 27322 27323 27324 27325 27326 27327 27328 27329 27330 27331 27332 27333 27334 27335 27336 27337 27338 27339 27340 27341 27342 27343 27344 27345 27346 27347 27348 27349 27350 27351 27352 27353 27354 27355 27356 27357 27358 27359 27360 27361 27362 27363 27364 27365 27366 27367 27368 27369 27370 27371 27372 27373 27374 27375 27376 27377 27378 27379 27380 27381 27382 27383 27384 27385 27386 27387 27388 27389 27390 27391 27392 27393 27394 27395 27396 27397 27398 27399 27400 27401 27402 27403 27404 27405 27406 27407 27408 27409 27410 27411 27412 27413 27414 27415 27416 27417 27418 27419 27420 27421 27422 27423 27424 27425 27426 27427 27428 27429 27430 27431 27432 27433 27434 27435 27436 27437 27438 27439 27440 27441 27442 27443 27444 27445 27446 27447 27448 27449 27450 27451 27452 27453 27454 27455 27456 27457 27458 27459 27460 27461 27462 27463 27464 27465 27466 27467 27468 27469 27470 27471 27472 27473 27474 27475 27476 27477 27478 27479 27480 27481 27482 27483 27484 27485 27486 27487 27488 27489 27490 27491 27492 27493 27494 27495 27496 27497 27498 27499 27500 27501 27502 27503 27504 27505 27506 27507 27508 27509 27510 27511 27512 27513 27514 27515 27516 27517 27518 27519 27520 27521 27522 27523 27524 27525 27526 27527 27528 27529 27530 27531 27532 27533 27534 27535 27536 27537 27538 27539 27540 27541 27542 27543 27544 27545 27546 27547 27548 27549 27550 27551 27552 27553 27554 27555 27556 27557 27558 27559 27560 27561 27562 27563 27564 27565 27566 27567 27568 27569 27570 27571 27572 27573 27574 27575 27576 27577 27578 27579 27580 27581 27582 27583 27584 27585 27586 27587 27588 27589 27590 27591 27592 27593 27594 27595 27596 27597 27598 27599 27600 27601 27602 27603 27604 27605 27606 27607 27608 27609 27610 27611 27612 27613 27614 27615 27616 27617 27618 27619 27620 27621 27622 27623 27624 27625 27626 27627 27628 27629 27630 27631 27632 27633 27634 27635 27636 27637 27638 27639 27640 27641 27642 27643 27644 27645 27646 27647 27648 27649 27650 27651 27652 27653 27654 27655 27656 27657 27658 27659 27660 27661 27662 27663 27664 27665 27666 27667 27668 27669 27670 27671 27672 27673 27674 27675 27676 27677 27678 27679 27680 27681 27682 27683 27684 27685 27686 27687 27688 27689 27690 27691 27692 27693 27694 27695 27696 27697 27698 27699 27700 27701 27702 27703 27704 27705 27706 27707 27708 27709 27710 27711 27712 27713 27714 27715 27716 27717 27718 27719 27720 27721 27722 27723 27724 27725 27726 27727 27728 27729 27730 27731 27732 27733 27734 27735 27736 27737 27738 27739 27740 27741 27742 27743 27744 27745 27746 27747 27748 27749 27750 27751 27752 27753 27754 27755 27756 27757 27758 27759 27760 27761 27762 27763 27764 27765 27766 27767 27768 27769 27770 27771 27772 27773 27774 27775 27776 27777 27778 27779 27780 27781 27782 27783 27784 27785 27786 27787 27788 27789 27790 27791 27792 27793 27794 27795 27796 27797 27798 27799 27800 27801 27802 27803 27804 27805 27806 27807 27808 27809 27810 27811 27812 27813 27814 27815 27816 27817 27818 27819 27820 27821 27822 27823 27824 27825 27826 27827 27828 27829 27830 27831 27832 27833 27834 27835 27836 27837 27838 27839 27840 27841 27842 27843 27844 27845 27846 27847 27848 27849 27850 27851 27852 27853 27854 27855 27856 27857 27858 27859 27860 27861 27862 27863 27864 27865 27866 27867 27868 27869 27870 27871 27872 27873 27874 27875 27876 27877 27878 27879 27880 27881 27882 27883 27884 27885 27886 27887 27888 27889 27890 27891 27892 27893 27894 27895 27896 27897 27898 27899 27900 27901 27902 27903 27904 27905 27906 27907 27908 27909 27910 27911 27912 27913 27914 27915 27916 27917 27918 27919 27920 27921 27922 27923 27924 27925 27926 27927 27928 27929 27930 27931 27932 27933 27934 27935 27936 27937 27938 27939 27940 27941 27942 27943 27944 27945 27946 27947 27948 27949 27950 27951 27952 27953 27954 27955 27956 27957 27958 27959 27960 27961 27962 27963 27964 27965 27966 27967 27968 27969 27970 27971 27972 27973 27974 27975 27976 27977 27978 27979 27980 27981 27982 27983 27984 27985 27986 27987 27988 27989 27990 27991 27992 27993 27994 27995 27996 27997 27998 27999 28000 28001 28002 28003 28004 28005 28006 28007 28008 28009 28010 28011 28012 28013 28014 28015 28016 28017 28018 28019 28020 28021 28022 28023 28024 28025 28026 28027 28028 28029 28030 28031 28032 28033 28034 28035 28036 28037 28038 28039 28040 28041 28042 28043 28044 28045 28046 28047 28048 28049 28050 28051 28052 28053 28054 28055 28056 28057 28058 28059 28060 28061 28062 28063 28064 28065 28066 28067 28068 28069 28070 28071 28072 28073 28074 28075 28076 28077 28078 28079 28080 28081 28082 28083 28084 28085 28086 28087 28088 28089 28090 28091 28092 28093 28094 28095 28096 28097 28098 28099 28100 28101 28102 28103 28104 28105 28106 28107 28108 28109 28110 28111 28112 28113 28114 28115 28116 28117 28118 28119 28120 28121 28122 28123 28124 28125 28126 28127 28128 28129 28130 28131 28132 28133 28134 28135 28136 28137 28138 28139 28140 28141 28142 28143 28144 28145 28146 28147 28148 28149 28150 28151 28152 28153 28154 28155 28156 28157 28158 28159 28160 28161 28162 28163 28164 28165 28166 28167 28168 28169 28170 28171 28172 28173 28174 28175 28176 28177 28178 28179 28180 28181 28182 28183 28184 28185 28186 28187 28188 28189 28190 28191 28192 28193 28194 28195 28196 28197 28198 28199 28200 28201 28202 28203 28204 28205 28206 28207 28208 28209 28210 28211 28212 28213 28214 28215 28216 28217 28218 28219 28220 28221 28222 28223 28224 28225 28226 28227 28228 28229 28230 28231 28232 28233 28234 28235 28236 28237 28238 28239 28240 28241 28242 28243 28244 28245 28246 28247 28248 28249 28250 28251 28252 28253 28254 28255 28256 28257 28258 28259 28260 28261 28262 28263 28264 28265 28266 28267 28268 28269 28270 28271 28272 28273 28274 28275 28276 28277 28278 28279 28280 28281 28282 28283 28284 28285 28286 28287 28288 28289 28290 28291 28292 28293 28294 28295 28296 28297 28298 28299 28300 28301 28302 28303 28304 28305 28306 28307 28308 28309 28310 28311 28312 28313 28314 28315 28316 28317 28318 28319 28320 28321 28322 28323 28324 28325 28326 28327 28328 28329 28330 28331 28332 28333 28334 28335 28336 28337 28338 28339 28340 28341 28342 28343 28344 28345 28346 28347 28348 28349 28350 28351 28352 28353 28354 28355 28356 28357 28358 28359 28360 28361 28362 28363 28364 28365 28366 28367 28368 28369 28370 28371 28372 28373 28374 28375 28376 28377 28378 28379 28380 28381 28382 28383 28384 28385 28386 28387 28388 28389 28390 28391 28392 28393 28394 28395 28396 28397 28398 28399 28400 28401 28402 28403 28404 28405 28406 28407 28408 28409 28410 28411 28412 28413 28414 28415 28416 28417 28418 28419 28420 28421 28422 28423 28424 28425 28426 28427 28428 28429 28430 28431 28432 28433 28434 28435 28436 28437 28438 28439 28440 28441 28442 28443 28444 28445 28446 28447 28448 28449 28450 28451 28452 28453 28454 28455 28456 28457 28458 28459 28460 28461 28462 28463 28464 28465 28466 28467 28468 28469 28470 28471 28472 28473 28474 28475 28476 28477 28478 28479 28480 28481 28482 28483 28484 28485 28486 28487 28488 28489 28490 28491 28492 28493 28494 28495 28496 28497 28498 28499 28500 28501 28502 28503 28504 28505 28506 28507 28508 28509 28510 28511 28512 28513 28514 28515 28516 28517 28518 28519 28520 28521 28522 28523 28524 28525 28526 28527 28528 28529 28530 28531 28532 28533 28534 28535 28536 28537 28538 28539 28540 28541 28542 28543 28544 28545 28546 28547 28548 28549 28550 28551 28552 28553 28554 28555 28556 28557 28558 28559 28560 28561 28562 28563 28564 28565 28566 28567 28568 28569 28570 28571 28572 28573 28574 28575 28576 28577 28578 28579 28580 28581 28582 28583 28584 28585 28586 28587 28588 28589 28590 28591 28592 28593 28594 28595 28596 28597 28598 28599 28600 28601 28602 28603 28604 28605 28606 28607 28608 28609 28610 28611 28612 28613 28614 28615 28616 28617 28618 28619 28620 28621 28622 28623 28624 28625 28626 28627 28628 28629 28630 28631 28632 28633 28634 28635 28636 28637 28638 28639 28640 28641 28642 28643 28644 28645 28646 28647 28648 28649 28650 28651 28652 28653 28654 28655 28656 28657 28658 28659 28660 28661 28662 28663 28664 28665 28666 28667 28668 28669 28670 28671 28672 28673 28674 28675 28676 28677 28678 28679 28680 28681 28682 28683 28684 28685 28686 28687 28688 28689 28690 28691 28692 28693 28694 28695 28696 28697 28698 28699 28700 28701 28702 28703 28704 28705 28706 28707 28708 28709 28710 28711 28712 28713 28714 28715 28716 28717 28718 28719 28720 28721 28722 28723 28724 28725 28726 28727 28728 28729 28730 28731 28732 28733 28734 28735 28736 28737 28738 28739 28740 28741 28742 28743 28744 28745 28746 28747 28748 28749 28750 28751 28752 28753 28754 28755 28756 28757 28758 28759 28760 28761 28762 28763 28764 28765 28766 28767 28768 28769 28770 28771 28772 28773 28774 28775 28776 28777 28778 28779 28780 28781 28782 28783 28784 28785 28786 28787 28788 28789 28790 28791 28792 28793 28794 28795 28796 28797 28798 28799 28800 28801 28802 28803 28804 28805 28806 28807 28808 28809 28810 28811 28812 28813 28814 28815 28816 28817 28818 28819 28820 28821 28822 28823 28824 28825 28826 28827 28828 28829 28830 28831 28832 28833 28834 28835 28836 28837 28838 28839 28840 28841 28842 28843 28844 28845 28846 28847 28848 28849 28850 28851 28852 28853 28854 28855 28856 28857 28858 28859 28860 28861 28862 28863 28864 28865 28866 28867 28868 28869 28870 28871 28872 28873 28874 28875 28876 28877 28878 28879 28880 28881 28882 28883 28884 28885 28886 28887 28888 28889 28890 28891 28892 28893 28894 28895 28896 28897 28898 28899 28900 28901 28902 28903 28904 28905 28906 28907 28908 28909 28910 28911 28912 28913 28914 28915 28916 28917 28918 28919 28920 28921 28922 28923 28924 28925 28926 28927 28928 28929 28930 28931 28932 28933 28934 28935 28936 28937 28938 28939 28940 28941 28942 28943 28944 28945 28946 28947 28948 28949 28950 28951 28952 28953 28954 28955 28956 28957 28958 28959 28960 28961 28962 28963 28964 28965 28966 28967 28968 28969 28970 28971 28972 28973 28974 28975 28976 28977 28978 28979 28980 28981 28982 28983 28984 28985 28986 28987 28988 28989 28990 28991 28992 28993 28994 28995 28996 28997 28998 28999 29000 29001 29002 29003 29004 29005 29006 29007 29008 29009 29010 29011 29012 29013 29014 29015 29016 29017 29018 29019 29020 29021 29022 29023 29024 29025 29026 29027 29028 29029 29030 29031 29032 29033 29034 29035 29036 29037 29038 29039 29040 29041 29042 29043 29044 29045 29046 29047 29048 29049 29050 29051 29052 29053 29054 29055 29056 29057 29058 29059 29060 29061 29062 29063 29064 29065 29066 29067 29068 29069 29070 29071 29072 29073 29074 29075 29076 29077 29078 29079 29080 29081 29082 29083 29084 29085 29086 29087 29088 29089 29090 29091 29092 29093 29094 29095 29096 29097 29098 29099 29100 29101 29102 29103 29104 29105 29106 29107 29108 29109 29110 29111 29112 29113 29114 29115 29116 29117 29118 29119 29120 29121 29122 29123 29124 29125 29126 29127 29128 29129 29130 29131 29132 29133 29134 29135 29136 29137 29138 29139 29140 29141 29142 29143 29144 29145 29146 29147 29148 29149 29150 29151 29152 29153 29154 29155 29156 29157 29158 29159 29160 29161 29162 29163 29164 29165 29166 29167 29168 29169 29170 29171 29172 29173 29174 29175 29176 29177 29178 29179 29180 29181 29182 29183 29184 29185 29186 29187 29188 29189 29190 29191 29192 29193 29194 29195 29196 29197 29198 29199 29200 29201 29202 29203 29204 29205 29206 29207 29208 29209 29210 29211 29212 29213 29214 29215 29216 29217 29218 29219 29220 29221 29222 29223 29224 29225 29226 29227 29228 29229 29230 29231 29232 29233 29234 29235 29236 29237 29238 29239 29240 29241 29242 29243 29244 29245 29246 29247 29248 29249 29250 29251 29252 29253 29254 29255 29256 29257 29258 29259 29260 29261 29262 29263 29264 29265 29266 29267 29268 29269 29270 29271 29272 29273 29274 29275 29276 29277 29278 29279 29280 29281 29282 29283 29284 29285 29286 29287 29288 29289 29290 29291 29292 29293 29294 29295 29296 29297 29298 29299 29300 29301 29302 29303 29304 29305 29306 29307 29308 29309 29310 29311 29312 29313 29314 29315 29316 29317 29318 29319 29320 29321 29322 29323 29324 29325 29326 29327 29328 29329 29330 29331 29332 29333 29334 29335 29336 29337 29338 29339 29340 29341 29342 29343 29344 29345 29346 29347 29348 29349 29350 29351 29352 29353 29354 29355 29356 29357 29358 29359 29360 29361 29362 29363 29364 29365 29366 29367 29368 29369 29370 29371 29372 29373 29374 29375 29376 29377 29378 29379 29380 29381 29382 29383 29384 29385 29386 29387 29388 29389 29390 29391 29392 29393 29394 29395 29396 29397 29398 29399 29400 29401 29402 29403 29404 29405 29406 29407 29408 29409 29410 29411 29412 29413 29414 29415 29416 29417 29418 29419 29420 29421 29422 29423 29424 29425 29426 29427 29428 29429 29430 29431 29432 29433 29434 29435 29436 29437 29438 29439 29440 29441 29442 29443 29444 29445 29446 29447 29448 29449 29450 29451 29452 29453 29454 29455 29456 29457 29458 29459 29460 29461 29462 29463 29464 29465 29466 29467 29468 29469 29470 29471 29472 29473 29474 29475 29476 29477 29478 29479 29480 29481 29482 29483 29484 29485 29486 29487 29488 29489 29490 29491 29492 29493 29494 29495 29496 29497 29498 29499 29500 29501 29502 29503 29504 29505 29506 29507 29508 29509 29510 29511 29512 29513 29514 29515 29516 29517 29518 29519 29520 29521 29522 29523 29524 29525 29526 29527 29528 29529 29530 29531 29532 29533 29534 29535 29536 29537 29538 29539 29540 29541 29542 29543 29544 29545 29546 29547 29548 29549 29550 29551 29552 29553 29554 29555 29556 29557 29558 29559 29560 29561 29562 29563 29564 29565 29566 29567 29568 29569 29570 29571 29572 29573 29574 29575 29576 29577 29578 29579 29580 29581 29582 29583 29584 29585 29586 29587 29588 29589 29590 29591 29592 29593 29594 29595 29596 29597 29598 29599 29600 29601 29602 29603 29604 29605 29606 29607 29608 29609 29610 29611 29612 29613 29614 29615 29616 29617 29618 29619 29620 29621 29622 29623 29624 29625 29626 29627 29628 29629 29630 29631 29632 29633 29634 29635 29636 29637 29638 29639 29640 29641 29642 29643 29644 29645 29646 29647 29648 29649 29650 29651 29652 29653 29654 29655 29656 29657 29658 29659 29660 29661 29662 29663 29664 29665 29666 29667 29668 29669 29670 29671 29672 29673 29674 29675 29676 29677 29678 29679 29680 29681 29682 29683 29684 29685 29686 29687 29688 29689 29690 29691 29692 29693 29694 29695 29696 29697 29698 29699 29700 29701 29702 29703 29704 29705 29706 29707 29708 29709 29710 29711 29712 29713 29714 29715 29716 29717 29718 29719 29720 29721 29722 29723 29724 29725 29726 29727 29728 29729 29730 29731 29732 29733 29734 29735 29736 29737 29738 29739 29740 29741 29742 29743 29744 29745 29746 29747 29748 29749 29750 29751 29752 29753 29754 29755 29756 29757 29758 29759 29760 29761 29762 29763 29764 29765 29766 29767 29768 29769 29770 29771 29772 29773 29774 29775 29776 29777 29778 29779 29780 29781 29782 29783 29784 29785 29786 29787 29788 29789 29790 29791 29792 29793 29794 29795 29796 29797 29798 29799 29800 29801 29802 29803 29804 29805 29806 29807 29808 29809 29810 29811 29812 29813 29814 29815 29816 29817 29818 29819 29820 29821 29822 29823 29824 29825 29826 29827 29828 29829 29830 29831 29832 29833 29834 29835 29836 29837 29838 29839 29840 29841 29842 29843 29844 29845 29846 29847 29848 29849 29850 29851 29852 29853 29854 29855 29856 29857 29858 29859 29860 29861 29862 29863 29864 29865 29866 29867 29868 29869 29870 29871 29872 29873 29874 29875 29876 29877 29878 29879 29880 29881 29882 29883 29884 29885 29886 29887 29888 29889 29890 29891 29892 29893 29894 29895 29896 29897 29898 29899 29900 29901 29902 29903 29904 29905 29906 29907 29908 29909 29910 29911 29912 29913 29914 29915 29916 29917 29918 29919 29920 29921 29922 29923 29924 29925 29926 29927 29928 29929 29930 29931 29932 29933 29934 29935 29936 29937 29938 29939 29940 29941 29942 29943 29944 29945 29946 29947 29948 29949 29950 29951 29952 29953 29954 29955 29956 29957 29958 29959 29960 29961 29962 29963 29964 29965 29966 29967 29968 29969 29970 29971 29972 29973 29974 29975 29976 29977 29978 29979 29980 29981 29982 29983 29984 29985 29986 29987 29988 29989 29990 29991 29992 29993 29994 29995 29996 29997 29998 29999 30000 30001 30002 30003 30004 30005 30006 30007 30008 30009 30010 30011 30012 30013 30014 30015 30016 30017 30018 30019 30020 30021 30022 30023 30024 30025 30026 30027 30028 30029 30030 30031 30032 30033 30034 30035 30036 30037 30038 30039 30040 30041 30042 30043 30044 30045 30046 30047 30048 30049 30050 30051 30052 30053 30054 30055 30056 30057 30058 30059 30060 30061 30062 30063 30064 30065 30066 30067 30068 30069 30070 30071 30072 30073 30074 30075 30076 30077 30078 30079 30080 30081 30082 30083 30084 30085 30086 30087 30088 30089 30090 30091 30092 30093 30094 30095 30096 30097 30098 30099 30100 30101 30102 30103 30104 30105 30106 30107 30108 30109 30110 30111 30112 30113 30114 30115 30116 30117 30118 30119 30120 30121 30122 30123 30124 30125 30126 30127 30128 30129 30130 30131 30132 30133 30134 30135 30136 30137 30138 30139 30140 30141 30142 30143 30144 30145 30146 30147 30148 30149 30150 30151 30152 30153 30154 30155 30156 30157 30158 30159 30160 30161 30162 30163 30164 30165 30166 30167 30168 30169 30170 30171 30172 30173 30174 30175 30176 30177 30178 30179 30180 30181 30182 30183 30184 30185 30186 30187 30188 30189 30190 30191 30192 30193 30194 30195 30196 30197 30198 30199 30200 30201 30202 30203 30204 30205 30206 30207 30208 30209 30210 30211 30212 30213 30214 30215 30216 30217 30218 30219 30220 30221 30222 30223 30224 30225 30226 30227 30228 30229 30230 30231 30232 30233 30234 30235 30236 30237 30238 30239 30240 30241 30242 30243 30244 30245 30246 30247 30248 30249 30250 30251 30252 30253 30254 30255 30256 30257 30258 30259 30260 30261 30262 30263 30264 30265 30266 30267 30268 30269 30270 30271 30272 30273 30274 30275 30276 30277 30278 30279 30280 30281 30282 30283 30284 30285 30286 30287 30288 30289 30290 30291 30292 30293 30294 30295 30296 30297 30298 30299 30300 30301 30302 30303 30304 30305 30306 30307 30308 30309 30310 30311 30312 30313 30314 30315 30316 30317 30318 30319 30320 30321 30322 30323 30324 30325 30326 30327 30328 30329 30330 30331 30332 30333 30334 30335 30336 30337 30338 30339 30340 30341 30342 30343 30344 30345 30346 30347 30348 30349 30350 30351 30352 30353 30354 30355 30356 30357 30358 30359 30360 30361 30362 30363 30364 30365 30366 30367 30368 30369 30370 30371 30372 30373 30374 30375 30376 30377 30378 30379 30380 30381 30382 30383 30384 30385 30386 30387 30388 30389 30390 30391 30392 30393 30394 30395 30396 30397 30398 30399 30400 30401 30402 30403 30404 30405 30406 30407 30408 30409 30410 30411 30412 30413 30414 30415 30416 30417 30418 30419 30420 30421 30422 30423 30424 30425 30426 30427 30428 30429 30430 30431 30432 30433 30434 30435 30436 30437 30438 30439 30440 30441 30442 30443 30444 30445 30446 30447 30448 30449 30450 30451 30452 30453 30454 30455 30456 30457 30458 30459 30460 30461 30462 30463 30464 30465 30466 30467 30468 30469 30470 30471 30472 30473 30474 30475 30476 30477 30478 30479 30480 30481 30482 30483 30484 30485 30486 30487 30488 30489 30490 30491 30492 30493 30494 30495 30496 30497 30498 30499 30500 30501 30502 30503 30504 30505 30506 30507 30508 30509 30510 30511 30512 30513 30514 30515 30516 30517 30518 30519 30520 30521 30522 30523 30524 30525 30526 30527 30528 30529 30530 30531 30532 30533 30534 30535 30536 30537 30538 30539 30540 30541 30542 30543 30544 30545 30546 30547 30548 30549 30550 30551 30552 30553 30554 30555 30556 30557 30558 30559 30560 30561 30562 30563 30564 30565 30566 30567 30568 30569 30570 30571 30572 30573 30574 30575 30576 30577 30578 30579 30580 30581 30582 30583 30584 30585 30586 30587 30588 30589 30590 30591 30592 30593 30594 30595 30596 30597 30598 30599 30600 30601 30602 30603 30604 30605 30606 30607 30608 30609 30610 30611 30612 30613 30614 30615 30616 30617 30618 30619 30620 30621 30622 30623 30624 30625 30626 30627 30628 30629 30630 30631 30632 30633 30634 30635 30636 30637 30638 30639 30640 30641 30642 30643 30644 30645 30646 30647 30648 30649 30650 30651 30652 30653 30654 30655 30656 30657 30658 30659 30660 30661 30662 30663 30664 30665 30666 30667 30668 30669 30670 30671 30672 30673 30674 30675 30676 30677 30678 30679 30680 30681 30682 30683 30684 30685 30686 30687 30688 30689 30690 30691 30692 30693 30694 30695 30696 30697 30698 30699 30700 30701 30702 30703 30704 30705 30706 30707 30708 30709 30710 30711 30712 30713 30714 30715 30716 30717 30718 30719 30720 30721 30722 30723 30724 30725 30726 30727 30728 30729 30730 30731 30732 30733 30734 30735 30736 30737 30738 30739 30740 30741 30742 30743 30744 30745 30746 30747 30748 30749 30750 30751 30752 30753 30754 30755 30756 30757 30758 30759 30760 30761 30762 30763 30764 30765 30766 30767 30768 30769 30770 30771 30772 30773 30774 30775 30776 30777 30778 30779 30780 30781 30782 30783 30784 30785 30786 30787 30788 30789 30790 30791 30792 30793 30794 30795 30796 30797 30798 30799 30800 30801 30802 30803 30804 30805 30806 30807 30808 30809 30810 30811 30812 30813 30814 30815 30816 30817 30818 30819 30820 30821 30822 30823 30824 30825 30826 30827 30828 30829 30830 30831 30832 30833 30834 30835 30836 30837 30838 30839 30840 30841 30842 30843 30844 30845 30846 30847 30848 30849 30850 30851 30852 30853 30854 30855 30856 30857 30858 30859 30860 30861 30862 30863 30864 30865 30866 30867 30868 30869 30870 30871 30872 30873 30874 30875 30876 30877 30878 30879 30880 30881 30882 30883 30884 30885 30886 30887 30888 30889 30890 30891 30892 30893 30894 30895 30896 30897 30898 30899 30900 30901 30902 30903 30904 30905 30906 30907 30908 30909 30910 30911 30912 30913 30914 30915 30916 30917 30918 30919 30920 30921 30922 30923 30924 30925 30926 30927 30928 30929 30930 30931 30932 30933 30934 30935 30936 30937 30938 30939 30940 30941 30942 30943 30944 30945 30946 30947 30948 30949 30950 30951 30952 30953 30954 30955 30956 30957 30958 30959 30960 30961 30962 30963 30964 30965 30966 30967 30968 30969 30970 30971 30972 30973 30974 30975 30976 30977 30978 30979 30980 30981 30982 30983 30984 30985 30986 30987 30988 30989 30990 30991 30992 30993 30994 30995 30996 30997 30998 30999 31000 31001 31002 31003 31004 31005 31006 31007 31008 31009 31010 31011 31012 31013 31014 31015 31016 31017 31018 31019 31020 31021 31022 31023 31024 31025 31026 31027 31028 31029 31030 31031 31032 31033 31034 31035 31036 31037 31038 31039 31040 31041 31042 31043 31044 31045 31046 31047 31048 31049 31050 31051 31052 31053 31054 31055 31056 31057 31058 31059 31060 31061 31062 31063 31064 31065 31066 31067 31068 31069 31070 31071 31072 31073 31074 31075 31076 31077 31078 31079 31080 31081 31082 31083 31084 31085 31086 31087 31088 31089 31090 31091 31092 31093 31094 31095 31096 31097 31098 31099 31100 31101 31102 31103 31104 31105 31106 31107 31108 31109 31110 31111 31112 31113 31114 31115 31116 31117 31118 31119 31120 31121 31122 31123 31124 31125 31126 31127 31128 31129 31130 31131 31132 31133 31134 31135 31136 31137 31138 31139 31140 31141 31142 31143 31144 31145 31146 31147 31148 31149 31150 31151 31152 31153 31154 31155 31156 31157 31158 31159 31160 31161 31162 31163 31164 31165 31166 31167 31168 31169 31170 31171 31172 31173 31174 31175 31176 31177 31178 31179 31180 31181 31182 31183 31184 31185 31186 31187 31188 31189 31190 31191 31192 31193 31194 31195 31196 31197 31198 31199 31200 31201 31202 31203 31204 31205 31206 31207 31208 31209 31210 31211 31212 31213 31214 31215 31216 31217 31218 31219 31220 31221 31222 31223 31224 31225 31226 31227 31228 31229 31230 31231 31232 31233 31234 31235 31236 31237 31238 31239 31240 31241 31242 31243 31244 31245 31246 31247 31248 31249 31250 31251 31252 31253 31254 31255 31256 31257 31258 31259 31260 31261 31262 31263 31264 31265 31266 31267 31268 31269 31270 31271 31272 31273 31274 31275 31276 31277 31278 31279 31280 31281 31282 31283 31284 31285 31286 31287 31288 31289 31290 31291 31292 31293 31294 31295 31296 31297 31298 31299 31300 31301 31302 31303 31304 31305 31306 31307 31308 31309 31310 31311 31312 31313 31314 31315 31316 31317 31318 31319 31320 31321 31322 31323 31324 31325 31326 31327 31328 31329 31330 31331 31332 31333 31334 31335 31336 31337 31338 31339 31340 31341 31342 31343 31344 31345 31346 31347 31348 31349 31350 31351 31352 31353 31354 31355 31356 31357 31358 31359 31360 31361 31362 31363 31364 31365 31366 31367 31368 31369 31370 31371 31372 31373 31374 31375 31376 31377 31378 31379 31380 31381 31382 31383 31384 31385 31386 31387 31388 31389 31390 31391 31392 31393 31394 31395 31396 31397 31398 31399 31400 31401 31402 31403 31404 31405 31406 31407 31408 31409 31410 31411 31412 31413 31414 31415 31416 31417 31418 31419 31420 31421 31422 31423 31424 31425 31426 31427 31428 31429 31430 31431 31432 31433 31434 31435 31436 31437 31438 31439 31440 31441 31442 31443 31444 31445 31446 31447 31448 31449 31450 31451 31452 31453 31454 31455 31456 31457 31458 31459 31460 31461 31462 31463 31464 31465 31466 31467 31468 31469 31470 31471 31472 31473 31474 31475 31476 31477 31478 31479 31480 31481 31482 31483 31484 31485 31486 31487 31488 31489 31490 31491 31492 31493 31494 31495 31496 31497 31498 31499 31500 31501 31502 31503 31504 31505 31506 31507 31508 31509 31510 31511 31512 31513 31514 31515 31516 31517 31518 31519 31520 31521 31522 31523 31524 31525 31526 31527 31528 31529 31530 31531 31532 31533 31534 31535 31536 31537 31538 31539 31540 31541 31542 31543 31544 31545 31546 31547 31548 31549 31550 31551 31552 31553 31554 31555 31556 31557 31558 31559 31560 31561 31562 31563 31564 31565 31566 31567 31568 31569 31570 31571 31572 31573 31574 31575 31576 31577 31578 31579 31580 31581 31582 31583 31584 31585 31586 31587 31588 31589 31590 31591 31592 31593 31594 31595 31596 31597 31598 31599 31600 31601 31602 31603 31604 31605 31606 31607 31608 31609 31610 31611 31612 31613 31614 31615 31616 31617 31618 31619 31620 31621 31622 31623 31624 31625 31626 31627 31628 31629 31630 31631 31632 31633 31634 31635 31636 31637 31638 31639 31640 31641 31642 31643 31644 31645 31646 31647 31648 31649 31650 31651 31652 31653 31654 31655 31656 31657 31658 31659 31660 31661 31662 31663 31664 31665 31666 31667 31668 31669 31670 31671 31672 31673 31674 31675 31676 31677 31678 31679 31680 31681 31682 31683 31684 31685 31686 31687 31688 31689 31690 31691 31692 31693 31694 31695 31696 31697 31698 31699 31700 31701 31702 31703 31704 31705 31706 31707 31708 31709 31710 31711 31712 31713 31714 31715 31716 31717 31718 31719 31720 31721 31722 31723 31724 31725 31726 31727 31728 31729 31730 31731 31732 31733 31734 31735 31736 31737 31738 31739 31740 31741 31742 31743 31744 31745 31746 31747 31748 31749 31750 31751 31752 31753 31754 31755 31756 31757 31758 31759 31760 31761 31762 31763 31764 31765 31766 31767 31768 31769 31770 31771 31772 31773 31774 31775 31776 31777 31778 31779 31780 31781 31782 31783 31784 31785 31786 31787 31788 31789 31790 31791 31792 31793 31794 31795 31796 31797 31798 31799 31800 31801 31802 31803 31804 31805 31806 31807 31808 31809 31810 31811 31812 31813 31814 31815 31816 31817 31818 31819 31820 31821 31822 31823 31824 31825 31826 31827 31828 31829 31830 31831 31832 31833 31834 31835 31836 31837 31838 31839 31840 31841 31842 31843 31844 31845 31846 31847 31848 31849 31850 31851 31852 31853 31854 31855 31856 31857 31858 31859 31860 31861 31862 31863 31864 31865 31866 31867 31868 31869 31870 31871 31872 31873 31874 31875 31876 31877 31878 31879 31880 31881 31882 31883 31884 31885 31886 31887 31888 31889 31890 31891 31892 31893 31894 31895 31896 31897 31898 31899 31900 31901 31902 31903 31904 31905 31906 31907 31908 31909 31910 31911 31912 31913 31914 31915 31916 31917 31918 31919 31920 31921 31922 31923 31924 31925 31926 31927 31928 31929 31930 31931 31932 31933 31934 31935 31936 31937 31938 31939 31940 31941 31942 31943 31944 31945 31946 31947 31948 31949 31950 31951 31952 31953 31954 31955 31956 31957 31958 31959 31960 31961 31962 31963 31964 31965 31966 31967 31968 31969 31970 31971 31972 31973 31974 31975 31976 31977 31978 31979 31980 31981 31982 31983 31984 31985 31986 31987 31988 31989 31990 31991 31992 31993 31994 31995 31996 31997 31998 31999 32000 32001 32002 32003 32004 32005 32006 32007 32008 32009 32010 32011 32012 32013 32014 32015 32016 32017 32018 32019 32020 32021 32022 32023 32024 32025 32026 32027 32028 32029 32030 32031 32032 32033 32034 32035 32036 32037 32038 32039 32040 32041 32042 32043 32044 32045 32046 32047 32048 32049 32050 32051 32052 32053 32054 32055 32056 32057 32058 32059 32060 32061 32062 32063 32064 32065 32066 32067 32068 32069 32070 32071 32072 32073 32074 32075 32076 32077 32078 32079 32080 32081 32082 32083 32084 32085 32086 32087 32088 32089 32090 32091 32092 32093 32094 32095 32096 32097 32098 32099 32100 32101 32102 32103 32104 32105 32106 32107 32108 32109 32110 32111 32112 32113 32114 32115 32116 32117 32118 32119 32120 32121 32122 32123 32124 32125 32126 32127 32128 32129 32130 32131 32132 32133 32134 32135 32136 32137 32138 32139 32140 32141 32142 32143 32144 32145 32146 32147 32148 32149 32150 32151 32152 32153 32154 32155 32156 32157 32158 32159 32160 32161 32162 32163 32164 32165 32166 32167 32168 32169 32170 32171 32172 32173 32174 32175 32176 32177 32178 32179 32180 32181 32182 32183 32184 32185 32186 32187 32188 32189 32190 32191 32192 32193 32194 32195 32196 32197 32198 32199 32200 32201 32202 32203 32204 32205 32206 32207 32208 32209 32210 32211 32212 32213 32214 32215 32216 32217 32218 32219 32220 32221 32222 32223 32224 32225 32226 32227 32228 32229 32230 32231 32232 32233 32234 32235 32236 32237 32238 32239 32240 32241 32242 32243 32244 32245 32246 32247 32248 32249 32250 32251 32252 32253 32254 32255 32256 32257 32258 32259 32260 32261 32262 32263 32264 32265 32266 32267 32268 32269 32270 32271 32272 32273 32274 32275 32276 32277 32278 32279 32280 32281 32282 32283 32284 32285 32286 32287 32288 32289 32290 32291 32292 32293 32294 32295 32296 32297 32298 32299 32300 32301 32302 32303 32304 32305 32306 32307 32308 32309 32310 32311 32312 32313 32314 32315 32316 32317 32318 32319 32320 32321 32322 32323 32324 32325 32326 32327 32328 32329 32330 32331 32332 32333 32334 32335 32336 32337 32338 32339 32340 32341 32342 32343 32344 32345 32346 32347 32348 32349 32350 32351 32352 32353 32354 32355 32356 32357 32358 32359 32360 32361 32362 32363 32364 32365 32366 32367 32368 32369 32370 32371 32372 32373 32374 32375 32376 32377 32378 32379 32380 32381 32382 32383 32384 32385 32386 32387 32388 32389 32390 32391 32392 32393 32394 32395 32396 32397 32398 32399 32400 32401 32402 32403 32404 32405 32406 32407 32408 32409 32410 32411 32412 32413 32414 32415 32416 32417 32418 32419 32420 32421 32422 32423 32424 32425 32426 32427 32428 32429 32430 32431 32432 32433 32434 32435 32436 32437 32438 32439 32440 32441 32442 32443 32444 32445 32446 32447 32448 32449 32450 32451 32452 32453 32454 32455 32456 32457 32458 32459 32460 32461 32462 32463 32464 32465 32466 32467 32468 32469 32470 32471 32472 32473 32474 32475 32476 32477 32478 32479 32480 32481 32482 32483 32484 32485 32486 32487 32488 32489 32490 32491 32492 32493 32494 32495 32496 32497 32498 32499 32500 32501 32502 32503 32504 32505 32506 32507 32508 32509 32510 32511 32512 32513 32514 32515 32516 32517 32518 32519 32520 32521 32522 32523 32524 32525 32526 32527 32528 32529 32530 32531 32532 32533 32534 32535 32536 32537 32538 32539 32540 32541 32542 32543 32544 32545 32546 32547 32548 32549 32550 32551 32552 32553 32554 32555 32556 32557 32558 32559 32560 32561 32562 32563 32564 32565 32566 32567 32568 32569 32570 32571 32572 32573 32574 32575 32576 32577 32578 32579 32580 32581 32582 32583 32584 32585 32586 32587 32588 32589 32590 32591 32592 32593 32594 32595 32596 32597 32598 32599 32600 32601 32602 32603 32604 32605 32606 32607 32608 32609 32610 32611 32612 32613 32614 32615 32616 32617 32618 32619 32620 32621 32622 32623 32624 32625 32626 32627 32628 32629 32630 32631 32632 32633 32634 32635 32636 32637 32638 32639 32640 32641 32642 32643 32644 32645 32646 32647 32648 32649 32650 32651 32652 32653 32654 32655 32656 32657 32658 32659 32660 32661 32662 32663 32664 32665 32666 32667 32668 32669 32670 32671 32672 32673 32674 32675 32676 32677 32678 32679 32680 32681 32682 32683 32684 32685 32686 32687 32688 32689 32690 32691 32692 32693 32694 32695 32696 32697 32698 32699 32700 32701 32702 32703 32704 32705 32706 32707 32708 32709 32710 32711 32712 32713 32714 32715 32716 32717 32718 32719 32720 32721 32722 32723 32724 32725 32726 32727 32728 32729 32730 32731 32732 32733 32734 32735 32736 32737 32738 32739 32740 32741 32742 32743 32744 32745 32746 32747 32748 32749 32750 32751 32752 32753 32754 32755 32756 32757 32758 32759 32760 32761 32762 32763 32764 32765 32766 32767 32768 32769 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779 32780 32781 32782 32783 32784 32785 32786 32787 32788 32789 32790 32791 32792 32793 32794 32795 32796 32797 32798 32799 32800 32801 32802 32803 32804 32805 32806 32807 32808 32809 32810 32811 32812 32813 32814 32815 32816 32817 32818 32819 32820 32821 32822 32823 32824 32825 32826 32827 32828 32829 32830 32831 32832 32833 32834 32835 32836 32837 32838 32839 32840 32841 32842 32843 32844 32845 32846 32847 32848 32849 32850 32851 32852 32853 32854 32855 32856 32857 32858 32859 32860 32861 32862 32863 32864 32865 32866 32867 32868 32869 32870 32871 32872 32873 32874 32875 32876 32877 32878 32879 32880 32881 32882 32883 32884 32885 32886 32887 32888 32889 32890 32891 32892 32893 32894 32895 32896 32897 32898 32899 32900 32901 32902 32903 32904 32905 32906 32907 32908 32909 32910 32911 32912 32913 32914 32915 32916 32917 32918 32919 32920 32921 32922 32923 32924 32925 32926 32927 32928 32929 32930 32931 32932 32933 32934 32935 32936 32937 32938 32939 32940 32941 32942 32943 32944 32945 32946 32947 32948 32949 32950 32951 32952 32953 32954 32955 32956 32957 32958 32959 32960 32961 32962 32963 32964 32965 32966 32967 32968 32969 32970 32971 32972 32973 32974 32975 32976 32977 32978 32979 32980 32981 32982 32983 32984 32985 32986 32987 32988 32989 32990 32991 32992 32993 32994 32995 32996 32997 32998 32999 33000 33001 33002 33003 33004 33005 33006 33007 33008 33009 33010 33011 33012 33013 33014 33015 33016 33017 33018 33019 33020 33021 33022 33023 33024 33025 33026 33027 33028 33029 33030 33031 33032 33033 33034 33035 33036 33037 33038 33039 33040 33041 33042 33043 33044 33045 33046 33047 33048 33049 33050 33051 33052 33053 33054 33055 33056 33057 33058 33059 33060 33061 33062 33063 33064 33065 33066 33067 33068 33069 33070 33071 33072 33073 33074 33075 33076 33077 33078 33079 33080 33081 33082 33083 33084 33085 33086 33087 33088 33089 33090 33091 33092 33093 33094 33095 33096 33097 33098 33099 33100 33101 33102 33103 33104 33105 33106 33107 33108 33109 33110 33111 33112 33113 33114 33115 33116 33117 33118 33119 33120 33121 33122 33123 33124 33125 33126 33127 33128 33129 33130 33131 33132 33133 33134 33135 33136 33137 33138 33139 33140 33141 33142 33143 33144 33145 33146 33147 33148 33149 33150 33151 33152 33153 33154 33155 33156 33157 33158 33159 33160 33161 33162 33163 33164 33165 33166 33167 33168 33169 33170 33171 33172 33173 33174 33175 33176 33177 33178 33179 33180 33181 33182 33183 33184 33185 33186 33187 33188 33189 33190 33191 33192 33193 33194 33195 33196 33197 33198 33199 33200 33201 33202 33203 33204 33205 33206 33207 33208 33209 33210 33211 33212 33213 33214 33215 33216 33217 33218 33219 33220 33221 33222 33223 33224 33225 33226 33227 33228 33229 33230 33231 33232 33233 33234 33235 33236 33237 33238 33239 33240 33241 33242 33243 33244 33245 33246 33247 33248 33249 33250 33251 33252 33253 33254 33255 33256 33257 33258 33259 33260 33261 33262 33263 33264 33265 33266 33267 33268 33269 33270 33271 33272 33273 33274 33275 33276 33277 33278 33279 33280 33281 33282 33283 33284 33285 33286 33287 33288 33289 33290 33291 33292 33293 33294 33295 33296 33297 33298 33299 33300 33301 33302 33303 33304 33305 33306 33307 33308 33309 33310 33311 33312 33313 33314 33315 33316 33317 33318 33319 33320 33321 33322 33323 33324 33325 33326 33327 33328 33329 33330 33331 33332 33333 33334 33335 33336 33337 33338 33339 33340 33341 33342 33343 33344 33345 33346 33347 33348 33349 33350 33351 33352 33353 33354 33355 33356 33357 33358 33359 33360 33361 33362 33363 33364 33365 33366 33367 33368 33369 33370 33371 33372 33373 33374 33375 33376 33377 33378 33379 33380 33381 33382 33383 33384 33385 33386 33387 33388 33389 33390 33391 33392 33393 33394 33395 33396 33397 33398 33399 33400 33401 33402 33403 33404 33405 33406 33407 33408 33409 33410 33411 33412 33413 33414 33415 33416 33417 33418 33419 33420 33421 33422 33423 33424 33425 33426 33427 33428 33429 33430 33431 33432 33433 33434 33435 33436 33437 33438 33439 33440 33441 33442 33443 33444 33445 33446 33447 33448 33449 33450 33451 33452 33453 33454 33455 33456 33457 33458 33459 33460 33461 33462 33463 33464 33465 33466 33467 33468 33469 33470 33471 33472 33473 33474 33475 33476 33477 33478 33479 33480 33481 33482 33483 33484 33485 33486 33487 33488 33489 33490 33491 33492 33493 33494 33495 33496 33497 33498 33499 33500 33501 33502 33503 33504 33505 33506 33507 33508 33509 33510 33511 33512 33513 33514 33515 33516 33517 33518 33519 33520 33521 33522 33523 33524 33525 33526 33527 33528 33529 33530 33531 33532 33533 33534 33535 33536 33537 33538 33539 33540 33541 33542 33543 33544 33545 33546 33547 33548 33549 33550 33551 33552 33553 33554 33555 33556 33557 33558 33559 33560 33561 33562 33563 33564 33565 33566 33567 33568 33569 33570 33571 33572 33573 33574 33575 33576 33577 33578 33579 33580 33581 33582 33583 33584 33585 33586 33587 33588 33589 33590 33591 33592 33593 33594 33595 33596 33597 33598 33599 33600 33601 33602 33603 33604 33605 33606 33607 33608 33609 33610 33611 33612 33613 33614 33615 33616 33617 33618 33619 33620 33621 33622 33623 33624 33625 33626 33627 33628 33629 33630 33631 33632 33633 33634 33635 33636 33637 33638 33639 33640 33641 33642 33643 33644 33645 33646 33647 33648 33649 33650 33651 33652 33653 33654 33655 33656 33657 33658 33659 33660 33661 33662 33663 33664 33665 33666 33667 33668 33669 33670 33671 33672 33673 33674 33675 33676 33677 33678 33679 33680 33681 33682 33683 33684 33685 33686 33687 33688 33689 33690 33691 33692 33693 33694 33695 33696 33697 33698 33699 33700 33701 33702 33703 33704 33705 33706 33707 33708 33709 33710 33711 33712 33713 33714 33715 33716 33717 33718 33719 33720 33721 33722 33723 33724 33725 33726 33727 33728 33729 33730 33731 33732 33733 33734 33735 33736 33737 33738 33739 33740 33741 33742 33743 33744 33745 33746 33747 33748 33749 33750 33751 33752 33753 33754 33755 33756 33757 33758 33759 33760 33761 33762 33763 33764 33765 33766 33767 33768 33769 33770 33771 33772 33773 33774 33775 33776 33777 33778 33779 33780 33781 33782 33783 33784 33785 33786 33787 33788 33789 33790 33791 33792 33793 33794 33795 33796 33797 33798 33799 33800 33801 33802 33803 33804 33805 33806 33807 33808 33809 33810 33811 33812 33813 33814 33815 33816 33817 33818 33819 33820 33821 33822 33823 33824 33825 33826 33827 33828 33829 33830 33831 33832 33833 33834 33835 33836 33837 33838 33839 33840 33841 33842 33843 33844 33845 33846 33847 33848 33849 33850 33851 33852 33853 33854 33855 33856 33857 33858 33859 33860 33861 33862 33863 33864 33865 33866 33867 33868 33869 33870 33871 33872 33873 33874 33875 33876 33877 33878 33879 33880 33881 33882 33883 33884 33885 33886 33887 33888 33889 33890 33891 33892 33893 33894 33895 33896 33897 33898 33899 33900 33901 33902 33903 33904 33905 33906 33907 33908 33909 33910 33911 33912 33913 33914 33915 33916 33917 33918 33919 33920 33921 33922 33923 33924 33925 33926 33927 33928 33929 33930 33931 33932 33933 33934 33935 33936 33937 33938 33939 33940 33941 33942 33943 33944 33945 33946 33947 33948 33949 33950 33951 33952 33953 33954 33955 33956 33957 33958 33959 33960 33961 33962 33963 33964 33965 33966 33967 33968 33969 33970 33971 33972 33973 33974 33975 33976 33977 33978 33979 33980 33981 33982 33983 33984 33985 33986 33987 33988 33989 33990 33991 33992 33993 33994 33995 33996 33997 33998 33999 34000 34001 34002 34003 34004 34005 34006 34007 34008 34009 34010 34011 34012 34013 34014 34015 34016 34017 34018 34019 34020 34021 34022 34023 34024 34025 34026 34027 34028 34029 34030 34031 34032 34033 34034 34035 34036 34037 34038 34039 34040 34041 34042 34043 34044 34045 34046 34047 34048 34049 34050 34051 34052 34053 34054 34055 34056 34057 34058 34059 34060 34061 34062 34063 34064 34065 34066 34067 34068 34069 34070 34071 34072 34073 34074 34075 34076 34077 34078 34079 34080 34081 34082 34083 34084 34085 34086 34087 34088 34089 34090 34091 34092 34093 34094 34095 34096 34097 34098 34099 34100 34101 34102 34103 34104 34105 34106 34107 34108 34109 34110 34111 34112 34113 34114 34115 34116 34117 34118 34119 34120 34121 34122 34123 34124 34125 34126 34127 34128 34129 34130 34131 34132 34133 34134 34135 34136 34137 34138 34139 34140 34141 34142 34143 34144 34145 34146 34147 34148 34149 34150 34151 34152 34153 34154 34155 34156 34157 34158 34159 34160 34161 34162 34163 34164 34165 34166 34167 34168 34169 34170 34171 34172 34173 34174 34175 34176 34177 34178 34179 34180 34181 34182 34183 34184 34185 34186 34187 34188 34189 34190 34191 34192 34193 34194 34195 34196 34197 34198 34199 34200 34201 34202 34203 34204 34205 34206 34207 34208 34209 34210 34211 34212 34213 34214 34215 34216 34217 34218 34219 34220 34221 34222 34223 34224 34225 34226 34227 34228 34229 34230 34231 34232 34233 34234 34235 34236 34237 34238 34239 34240 34241 34242 34243 34244 34245 34246 34247 34248 34249 34250 34251 34252 34253 34254 34255 34256 34257 34258 34259 34260 34261 34262 34263 34264 34265 34266 34267 34268 34269 34270 34271 34272 34273 34274 34275 34276 34277 34278 34279 34280 34281 34282 34283 34284 34285 34286 34287 34288 34289 34290 34291 34292 34293 34294 34295 34296 34297 34298 34299 34300 34301 34302 34303 34304 34305 34306 34307 34308 34309 34310 34311 34312 34313 34314 34315 34316 34317 34318 34319 34320 34321 34322 34323 34324 34325 34326 34327 34328 34329 34330 34331 34332 34333 34334 34335 34336 34337 34338 34339 34340 34341 34342 34343 34344 34345 34346 34347 34348 34349 34350 34351 34352 34353 34354 34355 34356 34357 34358 34359 34360 34361 34362 34363 34364 34365 34366 34367 34368 34369 34370 34371 34372 34373 34374 34375 34376 34377 34378 34379 34380 34381 34382 34383 34384 34385 34386 34387 34388 34389 34390 34391 34392 34393 34394 34395 34396 34397 34398 34399 34400 34401 34402 34403 34404 34405 34406 34407 34408 34409 34410 34411 34412 34413 34414 34415 34416 34417 34418 34419 34420 34421 34422 34423 34424 34425 34426 34427 34428 34429 34430 34431 34432 34433 34434 34435 34436 34437 34438 34439 34440 34441 34442 34443 34444 34445 34446 34447 34448 34449 34450 34451 34452 34453 34454 34455 34456 34457 34458 34459 34460 34461 34462 34463 34464 34465 34466 34467 34468 34469 34470 34471 34472 34473 34474 34475 34476 34477 34478 34479 34480 34481 34482 34483 34484 34485 34486 34487 34488 34489 34490 34491 34492 34493 34494 34495 34496 34497 34498 34499 34500 34501 34502 34503 34504 34505 34506 34507 34508 34509 34510 34511 34512 34513 34514 34515 34516 34517 34518 34519 34520 34521 34522 34523 34524 34525 34526 34527 34528 34529 34530 34531 34532 34533 34534 34535 34536 34537 34538 34539 34540 34541 34542 34543 34544 34545 34546 34547 34548 34549 34550 34551 34552 34553 34554 34555 34556 34557 34558 34559 34560 34561 34562 34563 34564 34565 34566 34567 34568 34569 34570 34571 34572 34573 34574 34575 34576 34577 34578 34579 34580 34581 34582 34583 34584 34585 34586 34587 34588 34589 34590 34591 34592 34593 34594 34595 34596 34597 34598 34599 34600 34601 34602 34603 34604 34605 34606 34607 34608 34609 34610 34611 34612 34613 34614 34615 34616 34617 34618 34619 34620 34621 34622 34623 34624 34625 34626 34627 34628 34629 34630 34631 34632 34633 34634 34635 34636 34637 34638 34639 34640 34641 34642 34643 34644 34645 34646 34647 34648 34649 34650 34651 34652 34653 34654 34655 34656 34657 34658 34659 34660 34661 34662 34663 34664 34665 34666 34667 34668 34669 34670 34671 34672 34673 34674 34675 34676 34677 34678 34679 34680 34681 34682 34683 34684 34685 34686 34687 34688 34689 34690 34691 34692 34693 34694 34695 34696 34697 34698 34699 34700 34701 34702 34703 34704 34705 34706 34707 34708 34709 34710 34711 34712 34713 34714 34715 34716 34717 34718 34719 34720 34721 34722 34723 34724 34725 34726 34727 34728 34729 34730 34731 34732 34733 34734 34735 34736 34737 34738 34739 34740 34741 34742 34743 34744 34745 34746 34747 34748 34749 34750 34751 34752 34753 34754 34755 34756 34757 34758 34759 34760 34761 34762 34763 34764 34765 34766 34767 34768 34769 34770 34771 34772 34773 34774 34775 34776 34777 34778 34779 34780 34781 34782 34783 34784 34785 34786 34787 34788 34789 34790 34791 34792 34793 34794 34795 34796 34797 34798 34799 34800 34801 34802 34803 34804 34805 34806 34807 34808 34809 34810 34811 34812 34813 34814 34815 34816 34817 34818 34819 34820 34821 34822 34823 34824 34825 34826 34827 34828 34829 34830 34831 34832 34833 34834 34835 34836 34837 34838 34839 34840 34841 34842 34843 34844 34845 34846 34847 34848 34849 34850 34851 34852 34853 34854 34855 34856 34857 34858 34859 34860 34861 34862 34863 34864 34865 34866 34867 34868 34869 34870 34871 34872 34873 34874 34875 34876 34877 34878 34879 34880 34881 34882 34883 34884 34885 34886 34887 34888 34889 34890 34891 34892 34893 34894 34895 34896 34897 34898 34899 34900 34901 34902 34903 34904 34905 34906 34907 34908 34909 34910 34911 34912 34913 34914 34915 34916 34917 34918 34919 34920 34921 34922 34923 34924 34925 34926 34927 34928 34929 34930 34931 34932 34933 34934 34935 34936 34937 34938 34939 34940 34941 34942 34943 34944 34945 34946 34947 34948 34949 34950 34951 34952 34953 34954 34955 34956 34957 34958 34959 34960 34961 34962 34963 34964 34965 34966 34967 34968 34969 34970 34971 34972 34973 34974 34975 34976 34977 34978 34979 34980 34981 34982 34983 34984 34985 34986 34987 34988 34989 34990 34991 34992 34993 34994 34995 34996 34997 34998 34999 35000 35001 35002 35003 35004 35005 35006 35007 35008 35009 35010 35011 35012 35013 35014 35015 35016 35017 35018 35019 35020 35021 35022 35023 35024 35025 35026 35027 35028 35029 35030 35031 35032 35033 35034 35035 35036 35037 35038 35039 35040 35041 35042 35043 35044 35045 35046 35047 35048 35049 35050 35051 35052 35053 35054 35055 35056 35057 35058 35059 35060 35061 35062 35063 35064 35065 35066 35067 35068 35069 35070 35071 35072 35073 35074 35075 35076 35077 35078 35079 35080 35081 35082 35083 35084 35085 35086 35087 35088 35089 35090 35091 35092 35093 35094 35095 35096 35097 35098 35099 35100 35101 35102 35103 35104 35105 35106 35107 35108 35109 35110 35111 35112 35113 35114 35115 35116 35117 35118 35119 35120 35121 35122 35123 35124 35125 35126 35127 35128 35129 35130 35131 35132 35133 35134 35135 35136 35137 35138 35139 35140 35141 35142 35143 35144 35145 35146 35147 35148 35149 35150 35151 35152 35153 35154 35155 35156 35157 35158 35159 35160 35161 35162 35163 35164 35165 35166 35167 35168 35169 35170 35171 35172 35173 35174 35175 35176 35177 35178 35179 35180 35181 35182 35183 35184 35185 35186 35187 35188 35189 35190 35191 35192 35193 35194 35195 35196 35197 35198 35199 35200 35201 35202 35203 35204 35205 35206 35207 35208 35209 35210 35211 35212 35213 35214 35215 35216 35217 35218 35219 35220 35221 35222 35223 35224 35225 35226 35227 35228 35229 35230 35231 35232 35233 35234 35235 35236 35237 35238 35239 35240 35241 35242 35243 35244 35245 35246 35247 35248 35249 35250 35251 35252 35253 35254 35255 35256 35257 35258 35259 35260 35261 35262 35263 35264 35265 35266 35267 35268 35269 35270 35271 35272 35273 35274 35275 35276 35277 35278 35279 35280 35281 35282 35283 35284 35285 35286 35287 35288 35289 35290 35291 35292 35293 35294 35295 35296 35297 35298 35299 35300 35301 35302 35303 35304 35305 35306 35307 35308 35309 35310 35311 35312 35313 35314 35315 35316 35317 35318 35319 35320 35321 35322 35323 35324 35325 35326 35327 35328 35329 35330 35331 35332 35333 35334 35335 35336 35337 35338 35339 35340 35341 35342 35343 35344 35345 35346 35347 35348 35349 35350 35351 35352 35353 35354 35355 35356 35357 35358 35359 35360 35361 35362 35363 35364 35365 35366 35367 35368 35369 35370 35371 35372 35373 35374 35375 35376 35377 35378 35379 35380 35381 35382 35383 35384 35385 35386 35387 35388 35389 35390 35391 35392 35393 35394 35395 35396 35397 35398 35399 35400 35401 35402 35403 35404 35405 35406 35407 35408 35409 35410 35411 35412 35413 35414 35415 35416 35417 35418 35419 35420 35421 35422 35423 35424 35425 35426 35427 35428 35429 35430 35431 35432 35433 35434 35435 35436 35437 35438 35439 35440 35441 35442 35443 35444 35445 35446 35447 35448 35449 35450 35451 35452 35453 35454 35455 35456 35457 35458 35459 35460 35461 35462 35463 35464 35465 35466 35467 35468 35469 35470 35471 35472 35473 35474 35475 35476 35477 35478 35479 35480 35481 35482 35483 35484 35485 35486 35487 35488 35489 35490 35491 35492 35493 35494 35495 35496 35497 35498 35499 35500 35501 35502 35503 35504 35505 35506 35507 35508 35509 35510 35511 35512 35513 35514 35515 35516 35517 35518 35519 35520 35521 35522 35523 35524 35525 35526 35527 35528 35529 35530 35531 35532 35533 35534 35535 35536 35537 35538 35539 35540 35541 35542 35543 35544 35545 35546 35547 35548 35549 35550 35551 35552 35553 35554 35555 35556 35557 35558 35559 35560 35561 35562 35563 35564 35565 35566 35567 35568 35569 35570 35571 35572 35573 35574 35575 35576 35577 35578 35579 35580 35581 35582 35583 35584 35585 35586 35587 35588 35589 35590 35591 35592 35593 35594 35595 35596 35597 35598 35599 35600 35601 35602 35603 35604 35605 35606 35607 35608 35609 35610 35611 35612 35613 35614 35615 35616 35617 35618 35619 35620 35621 35622 35623 35624 35625 35626 35627 35628 35629 35630 35631 35632 35633 35634 35635 35636 35637 35638 35639 35640 35641 35642 35643 35644 35645 35646 35647 35648 35649 35650 35651 35652 35653 35654 35655 35656 35657 35658 35659 35660 35661 35662 35663 35664 35665 35666 35667 35668 35669 35670 35671 35672 35673 35674 35675 35676 35677 35678 35679 35680 35681 35682 35683 35684 35685 35686 35687 35688 35689 35690 35691 35692 35693 35694 35695 35696 35697 35698 35699 35700 35701 35702 35703 35704 35705 35706 35707 35708 35709 35710 35711 35712 35713 35714 35715 35716 35717 35718 35719 35720 35721 35722 35723 35724 35725 35726 35727 35728 35729 35730 35731 35732 35733 35734 35735 35736 35737 35738 35739 35740 35741 35742 35743 35744 35745 35746 35747 35748 35749 35750 35751 35752 35753 35754 35755 35756 35757 35758 35759 35760 35761 35762 35763 35764 35765 35766 35767 35768 35769 35770 35771 35772 35773 35774 35775 35776 35777 35778 35779 35780 35781 35782 35783 35784 35785 35786 35787 35788 35789 35790 35791 35792 35793 35794 35795 35796 35797 35798 35799 35800 35801 35802 35803 35804 35805 35806 35807 35808 35809 35810 35811 35812 35813 35814 35815 35816 35817 35818 35819 35820 35821 35822 35823 35824 35825 35826 35827 35828 35829 35830 35831 35832 35833 35834 35835 35836 35837 35838 35839 35840 35841 35842 35843 35844 35845 35846 35847 35848 35849 35850 35851 35852 35853 35854 35855 35856 35857 35858 35859 35860 35861 35862 35863 35864 35865 35866 35867 35868 35869 35870 35871 35872 35873 35874 35875 35876 35877 35878 35879 35880 35881 35882 35883 35884 35885 35886 35887 35888 35889 35890 35891 35892 35893 35894 35895 35896 35897 35898 35899 35900 35901 35902 35903 35904 35905 35906 35907 35908 35909 35910 35911 35912 35913 35914 35915 35916 35917 35918 35919 35920 35921 35922 35923 35924 35925 35926 35927 35928 35929 35930 35931 35932 35933 35934 35935 35936 35937 35938 35939 35940 35941 35942 35943 35944 35945 35946 35947 35948 35949 35950 35951 35952 35953 35954 35955 35956 35957 35958 35959 35960 35961 35962 35963 35964 35965 35966 35967 35968 35969 35970 35971 35972 35973 35974 35975 35976 35977 35978 35979 35980 35981 35982 35983 35984 35985 35986 35987 35988 35989 35990 35991 35992 35993 35994 35995 35996 35997 35998 35999 36000 36001 36002 36003 36004 36005 36006 36007 36008 36009 36010 36011 36012 36013 36014 36015 36016 36017 36018 36019 36020 36021 36022 36023 36024 36025 36026 36027 36028 36029 36030 36031 36032 36033 36034 36035 36036 36037 36038 36039 36040 36041 36042 36043 36044 36045 36046 36047 36048 36049 36050 36051 36052 36053 36054 36055 36056 36057 36058 36059 36060 36061 36062 36063 36064 36065 36066 36067 36068 36069 36070 36071 36072 36073 36074 36075 36076 36077 36078 36079 36080 36081 36082 36083 36084 36085 36086 36087 36088 36089 36090 36091 36092 36093 36094 36095 36096 36097 36098 36099 36100 36101 36102 36103 36104 36105 36106 36107 36108 36109 36110 36111 36112 36113 36114 36115 36116 36117 36118 36119 36120 36121 36122 36123 36124 36125 36126 36127 36128 36129 36130 36131 36132 36133 36134 36135 36136 36137 36138 36139 36140 36141 36142 36143 36144 36145 36146 36147 36148 36149 36150 36151 36152 36153 36154 36155 36156 36157 36158 36159 36160 36161 36162 36163 36164 36165 36166 36167 36168 36169 36170 36171 36172 36173 36174 36175 36176 36177 36178 36179 36180 36181 36182 36183 36184 36185 36186 36187 36188 36189 36190 36191 36192 36193 36194 36195 36196 36197 36198 36199 36200 36201 36202 36203 36204 36205 36206 36207 36208 36209 36210 36211 36212 36213 36214 36215 36216 36217 36218 36219 36220 36221 36222 36223 36224 36225 36226 36227 36228 36229 36230 36231 36232 36233 36234 36235 36236 36237 36238 36239 36240 36241 36242 36243 36244 36245 36246 36247 36248 36249 36250 36251 36252 36253 36254 36255 36256 36257 36258 36259 36260 36261 36262 36263 36264 36265 36266 36267 36268 36269 36270 36271 36272 36273 36274 36275 36276 36277 36278 36279 36280 36281 36282 36283 36284 36285 36286 36287 36288 36289 36290 36291 36292 36293 36294 36295 36296 36297 36298 36299 36300 36301 36302 36303 36304 36305 36306 36307 36308 36309 36310 36311 36312 36313 36314 36315 36316 36317 36318 36319 36320 36321 36322 36323 36324 36325 36326 36327 36328 36329 36330 36331 36332 36333 36334 36335 36336 36337 36338 36339 36340 36341 36342 36343 36344 36345 36346 36347 36348 36349 36350 36351 36352 36353 36354 36355 36356 36357 36358 36359 36360 36361 36362 36363 36364 36365 36366 36367 36368 36369 36370 36371 36372 36373 36374 36375 36376 36377 36378 36379 36380 36381 36382 36383 36384 36385 36386 36387 36388 36389 36390 36391 36392 36393 36394 36395 36396 36397 36398 36399 36400 36401 36402 36403 36404 36405 36406 36407 36408 36409 36410 36411 36412 36413 36414 36415 36416 36417 36418 36419 36420 36421 36422 36423 36424 36425 36426 36427 36428 36429 36430 36431 36432 36433 36434 36435 36436 36437 36438 36439 36440 36441 36442 36443 36444 36445 36446 36447 36448 36449 36450 36451 36452 36453 36454 36455 36456 36457 36458 36459 36460 36461 36462 36463 36464 36465 36466 36467 36468 36469 36470 36471 36472 36473 36474 36475 36476 36477 36478 36479 36480 36481 36482 36483 36484 36485 36486 36487 36488 36489 36490 36491 36492 36493 36494 36495 36496 36497 36498 36499 36500 36501 36502 36503 36504 36505 36506 36507 36508 36509 36510 36511 36512 36513 36514 36515 36516 36517 36518 36519 36520 36521 36522 36523 36524 36525 36526 36527 36528 36529 36530 36531 36532 36533 36534 36535 36536 36537 36538 36539 36540 36541 36542 36543 36544 36545 36546 36547 36548 36549 36550 36551 36552 36553 36554 36555 36556 36557 36558 36559 36560 36561 36562 36563 36564 36565 36566 36567 36568 36569 36570 36571 36572 36573 36574 36575 36576 36577 36578 36579 36580 36581 36582 36583 36584 36585 36586 36587 36588 36589 36590 36591 36592 36593 36594 36595 36596 36597 36598 36599 36600 36601 36602 36603 36604 36605 36606 36607 36608 36609 36610 36611 36612 36613 36614 36615 36616 36617 36618 36619 36620 36621 36622 36623 36624 36625 36626 36627 36628 36629 36630 36631 36632 36633 36634 36635 36636 36637 36638 36639 36640 36641 36642 36643 36644 36645 36646 36647 36648 36649 36650 36651 36652 36653 36654 36655 36656 36657 36658 36659 36660 36661 36662 36663 36664 36665 36666 36667 36668 36669 36670 36671 36672 36673 36674 36675 36676 36677 36678 36679 36680 36681 36682 36683 36684 36685 36686 36687 36688 36689 36690 36691 36692 36693 36694 36695 36696 36697 36698 36699 36700 36701 36702 36703 36704 36705 36706 36707 36708 36709 36710 36711 36712 36713 36714 36715 36716 36717 36718 36719 36720 36721 36722 36723 36724 36725 36726 36727 36728 36729 36730 36731 36732 36733 36734 36735 36736 36737 36738 36739 36740 36741 36742 36743 36744 36745 36746 36747 36748 36749 36750 36751 36752 36753 36754 36755 36756 36757 36758 36759 36760 36761 36762 36763 36764 36765 36766 36767 36768 36769 36770 36771 36772 36773 36774 36775 36776 36777 36778 36779 36780 36781 36782 36783 36784 36785 36786 36787 36788 36789 36790 36791 36792 36793 36794 36795 36796 36797 36798 36799 36800 36801 36802 36803 36804 36805 36806 36807 36808 36809 36810 36811 36812 36813 36814 36815 36816 36817 36818 36819 36820 36821 36822 36823 36824 36825 36826 36827 36828 36829 36830 36831 36832 36833 36834 36835 36836 36837 36838 36839 36840 36841 36842 36843 36844 36845 36846 36847 36848 36849 36850 36851 36852 36853 36854 36855 36856 36857 36858 36859 36860 36861 36862 36863 36864 36865 36866 36867 36868 36869 36870 36871 36872 36873 36874 36875 36876 36877 36878 36879 36880 36881 36882 36883 36884 36885 36886 36887 36888 36889 36890 36891 36892 36893 36894 36895 36896 36897 36898 36899 36900 36901 36902 36903 36904 36905 36906 36907 36908 36909 36910 36911 36912 36913 36914 36915 36916 36917 36918 36919 36920 36921 36922 36923 36924 36925 36926 36927 36928 36929 36930 36931 36932 36933 36934 36935 36936 36937 36938 36939 36940 36941 36942 36943 36944 36945 36946 36947 36948 36949 36950 36951 36952 36953 36954 36955 36956 36957 36958 36959 36960 36961 36962 36963 36964 36965 36966 36967 36968 36969 36970 36971 36972 36973 36974 36975 36976 36977 36978 36979 36980 36981 36982 36983 36984 36985 36986 36987 36988 36989 36990 36991 36992 36993 36994 36995 36996 36997 36998 36999 37000 37001 37002 37003 37004 37005 37006 37007 37008 37009 37010 37011 37012 37013 37014 37015 37016 37017 37018 37019 37020 37021 37022 37023 37024 37025 37026 37027 37028 37029 37030 37031 37032 37033 37034 37035 37036 37037 37038 37039 37040 37041 37042 37043 37044 37045 37046 37047 37048 37049 37050 37051 37052 37053 37054 37055 37056 37057 37058 37059 37060 37061 37062 37063 37064 37065 37066 37067 37068 37069 37070 37071 37072 37073 37074 37075 37076 37077 37078 37079 37080 37081 37082 37083 37084 37085 37086 37087 37088 37089 37090 37091 37092 37093 37094 37095 37096 37097 37098 37099 37100 37101 37102 37103 37104 37105 37106 37107 37108 37109 37110 37111 37112 37113 37114 37115 37116 37117 37118 37119 37120 37121 37122 37123 37124 37125 37126 37127 37128 37129 37130 37131 37132 37133 37134 37135 37136 37137 37138 37139 37140 37141 37142 37143 37144 37145 37146 37147 37148 37149 37150 37151 37152 37153 37154 37155 37156 37157 37158 37159 37160 37161 37162 37163 37164 37165 37166 37167 37168 37169 37170 37171 37172 37173 37174 37175 37176 37177 37178 37179 37180 37181 37182 37183 37184 37185 37186 37187 37188 37189 37190 37191 37192 37193 37194 37195 37196 37197 37198 37199 37200 37201 37202 37203 37204 37205 37206 37207 37208 37209 37210 37211 37212 37213 37214 37215 37216 37217 37218 37219 37220 37221 37222 37223 37224 37225 37226 37227 37228 37229 37230 37231 37232 37233 37234 37235 37236 37237 37238 37239 37240 37241 37242 37243 37244 37245 37246 37247 37248 37249 37250 37251 37252 37253 37254 37255 37256 37257 37258 37259 37260 37261 37262 37263 37264 37265 37266 37267 37268 37269 37270 37271 37272 37273 37274 37275 37276 37277 37278 37279 37280 37281 37282 37283 37284 37285 37286 37287 37288 37289 37290 37291 37292 37293 37294 37295 37296 37297 37298 37299 37300 37301 37302 37303 37304 37305 37306 37307 37308 37309 37310 37311 37312 37313 37314 37315 37316 37317 37318 37319 37320 37321 37322 37323 37324 37325 37326 37327 37328 37329 37330 37331 37332 37333 37334 37335 37336 37337 37338 37339 37340 37341 37342 37343 37344 37345 37346 37347 37348 37349 37350 37351 37352 37353 37354 37355 37356 37357 37358 37359 37360 37361 37362 37363 37364 37365 37366 37367 37368 37369 37370 37371 37372 37373 37374 37375 37376 37377 37378 37379 37380 37381 37382 37383 37384 37385 37386 37387 37388 37389 37390 37391 37392 37393 37394 37395 37396 37397 37398 37399 37400 37401 37402 37403 37404 37405 37406 37407 37408 37409 37410 37411 37412 37413 37414 37415 37416 37417 37418 37419 37420 37421 37422 37423 37424 37425 37426 37427 37428 37429 37430 37431 37432 37433 37434 37435 37436 37437 37438 37439 37440 37441 37442 37443 37444 37445 37446 37447 37448 37449 37450 37451 37452 37453 37454 37455 37456 37457 37458 37459 37460 37461 37462 37463 37464 37465 37466 37467 37468 37469 37470 37471 37472 37473 37474 37475 37476 37477 37478 37479 37480 37481 37482 37483 37484 37485 37486 37487 37488 37489 37490 37491 37492 37493 37494 37495 37496 37497 37498 37499 37500 37501 37502 37503 37504 37505 37506 37507 37508 37509 37510 37511 37512 37513 37514 37515 37516 37517 37518 37519 37520 37521 37522 37523 37524 37525 37526 37527 37528 37529 37530 37531 37532 37533 37534 37535 37536 37537 37538 37539 37540 37541 37542 37543 37544 37545 37546 37547 37548 37549 37550 37551 37552 37553 37554 37555 37556 37557 37558 37559 37560 37561 37562 37563 37564 37565 37566 37567 37568 37569 37570 37571 37572 37573 37574 37575 37576 37577 37578 37579 37580 37581 37582 37583 37584 37585 37586 37587 37588 37589 37590 37591 37592 37593 37594 37595 37596 37597 37598 37599 37600 37601 37602 37603 37604 37605 37606 37607 37608 37609 37610 37611 37612 37613 37614 37615 37616 37617 37618 37619 37620 37621 37622 37623 37624 37625 37626 37627 37628 37629 37630 37631 37632 37633 37634 37635 37636 37637 37638 37639 37640 37641 37642 37643 37644 37645 37646 37647 37648 37649 37650 37651 37652 37653 37654 37655 37656 37657 37658 37659 37660 37661 37662 37663 37664 37665 37666 37667 37668 37669 37670 37671 37672 37673 37674 37675 37676 37677 37678 37679 37680 37681 37682 37683 37684 37685 37686 37687 37688 37689 37690 37691 37692 37693 37694 37695 37696 37697 37698 37699 37700 37701 37702 37703 37704 37705 37706 37707 37708 37709 37710 37711 37712 37713 37714 37715 37716 37717 37718 37719 37720 37721 37722 37723 37724 37725 37726 37727 37728 37729 37730 37731 37732 37733 37734 37735 37736 37737 37738 37739 37740 37741 37742 37743 37744 37745 37746 37747 37748 37749 37750 37751 37752 37753 37754 37755 37756 37757 37758 37759 37760 37761 37762 37763 37764 37765 37766 37767 37768 37769 37770 37771 37772 37773 37774 37775 37776 37777 37778 37779 37780 37781 37782 37783 37784 37785 37786 37787 37788 37789 37790 37791 37792 37793 37794 37795 37796 37797 37798 37799 37800 37801 37802 37803 37804 37805 37806 37807 37808 37809 37810 37811 37812 37813 37814 37815 37816 37817 37818 37819 37820 37821 37822 37823 37824 37825 37826 37827 37828 37829 37830 37831 37832 37833 37834 37835 37836 37837 37838 37839 37840 37841 37842 37843 37844 37845 37846 37847 37848 37849 37850 37851 37852 37853 37854 37855 37856 37857 37858 37859 37860 37861 37862 37863 37864 37865 37866 37867 37868 37869 37870 37871 37872 37873 37874 37875 37876 37877 37878 37879 37880 37881 37882 37883 37884 37885 37886 37887 37888 37889 37890 37891 37892 37893 37894 37895 37896 37897 37898 37899 37900 37901 37902 37903 37904 37905 37906 37907 37908 37909 37910 37911 37912 37913 37914 37915 37916 37917 37918 37919 37920 37921 37922 37923 37924 37925 37926 37927 37928 37929 37930 37931 37932 37933 37934 37935 37936 37937 37938 37939 37940 37941 37942 37943 37944 37945 37946 37947 37948 37949 37950 37951 37952 37953 37954 37955 37956 37957 37958 37959 37960 37961 37962 37963 37964 37965 37966 37967 37968 37969 37970 37971 37972 37973 37974 37975 37976 37977 37978 37979 37980 37981 37982 37983 37984 37985 37986 37987 37988 37989 37990 37991 37992 37993 37994 37995 37996 37997 37998 37999 38000 38001 38002 38003 38004 38005 38006 38007 38008 38009 38010 38011 38012 38013 38014 38015 38016 38017 38018 38019 38020 38021 38022 38023 38024 38025 38026 38027 38028 38029 38030 38031 38032 38033 38034 38035 38036 38037 38038 38039 38040 38041 38042 38043 38044 38045 38046 38047 38048 38049 38050 38051 38052 38053 38054 38055 38056 38057 38058 38059 38060 38061 38062 38063 38064 38065 38066 38067 38068 38069 38070 38071 38072 38073 38074 38075 38076 38077 38078 38079 38080 38081 38082 38083 38084 38085 38086 38087 38088 38089 38090 38091 38092 38093 38094 38095 38096 38097 38098 38099 38100 38101 38102 38103 38104 38105 38106 38107 38108 38109 38110 38111 38112 38113 38114 38115 38116 38117 38118 38119 38120 38121 38122 38123 38124 38125 38126 38127 38128 38129 38130 38131 38132 38133 38134 38135 38136 38137 38138 38139 38140 38141 38142 38143 38144 38145 38146 38147 38148 38149 38150 38151 38152 38153 38154 38155 38156 38157 38158 38159 38160 38161 38162 38163 38164 38165 38166 38167 38168 38169 38170 38171 38172 38173 38174 38175 38176 38177 38178 38179 38180 38181 38182 38183 38184 38185 38186 38187 38188 38189 38190 38191 38192 38193 38194 38195 38196 38197 38198 38199 38200 38201 38202 38203 38204 38205 38206 38207 38208 38209 38210 38211 38212 38213 38214 38215 38216 38217 38218 38219 38220 38221 38222 38223 38224 38225 38226 38227 38228 38229 38230 38231 38232 38233 38234 38235 38236 38237 38238 38239 38240 38241 38242 38243 38244 38245 38246 38247 38248 38249 38250 38251 38252 38253 38254 38255 38256 38257 38258 38259 38260 38261 38262 38263 38264 38265 38266 38267 38268 38269 38270 38271 38272 38273 38274 38275 38276 38277 38278 38279 38280 38281 38282 38283 38284 38285 38286 38287 38288 38289 38290 38291 38292 38293 38294 38295 38296 38297 38298 38299 38300 38301 38302 38303 38304 38305 38306 38307 38308 38309 38310 38311 38312 38313 38314 38315 38316 38317 38318 38319 38320 38321 38322 38323 38324 38325 38326 38327 38328 38329 38330 38331 38332 38333 38334 38335 38336 38337 38338 38339 38340 38341 38342 38343 38344 38345 38346 38347 38348 38349 38350 38351 38352 38353 38354 38355 38356 38357 38358 38359 38360 38361 38362 38363 38364 38365 38366 38367 38368 38369 38370 38371 38372 38373 38374 38375 38376 38377 38378 38379 38380 38381 38382 38383 38384 38385 38386 38387 38388 38389 38390 38391 38392 38393 38394 38395 38396 38397 38398 38399 38400 38401 38402 38403 38404 38405 38406 38407 38408 38409 38410 38411 38412 38413 38414 38415 38416 38417 38418 38419 38420 38421 38422 38423 38424 38425 38426 38427 38428 38429 38430 38431 38432 38433 38434 38435 38436 38437 38438 38439 38440 38441 38442 38443 38444 38445 38446 38447 38448 38449 38450 38451 38452 38453 38454 38455 38456 38457 38458 38459 38460 38461 38462 38463 38464 38465 38466 38467 38468 38469 38470 38471 38472 38473 38474 38475 38476 38477 38478 38479 38480 38481 38482 38483 38484 38485 38486 38487 38488 38489 38490 38491 38492 38493 38494 38495 38496 38497 38498 38499 38500 38501 38502 38503 38504 38505 38506 38507 38508 38509 38510 38511 38512 38513 38514 38515 38516 38517 38518 38519 38520 38521 38522 38523 38524 38525 38526 38527 38528 38529 38530 38531 38532 38533 38534 38535 38536 38537 38538 38539 38540 38541 38542 38543 38544 38545 38546 38547 38548 38549 38550 38551 38552 38553 38554 38555 38556 38557 38558 38559 38560 38561 38562 38563 38564 38565 38566 38567 38568 38569 38570 38571 38572 38573 38574 38575 38576 38577 38578 38579 38580 38581 38582 38583 38584 38585 38586 38587 38588 38589 38590 38591 38592 38593 38594 38595 38596 38597 38598 38599 38600 38601 38602 38603 38604 38605 38606 38607 38608 38609 38610 38611 38612 38613 38614 38615 38616 38617 38618 38619 38620 38621 38622 38623 38624 38625 38626 38627 38628 38629 38630 38631 38632 38633 38634 38635 38636 38637 38638 38639 38640 38641 38642 38643 38644 38645 38646 38647 38648 38649 38650 38651 38652 38653 38654 38655 38656 38657 38658 38659 38660 38661 38662 38663 38664 38665 38666 38667 38668 38669 38670 38671 38672 38673 38674 38675 38676 38677 38678 38679 38680 38681 38682 38683 38684 38685 38686 38687 38688 38689 38690 38691 38692 38693 38694 38695 38696 38697 38698 38699 38700 38701 38702 38703 38704 38705 38706 38707 38708 38709 38710 38711 38712 38713 38714 38715 38716 38717 38718 38719 38720 38721 38722 38723 38724 38725 38726 38727 38728 38729 38730 38731 38732 38733 38734 38735 38736 38737 38738 38739 38740 38741 38742 38743 38744 38745 38746 38747 38748 38749 38750 38751 38752 38753 38754 38755 38756 38757 38758 38759 38760 38761 38762 38763 38764 38765 38766 38767 38768 38769 38770 38771 38772 38773 38774 38775 38776 38777 38778 38779 38780 38781 38782 38783 38784 38785 38786 38787 38788 38789 38790 38791 38792 38793 38794 38795 38796 38797 38798 38799 38800 38801 38802 38803 38804 38805 38806 38807 38808 38809 38810 38811 38812 38813 38814 38815 38816 38817 38818 38819 38820 38821 38822 38823 38824 38825 38826 38827 38828 38829 38830 38831 38832 38833 38834 38835 38836 38837 38838 38839 38840 38841 38842 38843 38844 38845 38846 38847 38848 38849 38850 38851 38852 38853 38854 38855 38856 38857 38858 38859 38860 38861 38862 38863 38864 38865 38866 38867 38868 38869 38870 38871 38872 38873 38874 38875 38876 38877 38878 38879 38880 38881 38882 38883 38884 38885 38886 38887 38888 38889 38890 38891 38892 38893 38894 38895 38896 38897 38898 38899 38900 38901 38902 38903 38904 38905 38906 38907 38908 38909 38910 38911 38912 38913 38914 38915 38916 38917 38918 38919 38920 38921 38922 38923 38924 38925 38926 38927 38928 38929 38930 38931 38932 38933 38934 38935 38936 38937 38938 38939 38940 38941 38942 38943 38944 38945 38946 38947 38948 38949 38950 38951 38952 38953 38954 38955 38956 38957 38958 38959 38960 38961 38962 38963 38964 38965 38966 38967 38968 38969 38970 38971 38972 38973 38974 38975 38976 38977 38978 38979 38980 38981 38982 38983 38984 38985 38986 38987 38988 38989 38990 38991 38992 38993 38994 38995 38996 38997 38998 38999 39000 39001 39002 39003 39004 39005 39006 39007 39008 39009 39010 39011 39012 39013 39014 39015 39016 39017 39018 39019 39020 39021 39022 39023 39024 39025 39026 39027 39028 39029 39030 39031 39032 39033 39034 39035 39036 39037 39038 39039 39040 39041 39042 39043 39044 39045 39046 39047 39048 39049 39050 39051 39052 39053 39054 39055 39056 39057 39058 39059 39060 39061 39062 39063 39064 39065 39066 39067 39068 39069 39070 39071 39072 39073 39074 39075 39076 39077 39078 39079 39080 39081 39082 39083 39084 39085 39086 39087 39088 39089 39090 39091 39092 39093 39094 39095 39096 39097 39098 39099 39100 39101 39102 39103 39104 39105 39106 39107 39108 39109 39110 39111 39112 39113 39114 39115 39116 39117 39118 39119 39120 39121 39122 39123 39124 39125 39126 39127 39128 39129 39130 39131 39132 39133 39134 39135 39136 39137 39138 39139 39140 39141 39142 39143 39144 39145 39146 39147 39148 39149 39150 39151 39152 39153 39154 39155 39156 39157 39158 39159 39160 39161 39162 39163 39164 39165 39166 39167 39168 39169 39170 39171 39172 39173 39174 39175 39176 39177 39178 39179 39180 39181 39182 39183 39184 39185 39186 39187 39188 39189 39190 39191 39192 39193 39194 39195 39196 39197 39198 39199 39200 39201 39202 39203 39204 39205 39206 39207 39208 39209 39210 39211 39212 39213 39214 39215 39216 39217 39218 39219 39220 39221 39222 39223 39224 39225 39226 39227 39228 39229 39230 39231 39232 39233 39234 39235 39236 39237 39238 39239 39240 39241 39242 39243 39244 39245 39246 39247 39248 39249 39250 39251 39252 39253 39254 39255 39256 39257 39258 39259 39260 39261 39262 39263 39264 39265 39266 39267 39268 39269 39270 39271 39272 39273 39274 39275 39276 39277 39278 39279 39280 39281 39282 39283 39284 39285 39286 39287 39288 39289 39290 39291 39292 39293 39294 39295 39296 39297 39298 39299 39300 39301 39302 39303 39304 39305 39306 39307 39308 39309 39310 39311 39312 39313 39314 39315 39316 39317 39318 39319 39320 39321 39322 39323 39324 39325 39326 39327 39328 39329 39330 39331 39332 39333 39334 39335 39336 39337 39338 39339 39340 39341 39342 39343 39344 39345 39346 39347 39348 39349 39350 39351 39352 39353 39354 39355 39356 39357 39358 39359 39360 39361 39362 39363 39364 39365 39366 39367 39368 39369 39370 39371 39372 39373 39374 39375 39376 39377 39378 39379 39380 39381 39382 39383 39384 39385 39386 39387 39388 39389 39390 39391 39392 39393 39394 39395 39396 39397 39398 39399 39400 39401 39402 39403 39404 39405 39406 39407 39408 39409 39410 39411 39412 39413 39414 39415 39416 39417 39418 39419 39420 39421 39422 39423 39424 39425 39426 39427 39428 39429 39430 39431 39432 39433 39434 39435 39436 39437 39438 39439 39440 39441 39442 39443 39444 39445 39446 39447 39448 39449 39450 39451 39452 39453 39454 39455 39456 39457 39458 39459 39460 39461 39462 39463 39464 39465 39466 39467 39468 39469 39470 39471 39472 39473 39474 39475 39476 39477 39478 39479 39480 39481 39482 39483 39484 39485 39486 39487 39488 39489 39490 39491 39492 39493 39494 39495 39496 39497 39498 39499 39500 39501 39502 39503 39504 39505 39506 39507 39508 39509 39510 39511 39512 39513 39514 39515 39516 39517 39518 39519 39520 39521 39522 39523 39524 39525 39526 39527 39528 39529 39530 39531 39532 39533 39534 39535 39536 39537 39538 39539 39540 39541 39542 39543 39544 39545 39546 39547 39548 39549 39550 39551 39552 39553 39554 39555 39556 39557 39558 39559 39560 39561 39562 39563 39564 39565 39566 39567 39568 39569 39570 39571 39572 39573 39574 39575 39576 39577 39578 39579 39580 39581 39582 39583 39584 39585 39586 39587 39588 39589 39590 39591 39592 39593 39594 39595 39596 39597 39598 39599 39600 39601 39602 39603 39604 39605 39606 39607 39608 39609 39610 39611 39612 39613 39614 39615 39616 39617 39618 39619 39620 39621 39622 39623 39624 39625 39626 39627 39628 39629 39630 39631 39632 39633 39634 39635 39636 39637 39638 39639 39640 39641 39642 39643 39644 39645 39646 39647 39648 39649 39650 39651 39652 39653 39654 39655 39656 39657 39658 39659 39660 39661 39662 39663 39664 39665 39666 39667 39668 39669 39670 39671 39672 39673 39674 39675 39676 39677 39678 39679 39680 39681 39682 39683 39684 39685 39686 39687 39688 39689 39690 39691 39692 39693 39694 39695 39696 39697 39698 39699 39700 39701 39702 39703 39704 39705 39706 39707 39708 39709 39710 39711 39712 39713 39714 39715 39716 39717 39718 39719 39720 39721 39722 39723 39724 39725 39726 39727 39728 39729 39730 39731 39732 39733 39734 39735 39736 39737 39738 39739 39740 39741 39742 39743 39744 39745 39746 39747 39748 39749 39750 39751 39752 39753 39754 39755 39756 39757 39758 39759 39760 39761 39762 39763 39764 39765 39766 39767 39768 39769 39770 39771 39772 39773 39774 39775 39776 39777 39778 39779 39780 39781 39782 39783 39784 39785 39786 39787 39788 39789 39790 39791 39792 39793 39794 39795 39796 39797 39798 39799 39800 39801 39802 39803 39804 39805 39806 39807 39808 39809 39810 39811 39812 39813 39814 39815 39816 39817 39818 39819 39820 39821 39822 39823 39824 39825 39826 39827 39828 39829 39830 39831 39832 39833 39834 39835 39836 39837 39838 39839 39840 39841 39842 39843 39844 39845 39846 39847 39848 39849 39850 39851 39852 39853 39854 39855 39856 39857 39858 39859 39860 39861 39862 39863 39864 39865 39866 39867 39868 39869 39870 39871 39872 39873 39874 39875 39876 39877 39878 39879 39880 39881 39882 39883 39884 39885 39886 39887 39888 39889 39890 39891 39892 39893 39894 39895 39896 39897 39898 39899 39900 39901 39902 39903 39904 39905 39906 39907 39908 39909 39910 39911 39912 39913 39914 39915 39916 39917 39918 39919 39920 39921 39922 39923 39924 39925 39926 39927 39928 39929 39930 39931 39932 39933 39934 39935 39936 39937 39938 39939 39940 39941 39942 39943 39944 39945 39946 39947 39948 39949 39950 39951 39952 39953 39954 39955 39956 39957 39958 39959 39960 39961 39962 39963 39964 39965 39966 39967 39968 39969 39970 39971 39972 39973 39974 39975 39976 39977 39978 39979 39980 39981 39982 39983 39984 39985 39986 39987 39988 39989 39990 39991 39992 39993 39994 39995 39996 39997 39998 39999 40000 40001 40002 40003 40004 40005 40006 40007 40008 40009 40010 40011 40012 40013 40014 40015 40016 40017 40018 40019 40020 40021 40022 40023 40024 40025 40026 40027 40028 40029 40030 40031 40032 40033 40034 40035 40036 40037 40038 40039 40040 40041 40042 40043 40044 40045 40046 40047 40048 40049 40050 40051 40052 40053 40054 40055 40056 40057 40058 40059 40060 40061 40062 40063 40064 40065 40066 40067 40068 40069 40070 40071 40072 40073 40074 40075 40076 40077 40078 40079 40080 40081 40082 40083 40084 40085 40086 40087 40088 40089 40090 40091 40092 40093 40094 40095 40096 40097 40098 40099 40100 40101 40102 40103 40104 40105 40106 40107 40108 40109 40110 40111 40112 40113 40114 40115 40116 40117 40118 40119 40120 40121 40122 40123 40124 40125 40126 40127 40128 40129 40130 40131 40132 40133 40134 40135 40136 40137 40138 40139 40140 40141 40142 40143 40144 40145 40146 40147 40148 40149 40150 40151 40152 40153 40154 40155 40156 40157 40158 40159 40160 40161 40162 40163 40164 40165 40166 40167 40168 40169 40170 40171 40172 40173 40174 40175 40176 40177 40178 40179 40180 40181 40182 40183 40184 40185 40186 40187 40188 40189 40190 40191 40192 40193 40194 40195 40196 40197 40198 40199 40200 40201 40202 40203 40204 40205 40206 40207 40208 40209 40210 40211 40212 40213 40214 40215 40216 40217 40218 40219 40220 40221 40222 40223 40224 40225 40226 40227 40228 40229 40230 40231 40232 40233 40234 40235 40236 40237 40238 40239 40240 40241 40242 40243 40244 40245 40246 40247 40248 40249 40250 40251 40252 40253 40254 40255 40256 40257 40258 40259 40260 40261 40262 40263 40264 40265 40266 40267 40268 40269 40270 40271 40272 40273 40274 40275 40276 40277 40278 40279 40280 40281 40282 40283 40284 40285 40286 40287 40288 40289 40290 40291 40292 40293 40294 40295 40296 40297 40298 40299 40300 40301 40302 40303 40304 40305 40306 40307 40308 40309 40310 40311 40312 40313 40314 40315 40316 40317 40318 40319 40320 40321 40322 40323 40324 40325 40326 40327 40328 40329 40330 40331 40332 40333 40334 40335 40336 40337 40338 40339 40340 40341 40342 40343 40344 40345 40346 40347 40348 40349 40350 40351 40352 40353 40354 40355 40356 40357 40358 40359 40360 40361 40362 40363 40364 40365 40366 40367 40368 40369 40370 40371 40372 40373 40374 40375 40376 40377 40378 40379 40380 40381 40382 40383 40384 40385 40386 40387 40388 40389 40390 40391 40392 40393 40394 40395 40396 40397 40398 40399 40400 40401 40402 40403 40404 40405 40406 40407 40408 40409 40410 40411 40412 40413 40414 40415 40416 40417 40418 40419 40420 40421 40422 40423 40424 40425 40426 40427 40428 40429 40430 40431 40432 40433 40434 40435 40436 40437 40438 40439 40440 40441 40442 40443 40444 40445 40446 40447 40448 40449 40450 40451 40452 40453 40454 40455 40456 40457 40458 40459 40460 40461 40462 40463 40464 40465 40466 40467 40468 40469 40470 40471 40472 40473 40474 40475 40476 40477 40478 40479 40480 40481 40482 40483 40484 40485 40486 40487 40488 40489 40490 40491 40492 40493 40494 40495 40496 40497 40498 40499 40500 40501 40502 40503 40504 40505 40506 40507 40508 40509 40510 40511 40512 40513 40514 40515 40516 40517 40518 40519 40520 40521 40522 40523 40524 40525 40526 40527 40528 40529 40530 40531 40532 40533 40534 40535 40536 40537 40538 40539 40540 40541 40542 40543 40544 40545 40546 40547 40548 40549 40550 40551 40552 40553 40554 40555 40556 40557 40558 40559 40560 40561 40562 40563 40564 40565 40566 40567 40568 40569 40570 40571 40572 40573 40574 40575 40576 40577 40578 40579 40580 40581 40582 40583 40584 40585 40586 40587 40588 40589 40590 40591 40592 40593 40594 40595 40596 40597 40598 40599 40600 40601 40602 40603 40604 40605 40606 40607 40608 40609 40610 40611 40612 40613 40614 40615 40616 40617 40618 40619 40620 40621 40622 40623 40624 40625 40626 40627 40628 40629 40630 40631 40632 40633 40634 40635 40636 40637 40638 40639 40640 40641 40642 40643 40644 40645 40646 40647 40648 40649 40650 40651 40652 40653 40654 40655 40656 40657 40658 40659 40660 40661 40662 40663 40664 40665 40666 40667 40668 40669 40670 40671 40672 40673 40674 40675 40676 40677 40678 40679 40680 40681 40682 40683 40684 40685 40686 40687 40688 40689 40690 40691 40692 40693 40694 40695 40696 40697 40698 40699 40700 40701 40702 40703 40704 40705 40706 40707 40708 40709 40710 40711 40712 40713 40714 40715 40716 40717 40718 40719 40720 40721 40722 40723 40724 40725 40726 40727 40728 40729 40730 40731 40732 40733 40734 40735 40736 40737 40738 40739 40740 40741 40742 40743 40744 40745 40746 40747 40748 40749 40750 40751 40752 40753 40754 40755 40756 40757 40758 40759 40760 40761 40762 40763 40764 40765 40766 40767 40768 40769 40770 40771 40772 40773 40774 40775 40776 40777 40778 40779 40780 40781 40782 40783 40784 40785 40786 40787 40788 40789 40790 40791 40792 40793 40794 40795 40796 40797 40798 40799 40800 40801 40802 40803 40804 40805 40806 40807 40808 40809 40810 40811 40812 40813 40814 40815 40816 40817 40818 40819 40820 40821 40822 40823 40824 40825 40826 40827 40828 40829 40830 40831 40832 40833 40834 40835 40836 40837 40838 40839 40840 40841 40842 40843 40844 40845 40846 40847 40848 40849 40850 40851 40852 40853 40854 40855 40856 40857 40858 40859 40860 40861 40862 40863 40864 40865 40866 40867 40868 40869 40870 40871 40872 40873 40874 40875 40876 40877 40878 40879 40880 40881 40882 40883 40884 40885 40886 40887 40888 40889 40890 40891 40892 40893 40894 40895 40896 40897 40898 40899 40900 40901 40902 40903 40904 40905 40906 40907 40908 40909 40910 40911 40912 40913 40914 40915 40916 40917 40918 40919 40920 40921 40922 40923 40924 40925 40926 40927 40928 40929 40930 40931 40932 40933 40934 40935 40936 40937 40938 40939 40940 40941 40942 40943 40944 40945 40946 40947 40948 40949 40950 40951 40952 40953 40954 40955 40956 40957 40958 40959 40960 40961 40962 40963 40964 40965 40966 40967 40968 40969 40970 40971 40972 40973 40974 40975 40976 40977 40978 40979 40980 40981 40982 40983 40984 40985 40986 40987 40988 40989 40990 40991 40992 40993 40994 40995 40996 40997 40998 40999 41000 41001 41002 41003 41004 41005 41006 41007 41008 41009 41010 41011 41012 41013 41014 41015 41016 41017 41018 41019 41020 41021 41022 41023 41024 41025 41026 41027 41028 41029 41030 41031 41032 41033 41034 41035 41036 41037 41038 41039 41040 41041 41042 41043 41044 41045 41046 41047 41048 41049 41050 41051 41052 41053 41054 41055 41056 41057 41058 41059 41060 41061 41062 41063 41064 41065 41066 41067 41068 41069 41070 41071 41072 41073 41074 41075 41076 41077 41078 41079 41080 41081 41082 41083 41084 41085 41086 41087 41088 41089 41090 41091 41092 41093 41094 41095 41096 41097 41098 41099 41100 41101 41102 41103 41104 41105 41106 41107 41108 41109 41110 41111 41112 41113 41114 41115 41116 41117 41118 41119 41120 41121 41122 41123 41124 41125 41126 41127 41128 41129 41130 41131 41132 41133 41134 41135 41136 41137 41138 41139 41140 41141 41142 41143 41144 41145 41146 41147 41148 41149 41150 41151 41152 41153 41154 41155 41156 41157 41158 41159 41160 41161 41162 41163 41164 41165 41166 41167 41168 41169 41170 41171 41172 41173 41174 41175 41176 41177 41178 41179 41180 41181 41182 41183 41184 41185 41186 41187 41188 41189 41190 41191 41192 41193 41194 41195 41196 41197 41198 41199 41200 41201 41202 41203 41204 41205 41206 41207 41208 41209 41210 41211 41212 41213 41214 41215 41216 41217 41218 41219 41220 41221 41222 41223 41224 41225 41226 41227 41228 41229 41230 41231 41232 41233 41234 41235 41236 41237 41238 41239 41240 41241 41242 41243 41244 41245 41246 41247 41248 41249 41250 41251 41252 41253 41254 41255 41256 41257 41258 41259 41260 41261 41262 41263 41264 41265 41266 41267 41268 41269 41270 41271 41272 41273 41274 41275 41276 41277 41278 41279 41280 41281 41282 41283 41284 41285 41286 41287 41288 41289 41290 41291 41292 41293 41294 41295 41296 41297 41298 41299 41300 41301 41302 41303 41304 41305 41306 41307 41308 41309 41310 41311 41312 41313 41314 41315 41316 41317 41318 41319 41320 41321 41322 41323 41324 41325 41326 41327 41328 41329 41330 41331 41332 41333 41334 41335 41336 41337 41338 41339 41340 41341 41342 41343 41344 41345 41346 41347 41348 41349 41350 41351 41352 41353 41354 41355 41356 41357 41358 41359 41360 41361 41362 41363 41364 41365 41366 41367 41368 41369 41370 41371 41372 41373 41374 41375 41376 41377 41378 41379 41380 41381 41382 41383 41384 41385 41386 41387 41388 41389 41390 41391 41392 41393 41394 41395 41396 41397 41398 41399 41400 41401 41402 41403 41404 41405 41406 41407 41408 41409 41410 41411 41412 41413 41414 41415 41416 41417 41418 41419 41420 41421 41422 41423 41424 41425 41426 41427 41428 41429 41430 41431 41432 41433 41434 41435 41436 41437 41438 41439 41440 41441 41442 41443 41444 41445 41446 41447 41448 41449 41450 41451 41452 41453 41454 41455 41456 41457 41458 41459 41460 41461 41462 41463 41464 41465 41466 41467 41468 41469 41470 41471 41472 41473 41474 41475 41476 41477 41478 41479 41480 41481 41482 41483 41484 41485 41486 41487 41488 41489 41490 41491 41492 41493 41494 41495 41496 41497 41498 41499 41500 41501 41502 41503 41504 41505 41506 41507 41508 41509 41510 41511 41512 41513 41514 41515 41516 41517 41518 41519 41520 41521 41522 41523 41524 41525 41526 41527 41528 41529 41530 41531 41532 41533 41534 41535 41536 41537 41538 41539 41540 41541 41542 41543 41544 41545 41546 41547 41548 41549 41550 41551 41552 41553 41554 41555 41556 41557 41558 41559 41560 41561 41562 41563 41564 41565 41566 41567 41568 41569 41570 41571 41572 41573 41574 41575 41576 41577 41578 41579 41580 41581 41582 41583 41584 41585 41586 41587 41588 41589 41590 41591 41592 41593 41594 41595 41596 41597 41598 41599 41600 41601 41602 41603 41604 41605 41606 41607 41608 41609 41610 41611 41612 41613 41614 41615 41616 41617 41618 41619 41620 41621 41622 41623 41624 41625 41626 41627 41628 41629 41630 41631 41632 41633 41634 41635 41636 41637 41638 41639 41640 41641 41642 41643 41644 41645 41646 41647 41648 41649 41650 41651 41652 41653 41654 41655 41656 41657 41658 41659 41660 41661 41662 41663 41664 41665 41666 41667 41668 41669 41670 41671 41672 41673 41674 41675 41676 41677 41678 41679 41680 41681 41682 41683 41684 41685 41686 41687 41688 41689 41690 41691 41692 41693 41694 41695 41696 41697 41698 41699 41700 41701 41702 41703 41704 41705 41706 41707 41708 41709 41710 41711 41712 41713 41714 41715 41716 41717 41718 41719 41720 41721 41722 41723 41724 41725 41726 41727 41728 41729 41730 41731 41732 41733 41734 41735 41736 41737 41738 41739 41740 41741 41742 41743 41744 41745 41746 41747 41748 41749 41750 41751 41752 41753 41754 41755 41756 41757 41758 41759 41760 41761 41762 41763 41764 41765 41766 41767 41768 41769 41770 41771 41772 41773 41774 41775 41776 41777 41778 41779 41780 41781 41782 41783 41784 41785 41786 41787 41788 41789 41790 41791 41792 41793 41794 41795 41796 41797 41798 41799 41800 41801 41802 41803 41804 41805 41806 41807 41808 41809 41810 41811 41812 41813 41814 41815 41816 41817 41818 41819 41820 41821 41822 41823 41824 41825 41826 41827 41828 41829 41830 41831 41832 41833 41834 41835 41836 41837 41838 41839 41840 41841 41842 41843 41844 41845 41846 41847 41848 41849 41850 41851 41852 41853 41854 41855 41856 41857 41858 41859 41860 41861 41862 41863 41864 41865 41866 41867 41868 41869 41870 41871 41872 41873 41874 41875 41876 41877 41878 41879 41880 41881 41882 41883 41884 41885 41886 41887 41888 41889 41890 41891 41892 41893 41894 41895 41896 41897 41898 41899 41900 41901 41902 41903 41904 41905 41906 41907 41908 41909 41910 41911 41912 41913 41914 41915 41916 41917 41918 41919 41920 41921 41922 41923 41924 41925 41926 41927 41928 41929 41930 41931 41932 41933 41934 41935 41936 41937 41938 41939 41940 41941 41942 41943 41944 41945 41946 41947 41948 41949 41950 41951 41952 41953 41954 41955 41956 41957 41958 41959 41960 41961 41962 41963 41964 41965 41966 41967 41968 41969 41970 41971 41972 41973 41974 41975 41976 41977 41978 41979 41980 41981 41982 41983 41984 41985 41986 41987 41988 41989 41990 41991 41992 41993 41994 41995 41996 41997 41998 41999 42000 42001 42002 42003 42004 42005 42006 42007 42008 42009 42010 42011 42012 42013 42014 42015 42016 42017 42018 42019 42020 42021 42022 42023 42024 42025 42026 42027 42028 42029 42030 42031 42032 42033 42034 42035 42036 42037 42038 42039 42040 42041 42042 42043 42044 42045 42046 42047 42048 42049 42050 42051 42052 42053 42054 42055 42056 42057 42058 42059 42060 42061 42062 42063 42064 42065 42066 42067 42068 42069 42070 42071 42072 42073 42074 42075 42076 42077 42078 42079 42080 42081 42082 42083 42084 42085 42086 42087 42088 42089 42090 42091 42092 42093 42094 42095 42096 42097 42098 42099 42100 42101 42102 42103 42104 42105 42106 42107 42108 42109 42110 42111 42112 42113 42114 42115 42116 42117 42118 42119 42120 42121 42122 42123 42124 42125 42126 42127 42128 42129 42130 42131 42132 42133 42134 42135 42136 42137 42138 42139 42140 42141 42142 42143 42144 42145 42146 42147 42148 42149 42150 42151 42152 42153 42154 42155 42156 42157 42158 42159 42160 42161 42162 42163 42164 42165 42166 42167 42168 42169 42170 42171 42172 42173 42174 42175 42176 42177 42178 42179 42180 42181 42182 42183 42184 42185 42186 42187 42188 42189 42190 42191 42192 42193 42194 42195 42196 42197 42198 42199 42200 42201 42202 42203 42204 42205 42206 42207 42208 42209 42210 42211 42212 42213 42214 42215 42216 42217 42218 42219 42220 42221 42222 42223 42224 42225 42226 42227 42228 42229 42230 42231 42232 42233 42234 42235 42236 42237 42238 42239 42240 42241 42242 42243 42244 42245 42246 42247 42248 42249 42250 42251 42252 42253 42254 42255 42256 42257 42258 42259 42260 42261 42262 42263 42264 42265 42266 42267 42268 42269 42270 42271 42272 42273 42274 42275 42276 42277 42278 42279 42280 42281 42282 42283 42284 42285 42286 42287 42288 42289 42290 42291 42292 42293 42294 42295 42296 42297 42298 42299 42300 42301 42302 42303 42304 42305 42306 42307 42308 42309 42310 42311 42312 42313 42314 42315 42316 42317 42318 42319 42320 42321 42322 42323 42324 42325 42326 42327 42328 42329 42330 42331 42332 42333 42334 42335 42336 42337 42338 42339 42340 42341 42342 42343 42344 42345 42346 42347 42348 42349 42350 42351 42352 42353 42354 42355 42356 42357 42358 42359 42360 42361 42362 42363 42364 42365 42366 42367 42368 42369 42370 42371 42372 42373 42374 42375 42376 42377 42378 42379 42380 42381 42382 42383 42384 42385 42386 42387 42388 42389 42390 42391 42392 42393 42394 42395 42396 42397 42398 42399 42400 42401 42402 42403 42404 42405 42406 42407 42408 42409 42410 42411 42412 42413 42414 42415 42416 42417 42418 42419 42420 42421 42422 42423 42424 42425 42426 42427 42428 42429 42430 42431 42432 42433 42434 42435 42436 42437 42438 42439 42440 42441 42442 42443 42444 42445 42446 42447 42448 42449 42450 42451 42452 42453 42454 42455 42456 42457 42458 42459 42460 42461 42462 42463 42464 42465 42466 42467 42468 42469 42470 42471 42472 42473 42474 42475 42476 42477 42478 42479 42480 42481 42482 42483 42484 42485 42486 42487 42488 42489 42490 42491 42492 42493 42494 42495 42496 42497 42498 42499 42500 42501 42502 42503 42504 42505 42506 42507 42508 42509 42510 42511 42512 42513 42514 42515 42516 42517 42518 42519 42520 42521 42522 42523 42524 42525 42526 42527 42528 42529 42530 42531 42532 42533 42534 42535 42536 42537 42538 42539 42540 42541 42542 42543 42544 42545 42546 42547 42548 42549 42550 42551 42552 42553 42554 42555 42556 42557 42558 42559 42560 42561 42562 42563 42564 42565 42566 42567 42568 42569 42570 42571 42572 42573 42574 42575 42576 42577 42578 42579 42580 42581 42582 42583 42584 42585 42586 42587 42588 42589 42590 42591 42592 42593 42594 42595 42596 42597 42598 42599 42600 42601 42602 42603 42604 42605 42606 42607 42608 42609 42610 42611 42612 42613 42614 42615 42616 42617 42618 42619 42620 42621 42622 42623 42624 42625 42626 42627 42628 42629 42630 42631 42632 42633 42634 42635 42636 42637 42638 42639 42640 42641 42642 42643 42644 42645 42646 42647 42648 42649 42650 42651 42652 42653 42654 42655 42656 42657 42658 42659 42660 42661 42662 42663 42664 42665 42666 42667 42668 42669 42670 42671 42672 42673 42674 42675 42676 42677 42678 42679 42680 42681 42682 42683 42684 42685 42686 42687 42688 42689 42690 42691 42692 42693 42694 42695 42696 42697 42698 42699 42700 42701 42702 42703 42704 42705 42706 42707 42708 42709 42710 42711 42712 42713 42714 42715 42716 42717 42718 42719 42720 42721 42722 42723 42724 42725 42726 42727 42728 42729 42730 42731 42732 42733 42734 42735 42736 42737 42738 42739 42740 42741 42742 42743 42744 42745 42746 42747 42748 42749 42750 42751 42752 42753 42754 42755 42756 42757 42758 42759 42760 42761 42762 42763 42764 42765 42766 42767 42768 42769 42770 42771 42772 42773 42774 42775 42776 42777 42778 42779 42780 42781 42782 42783 42784 42785 42786 42787 42788 42789 42790 42791 42792 42793 42794 42795 42796 42797 42798 42799 42800 42801 42802 42803 42804 42805 42806 42807 42808 42809 42810 42811 42812 42813 42814 42815 42816 42817 42818 42819 42820 42821 42822 42823 42824 42825 42826 42827 42828 42829 42830 42831 42832 42833 42834 42835 42836 42837 42838 42839 42840 42841 42842 42843 42844 42845 42846 42847 42848 42849 42850 42851 42852 42853 42854 42855 42856 42857 42858 42859 42860 42861 42862 42863 42864 42865 42866 42867 42868 42869 42870 42871 42872 42873 42874 42875 42876 42877 42878 42879 42880 42881 42882 42883 42884 42885 42886 42887 42888 42889 42890 42891 42892 42893 42894 42895 42896 42897 42898 42899 42900 42901 42902 42903 42904 42905 42906 42907 42908 42909 42910 42911 42912 42913 42914 42915 42916 42917 42918 42919 42920 42921 42922 42923 42924 42925 42926 42927 42928 42929 42930 42931 42932 42933 42934 42935 42936 42937 42938 42939 42940 42941 42942 42943 42944 42945 42946 42947 42948 42949 42950 42951 42952 42953 42954 42955 42956 42957 42958 42959 42960 42961 42962 42963 42964 42965 42966 42967 42968 42969 42970 42971 42972 42973 42974 42975 42976 42977 42978 42979 42980 42981 42982 42983 42984 42985 42986 42987 42988 42989 42990 42991 42992 42993 42994 42995 42996 42997 42998 42999 43000 43001 43002 43003 43004 43005 43006 43007 43008 43009 43010 43011 43012 43013 43014 43015 43016 43017 43018 43019 43020 43021 43022 43023 43024 43025 43026 43027 43028 43029 43030 43031 43032 43033 43034 43035 43036 43037 43038 43039 43040 43041 43042 43043 43044 43045 43046 43047 43048 43049 43050 43051 43052 43053 43054 43055 43056 43057 43058 43059 43060 43061 43062 43063 43064 43065 43066 43067 43068 43069 43070 43071 43072 43073 43074 43075 43076 43077 43078 43079 43080 43081 43082 43083 43084 43085 43086 43087 43088 43089 43090 43091 43092 43093 43094 43095 43096 43097 43098 43099 43100 43101 43102 43103 43104 43105 43106 43107 43108 43109 43110 43111 43112 43113 43114 43115 43116 43117 43118 43119 43120 43121 43122 43123 43124 43125 43126 43127 43128 43129 43130 43131 43132 43133 43134 43135 43136 43137 43138 43139 43140 43141 43142 43143 43144 43145 43146 43147 43148 43149 43150 43151 43152 43153 43154 43155 43156 43157 43158 43159 43160 43161 43162 43163 43164 43165 43166 43167 43168 43169 43170 43171 43172 43173 43174 43175 43176 43177 43178 43179 43180 43181 43182 43183 43184 43185 43186 43187 43188 43189 43190 43191 43192 43193 43194 43195 43196 43197 43198 43199 43200 43201 43202 43203 43204 43205 43206 43207 43208 43209 43210 43211 43212 43213 43214 43215 43216 43217 43218 43219 43220 43221 43222 43223 43224 43225 43226 43227 43228 43229 43230 43231 43232 43233 43234 43235 43236 43237 43238 43239 43240 43241 43242 43243 43244 43245 43246 43247 43248 43249 43250 43251 43252 43253 43254 43255 43256 43257 43258 43259 43260 43261 43262 43263 43264 43265 43266 43267 43268 43269 43270 43271 43272 43273 43274 43275 43276 43277 43278 43279 43280 43281 43282 43283 43284 43285 43286 43287 43288 43289 43290 43291 43292 43293 43294 43295 43296 43297 43298 43299 43300 43301 43302 43303 43304 43305 43306 43307 43308 43309 43310 43311 43312 43313 43314 43315 43316 43317 43318 43319 43320 43321 43322 43323 43324 43325 43326 43327 43328 43329 43330 43331 43332 43333 43334 43335 43336 43337 43338 43339 43340 43341 43342 43343 43344 43345 43346 43347 43348 43349 43350 43351 43352 43353 43354 43355 43356 43357 43358 43359 43360 43361 43362 43363 43364 43365 43366 43367 43368 43369 43370 43371 43372 43373 43374 43375 43376 43377 43378 43379 43380 43381 43382 43383 43384 43385 43386 43387 43388 43389 43390 43391 43392 43393 43394 43395 43396 43397 43398 43399 43400 43401 43402 43403 43404 43405 43406 43407 43408 43409 43410 43411 43412 43413 43414 43415 43416 43417 43418 43419 43420 43421 43422 43423 43424 43425 43426 43427 43428 43429 43430 43431 43432 43433 43434 43435 43436 43437 43438 43439 43440 43441 43442 43443 43444 43445 43446 43447 43448 43449 43450 43451 43452 43453 43454 43455 43456 43457 43458 43459 43460 43461 43462 43463 43464 43465 43466 43467 43468 43469 43470 43471 43472 43473 43474 43475 43476 43477 43478 43479 43480 43481 43482 43483 43484 43485 43486 43487 43488 43489 43490 43491 43492 43493 43494 43495 43496 43497 43498 43499 43500 43501 43502 43503 43504 43505 43506 43507 43508 43509 43510 43511 43512 43513 43514 43515 43516 43517 43518 43519 43520 43521 43522 43523 43524 43525 43526 43527 43528 43529 43530 43531 43532 43533 43534 43535 43536 43537 43538 43539 43540 43541 43542 43543 43544 43545 43546 43547 43548 43549 43550 43551 43552 43553 43554 43555 43556 43557 43558 43559 43560 43561 43562 43563 43564 43565 43566 43567 43568 43569 43570 43571 43572 43573 43574 43575 43576 43577 43578 43579 43580 43581 43582 43583 43584 43585 43586 43587 43588 43589 43590 43591 43592 43593 43594 43595 43596 43597 43598 43599 43600 43601 43602 43603 43604 43605 43606 43607 43608 43609 43610 43611 43612 43613 43614 43615 43616 43617 43618 43619 43620 43621 43622 43623 43624 43625 43626 43627 43628 43629 43630 43631 43632 43633 43634 43635 43636 43637 43638 43639 43640 43641 43642 43643 43644 43645 43646 43647 43648 43649 43650 43651 43652 43653 43654 43655 43656 43657 43658 43659 43660 43661 43662 43663 43664 43665 43666 43667 43668 43669 43670 43671 43672 43673 43674 43675 43676 43677 43678 43679 43680 43681 43682 43683 43684 43685 43686 43687 43688 43689 43690 43691 43692 43693 43694 43695 43696 43697 43698 43699 43700 43701 43702 43703 43704 43705 43706 43707 43708 43709 43710 43711 43712 43713 43714 43715 43716 43717 43718 43719 43720 43721 43722 43723 43724 43725 43726 43727 43728 43729 43730 43731 43732 43733 43734 43735 43736 43737 43738 43739 43740 43741 43742 43743 43744 43745 43746 43747 43748 43749 43750 43751 43752 43753 43754 43755 43756 43757 43758 43759 43760 43761 43762 43763 43764 43765 43766 43767 43768 43769 43770 43771 43772 43773 43774 43775 43776 43777 43778 43779 43780 43781 43782 43783 43784 43785 43786 43787 43788 43789 43790 43791 43792 43793 43794 43795 43796 43797 43798 43799 43800 43801 43802 43803 43804 43805 43806 43807 43808 43809 43810 43811 43812 43813 43814 43815 43816 43817 43818 43819 43820 43821 43822 43823 43824 43825 43826 43827 43828 43829 43830 43831 43832 43833 43834 43835 43836 43837 43838 43839 43840 43841 43842 43843 43844 43845 43846 43847 43848 43849 43850 43851 43852 43853 43854 43855 43856 43857 43858 43859 43860 43861 43862 43863 43864 43865 43866 43867 43868 43869 43870 43871 43872 43873 43874 43875 43876 43877 43878 43879 43880 43881 43882 43883 43884 43885 43886 43887 43888 43889 43890 43891 43892 43893 43894 43895 43896 43897 43898 43899 43900 43901 43902 43903 43904 43905 43906 43907 43908 43909 43910 43911 43912 43913 43914 43915 43916 43917 43918 43919 43920 43921 43922 43923 43924 43925 43926 43927 43928 43929 43930 43931 43932 43933 43934 43935 43936 43937 43938 43939 43940 43941 43942 43943 43944 43945 43946 43947 43948 43949 43950 43951 43952 43953 43954 43955 43956 43957 43958 43959 43960 43961 43962 43963 43964 43965 43966 43967 43968 43969 43970 43971 43972 43973 43974 43975 43976 43977 43978 43979 43980 43981 43982 43983 43984 43985 43986 43987 43988 43989 43990 43991 43992 43993 43994 43995 43996 43997 43998 43999 44000 44001 44002 44003 44004 44005 44006 44007 44008 44009 44010 44011 44012 44013 44014 44015 44016 44017 44018 44019 44020 44021 44022 44023 44024 44025 44026 44027 44028 44029 44030 44031 44032 44033 44034 44035 44036 44037 44038 44039 44040 44041 44042 44043 44044 44045 44046 44047 44048 44049 44050 44051 44052 44053 44054 44055 44056 44057 44058 44059 44060 44061 44062 44063 44064 44065 44066 44067 44068 44069 44070 44071 44072 44073 44074 44075 44076 44077 44078 44079 44080 44081 44082 44083 44084 44085 44086 44087 44088 44089 44090 44091 44092 44093 44094 44095 44096 44097 44098 44099 44100 44101 44102 44103 44104 44105 44106 44107 44108 44109 44110 44111 44112 44113 44114 44115 44116 44117 44118 44119 44120 44121 44122 44123 44124 44125 44126 44127 44128 44129 44130 44131 44132 44133 44134 44135 44136 44137 44138 44139 44140 44141 44142 44143 44144 44145 44146 44147 44148 44149 44150 44151 44152 44153 44154 44155 44156 44157 44158 44159 44160 44161 44162 44163 44164 44165 44166 44167 44168 44169 44170 44171 44172 44173 44174 44175 44176 44177 44178 44179 44180 44181 44182 44183 44184 44185 44186 44187 44188 44189 44190 44191 44192 44193 44194 44195 44196 44197 44198 44199 44200 44201 44202 44203 44204 44205 44206 44207 44208 44209 44210 44211 44212 44213 44214 44215 44216 44217 44218 44219 44220 44221 44222 44223 44224 44225 44226 44227 44228 44229 44230 44231 44232 44233 44234 44235 44236 44237 44238 44239 44240 44241 44242 44243 44244 44245 44246 44247 44248 44249 44250 44251 44252 44253 44254 44255 44256 44257 44258 44259 44260 44261 44262 44263 44264 44265 44266 44267 44268 44269 44270 44271 44272 44273 44274 44275 44276 44277 44278 44279 44280 44281 44282 44283 44284 44285 44286 44287 44288 44289 44290 44291 44292 44293 44294 44295 44296 44297 44298 44299 44300 44301 44302 44303 44304 44305 44306 44307 44308 44309 44310 44311 44312 44313 44314 44315 44316 44317 44318 44319 44320 44321 44322 44323 44324 44325 44326 44327 44328 44329 44330 44331 44332 44333 44334 44335 44336 44337 44338 44339 44340 44341 44342 44343 44344 44345 44346 44347 44348 44349 44350 44351 44352 44353 44354 44355 44356 44357 44358 44359 44360 44361 44362 44363 44364 44365 44366 44367 44368 44369 44370 44371 44372 44373 44374 44375 44376 44377 44378 44379 44380 44381 44382 44383 44384 44385 44386 44387 44388 44389 44390 44391 44392 44393 44394 44395 44396 44397 44398 44399 44400 44401 44402 44403 44404 44405 44406 44407 44408 44409 44410 44411 44412 44413 44414 44415 44416 44417 44418 44419 44420 44421 44422 44423 44424 44425 44426 44427 44428 44429 44430 44431 44432 44433 44434 44435 44436 44437 44438 44439 44440 44441 44442 44443 44444 44445 44446 44447 44448 44449 44450 44451 44452 44453 44454 44455 44456 44457 44458 44459 44460 44461 44462 44463 44464 44465 44466 44467 44468 44469 44470 44471 44472 44473 44474 44475 44476 44477 44478 44479 44480 44481 44482 44483 44484 44485 44486 44487 44488 44489 44490 44491 44492 44493 44494 44495 44496 44497 44498 44499 44500 44501 44502 44503 44504 44505 44506 44507 44508 44509 44510 44511 44512 44513 44514 44515 44516 44517 44518 44519 44520 44521 44522 44523 44524 44525 44526 44527 44528 44529 44530 44531 44532 44533 44534 44535 44536 44537 44538 44539 44540 44541 44542 44543 44544 44545 44546 44547 44548 44549 44550 44551 44552 44553 44554 44555 44556 44557 44558 44559 44560 44561 44562 44563 44564 44565 44566 44567 44568 44569 44570 44571 44572 44573 44574 44575 44576 44577 44578 44579 44580 44581 44582 44583 44584 44585 44586 44587 44588 44589 44590 44591 44592 44593 44594 44595 44596 44597 44598 44599 44600 44601 44602 44603 44604 44605 44606 44607 44608 44609 44610 44611 44612 44613 44614 44615 44616 44617 44618 44619 44620 44621 44622 44623 44624 44625 44626 44627 44628 44629 44630 44631 44632 44633 44634 44635 44636 44637 44638 44639 44640 44641 44642 44643 44644 44645 44646 44647 44648 44649 44650 44651 44652 44653 44654 44655 44656 44657 44658 44659 44660 44661 44662 44663 44664 44665 44666 44667 44668 44669 44670 44671 44672 44673 44674 44675 44676 44677 44678 44679 44680 44681 44682 44683 44684 44685 44686 44687 44688 44689 44690 44691 44692 44693 44694 44695 44696 44697 44698 44699 44700 44701 44702 44703 44704 44705 44706 44707 44708 44709 44710 44711 44712 44713 44714 44715 44716 44717 44718 44719 44720 44721 44722 44723 44724 44725 44726 44727 44728 44729 44730 44731 44732 44733 44734 44735 44736 44737 44738 44739 44740 44741 44742 44743 44744 44745 44746 44747 44748 44749 44750 44751 44752 44753 44754 44755 44756 44757 44758 44759 44760 44761 44762 44763 44764 44765 44766 44767 44768 44769 44770 44771 44772 44773 44774 44775 44776 44777 44778 44779 44780 44781 44782 44783 44784 44785 44786 44787 44788 44789 44790 44791 44792 44793 44794 44795 44796 44797 44798 44799 44800 44801 44802 44803 44804 44805 44806 44807 44808 44809 44810 44811 44812 44813 44814 44815 44816 44817 44818 44819 44820 44821 44822 44823 44824 44825 44826 44827 44828 44829 44830 44831 44832 44833 44834 44835 44836 44837 44838 44839 44840 44841 44842 44843 44844 44845 44846 44847 44848 44849 44850 44851 44852 44853 44854 44855 44856 44857 44858 44859 44860 44861 44862 44863 44864 44865 44866 44867 44868 44869 44870 44871 44872 44873 44874 44875 44876 44877 44878 44879 44880 44881 44882 44883 44884 44885 44886 44887 44888 44889 44890 44891 44892 44893 44894 44895 44896 44897 44898 44899 44900 44901 44902 44903 44904 44905 44906 44907 44908 44909 44910 44911 44912 44913 44914 44915 44916 44917 44918 44919 44920 44921 44922 44923 44924 44925 44926 44927 44928 44929 44930 44931 44932 44933 44934 44935 44936 44937 44938 44939 44940 44941 44942 44943 44944 44945 44946 44947 44948 44949 44950 44951 44952 44953 44954 44955 44956 44957 44958 44959 44960 44961 44962 44963 44964 44965 44966 44967 44968 44969 44970 44971 44972 44973 44974 44975 44976 44977 44978 44979 44980 44981 44982 44983 44984 44985 44986 44987 44988 44989 44990 44991 44992 44993 44994 44995 44996 44997 44998 44999 45000 45001 45002 45003 45004 45005 45006 45007 45008 45009 45010 45011 45012 45013 45014 45015 45016 45017 45018 45019 45020 45021 45022 45023 45024 45025 45026 45027 45028 45029 45030 45031 45032 45033 45034 45035 45036 45037 45038 45039 45040 45041 45042 45043 45044 45045 45046 45047 45048 45049 45050 45051 45052 45053 45054 45055 45056 45057 45058 45059 45060 45061 45062 45063 45064 45065 45066 45067 45068 45069 45070 45071 45072 45073 45074 45075 45076 45077 45078 45079 45080 45081 45082 45083 45084 45085 45086 45087 45088 45089 45090 45091 45092 45093 45094 45095 45096 45097 45098 45099 45100 45101 45102 45103 45104 45105 45106 45107 45108 45109 45110 45111 45112 45113 45114 45115 45116 45117 45118 45119 45120 45121 45122 45123 45124 45125 45126 45127 45128 45129 45130 45131 45132 45133 45134 45135 45136 45137 45138 45139 45140 45141 45142 45143 45144 45145 45146 45147 45148 45149 45150 45151 45152 45153 45154 45155 45156 45157 45158 45159 45160 45161 45162 45163 45164 45165 45166 45167 45168 45169 45170 45171 45172 45173 45174 45175 45176 45177 45178 45179 45180 45181 45182 45183 45184 45185 45186 45187 45188 45189 45190 45191 45192 45193 45194 45195 45196 45197 45198 45199 45200 45201 45202 45203 45204 45205 45206 45207 45208 45209 45210 45211 45212 45213 45214 45215 45216 45217 45218 45219 45220 45221 45222 45223 45224 45225 45226 45227 45228 45229 45230 45231 45232 45233 45234 45235 45236 45237 45238 45239 45240 45241 45242 45243 45244 45245 45246 45247 45248 45249 45250 45251 45252 45253 45254 45255 45256 45257 45258 45259 45260 45261 45262 45263 45264 45265 45266 45267 45268 45269 45270 45271 45272 45273 45274 45275 45276 45277 45278 45279 45280 45281 45282 45283 45284 45285 45286 45287 45288 45289 45290 45291 45292 45293 45294 45295 45296 45297 45298 45299 45300 45301 45302 45303 45304 45305 45306 45307 45308 45309 45310 45311 45312 45313 45314 45315 45316 45317 45318 45319 45320 45321 45322 45323 45324 45325 45326 45327 45328 45329 45330 45331 45332 45333 45334 45335 45336 45337 45338 45339 45340 45341 45342 45343 45344 45345 45346 45347 45348 45349 45350 45351 45352 45353 45354 45355 45356 45357 45358 45359 45360 45361 45362 45363 45364 45365 45366 45367 45368 45369 45370 45371 45372 45373 45374 45375 45376 45377 45378 45379 45380 45381 45382 45383 45384 45385 45386 45387 45388 45389 45390 45391 45392 45393 45394 45395 45396 45397 45398 45399 45400 45401 45402 45403 45404 45405 45406 45407 45408 45409 45410 45411 45412 45413 45414 45415 45416 45417 45418 45419 45420 45421 45422 45423 45424 45425 45426 45427 45428 45429 45430 45431 45432 45433 45434 45435 45436 45437 45438 45439 45440 45441 45442 45443 45444 45445 45446 45447 45448 45449 45450 45451 45452 45453 45454 45455 45456 45457 45458 45459 45460 45461 45462 45463 45464 45465 45466 45467 45468 45469 45470 45471 45472 45473 45474 45475 45476 45477 45478 45479 45480 45481 45482 45483 45484 45485 45486 45487 45488 45489 45490 45491 45492 45493 45494 45495 45496 45497 45498 45499 45500 45501 45502 45503 45504 45505 45506 45507 45508 45509 45510 45511 45512 45513 45514 45515 45516 45517 45518 45519 45520 45521 45522 45523 45524 45525 45526 45527 45528 45529 45530 45531 45532 45533 45534 45535 45536 45537 45538 45539 45540 45541 45542 45543 45544 45545 45546 45547 45548 45549 45550 45551 45552 45553 45554 45555 45556 45557 45558 45559 45560 45561 45562 45563 45564 45565 45566 45567 45568 45569 45570 45571 45572 45573 45574 45575 45576 45577 45578 45579 45580 45581 45582 45583 45584 45585 45586 45587 45588 45589 45590 45591 45592 45593 45594 45595 45596 45597 45598 45599 45600 45601 45602 45603 45604 45605 45606 45607 45608 45609 45610 45611 45612 45613 45614 45615 45616 45617 45618 45619 45620 45621 45622 45623 45624 45625 45626 45627 45628 45629 45630 45631 45632 45633 45634 45635 45636 45637 45638 45639 45640 45641 45642 45643 45644 45645 45646 45647 45648 45649 45650 45651 45652 45653 45654 45655 45656 45657 45658 45659 45660 45661 45662 45663 45664 45665 45666 45667 45668 45669 45670 45671 45672 45673 45674 45675 45676 45677 45678 45679 45680 45681 45682 45683 45684 45685 45686 45687 45688 45689 45690 45691 45692 45693 45694 45695 45696 45697 45698 45699 45700 45701 45702 45703 45704 45705 45706 45707 45708 45709 45710 45711 45712 45713 45714 45715 45716 45717 45718 45719 45720 45721 45722 45723 45724 45725 45726 45727 45728 45729 45730 45731 45732 45733 45734 45735 45736 45737 45738 45739 45740 45741 45742 45743 45744 45745 45746 45747 45748 45749 45750 45751 45752 45753 45754 45755 45756 45757 45758 45759 45760 45761 45762 45763 45764 45765 45766 45767 45768 45769 45770 45771 45772 45773 45774 45775 45776 45777 45778 45779 45780 45781 45782 45783 45784 45785 45786 45787 45788 45789 45790 45791 45792 45793 45794 45795 45796 45797 45798 45799 45800 45801 45802 45803 45804 45805 45806 45807 45808 45809 45810 45811 45812 45813 45814 45815 45816 45817 45818 45819 45820 45821 45822 45823 45824 45825 45826 45827 45828 45829 45830 45831 45832 45833 45834 45835 45836 45837 45838 45839 45840 45841 45842 45843 45844 45845 45846 45847 45848 45849 45850 45851 45852 45853 45854 45855 45856 45857 45858 45859 45860 45861 45862 45863 45864 45865 45866 45867 45868 45869 45870 45871 45872 45873 45874 45875 45876 45877 45878 45879 45880 45881 45882 45883 45884 45885 45886 45887 45888 45889 45890 45891 45892 45893 45894 45895 45896 45897 45898 45899 45900 45901 45902 45903 45904 45905 45906 45907 45908 45909 45910 45911 45912 45913 45914 45915 45916 45917 45918 45919 45920 45921 45922 45923 45924 45925 45926 45927 45928 45929 45930 45931 45932 45933 45934 45935 45936 45937 45938 45939 45940 45941 45942 45943 45944 45945 45946 45947 45948 45949 45950 45951 45952 45953 45954 45955 45956 45957 45958 45959 45960 45961 45962 45963 45964 45965 45966 45967 45968 45969 45970 45971 45972 45973 45974 45975 45976 45977 45978 45979 45980 45981 45982 45983 45984 45985 45986 45987 45988 45989 45990 45991 45992 45993 45994 45995 45996 45997 45998 45999 46000 46001 46002 46003 46004 46005 46006 46007 46008 46009 46010 46011 46012 46013 46014 46015 46016 46017 46018 46019 46020 46021 46022 46023 46024 46025 46026 46027 46028 46029 46030 46031 46032 46033 46034 46035 46036 46037 46038 46039 46040 46041 46042 46043 46044 46045 46046 46047 46048 46049 46050 46051 46052 46053 46054 46055 46056 46057 46058 46059 46060 46061 46062 46063 46064 46065 46066 46067 46068 46069 46070 46071 46072 46073 46074 46075 46076 46077 46078 46079 46080 46081 46082 46083 46084 46085 46086 46087 46088 46089 46090 46091 46092 46093 46094 46095 46096 46097 46098 46099 46100 46101 46102 46103 46104 46105 46106 46107 46108 46109 46110 46111 46112 46113 46114 46115 46116 46117 46118 46119 46120 46121 46122 46123 46124 46125 46126 46127 46128 46129 46130 46131 46132 46133 46134 46135 46136 46137 46138 46139 46140 46141 46142 46143 46144 46145 46146 46147 46148 46149 46150 46151 46152 46153 46154 46155 46156 46157 46158 46159 46160 46161 46162 46163 46164 46165 46166 46167 46168 46169 46170 46171 46172 46173 46174 46175 46176 46177 46178 46179 46180 46181 46182 46183 46184 46185 46186 46187 46188 46189 46190 46191 46192 46193 46194 46195 46196 46197 46198 46199 46200 46201 46202 46203 46204 46205 46206 46207 46208 46209 46210 46211 46212 46213 46214 46215 46216 46217 46218 46219 46220 46221 46222 46223 46224 46225 46226 46227 46228 46229 46230 46231 46232 46233 46234 46235 46236 46237 46238 46239 46240 46241 46242 46243 46244 46245 46246 46247 46248 46249 46250 46251 46252 46253 46254 46255 46256 46257 46258 46259 46260 46261 46262 46263 46264 46265 46266 46267 46268 46269 46270 46271 46272 46273 46274 46275 46276 46277 46278 46279 46280 46281 46282 46283 46284 46285 46286 46287 46288 46289 46290 46291 46292 46293 46294 46295 46296 46297 46298 46299 46300 46301 46302 46303 46304 46305 46306 46307 46308 46309 46310 46311 46312 46313 46314 46315 46316 46317 46318 46319 46320 46321 46322 46323 46324 46325 46326 46327 46328 46329 46330 46331 46332 46333 46334 46335 46336 46337 46338 46339 46340 46341 46342 46343 46344 46345 46346 46347 46348 46349 46350 46351 46352 46353 46354 46355 46356 46357 46358 46359 46360 46361 46362 46363 46364 46365 46366 46367 46368 46369 46370 46371 46372 46373 46374 46375 46376 46377 46378 46379 46380 46381 46382 46383 46384 46385 46386 46387 46388 46389 46390 46391 46392 46393 46394 46395 46396 46397 46398 46399 46400 46401 46402 46403 46404 46405 46406 46407 46408 46409 46410 46411 46412 46413 46414 46415 46416 46417 46418 46419 46420 46421 46422 46423 46424 46425 46426 46427 46428 46429 46430 46431 46432 46433 46434 46435 46436 46437 46438 46439 46440 46441 46442 46443 46444 46445 46446 46447 46448 46449 46450 46451 46452 46453 46454 46455 46456 46457 46458 46459 46460 46461 46462 46463 46464 46465 46466 46467 46468 46469 46470 46471 46472 46473 46474 46475 46476 46477 46478 46479 46480 46481 46482 46483 46484 46485 46486 46487 46488 46489 46490 46491 46492 46493 46494 46495 46496 46497 46498 46499 46500 46501 46502 46503 46504 46505 46506 46507 46508 46509 46510 46511 46512 46513 46514 46515 46516 46517 46518 46519 46520 46521 46522 46523 46524 46525 46526 46527 46528 46529 46530 46531 46532 46533 46534 46535 46536 46537 46538 46539 46540 46541 46542 46543 46544 46545 46546 46547 46548 46549 46550 46551 46552 46553 46554 46555 46556 46557 46558 46559 46560 46561 46562 46563 46564 46565 46566 46567 46568 46569 46570 46571 46572 46573 46574 46575 46576 46577 46578 46579 46580 46581 46582 46583 46584 46585 46586 46587 46588 46589 46590 46591 46592 46593 46594 46595 46596 46597 46598 46599 46600 46601 46602 46603 46604 46605 46606 46607 46608 46609 46610 46611 46612 46613 46614 46615 46616 46617 46618 46619 46620 46621 46622 46623 46624 46625 46626 46627 46628 46629 46630 46631 46632 46633 46634 46635 46636 46637 46638 46639 46640 46641 46642 46643 46644 46645 46646 46647 46648 46649 46650 46651 46652 46653 46654 46655 46656 46657 46658 46659 46660 46661 46662 46663 46664 46665 46666 46667 46668 46669 46670 46671 46672 46673 46674 46675 46676 46677 46678 46679 46680 46681 46682 46683 46684 46685 46686 46687 46688 46689 46690 46691 46692 46693 46694 46695 46696 46697 46698 46699 46700 46701 46702 46703 46704 46705 46706 46707 46708 46709 46710 46711 46712 46713 46714 46715 46716 46717 46718 46719 46720 46721 46722 46723 46724 46725 46726 46727 46728 46729 46730 46731 46732 46733 46734 46735 46736 46737 46738 46739 46740 46741 46742 46743 46744 46745 46746 46747 46748 46749 46750 46751 46752 46753 46754 46755 46756 46757 46758 46759 46760 46761 46762 46763 46764 46765 46766 46767 46768 46769 46770 46771 46772 46773 46774 46775 46776 46777 46778 46779 46780 46781 46782 46783 46784 46785 46786 46787 46788 46789 46790 46791 46792 46793 46794 46795 46796 46797 46798 46799 46800 46801 46802 46803 46804 46805 46806 46807 46808 46809 46810 46811 46812 46813 46814 46815 46816 46817 46818 46819 46820 46821 46822 46823 46824 46825 46826 46827 46828 46829 46830 46831 46832 46833 46834 46835 46836 46837 46838 46839 46840 46841 46842 46843 46844 46845 46846 46847 46848 46849 46850 46851 46852 46853 46854 46855 46856 46857 46858 46859 46860 46861 46862 46863 46864 46865 46866 46867 46868 46869 46870 46871 46872 46873 46874 46875 46876 46877 46878 46879 46880 46881 46882 46883 46884 46885 46886 46887 46888 46889 46890 46891 46892 46893 46894 46895 46896 46897 46898 46899 46900 46901 46902 46903 46904 46905 46906 46907 46908 46909 46910 46911 46912 46913 46914 46915 46916 46917 46918 46919 46920 46921 46922 46923 46924 46925 46926 46927 46928 46929 46930 46931 46932 46933 46934 46935 46936 46937 46938 46939 46940 46941 46942 46943 46944 46945 46946 46947 46948 46949 46950 46951 46952 46953 46954 46955 46956 46957 46958 46959 46960 46961 46962 46963 46964 46965 46966 46967 46968 46969 46970 46971 46972 46973 46974 46975 46976 46977 46978 46979 46980 46981 46982 46983 46984 46985 46986 46987 46988 46989 46990 46991 46992 46993 46994 46995 46996 46997 46998 46999 47000 47001 47002 47003 47004 47005 47006 47007 47008 47009 47010 47011 47012 47013 47014 47015 47016 47017 47018 47019 47020 47021 47022 47023 47024 47025 47026 47027 47028 47029 47030 47031 47032 47033 47034 47035 47036 47037 47038 47039 47040 47041 47042 47043 47044 47045 47046 47047 47048 47049 47050 47051 47052 47053 47054 47055 47056 47057 47058 47059 47060 47061 47062 47063 47064 47065 47066 47067 47068 47069 47070 47071 47072 47073 47074 47075 47076 47077 47078 47079 47080 47081 47082 47083 47084 47085 47086 47087 47088 47089 47090 47091 47092 47093 47094 47095 47096 47097 47098 47099 47100 47101 47102 47103 47104 47105 47106 47107 47108 47109 47110 47111 47112 47113 47114 47115 47116 47117 47118 47119 47120 47121 47122 47123 47124 47125 47126 47127 47128 47129 47130 47131 47132 47133 47134 47135 47136 47137 47138 47139 47140 47141 47142 47143 47144 47145 47146 47147 47148 47149 47150 47151 47152 47153 47154 47155 47156 47157 47158 47159 47160 47161 47162 47163 47164 47165 47166 47167 47168 47169 47170 47171 47172 47173 47174 47175 47176 47177 47178 47179 47180 47181 47182 47183 47184 47185 47186 47187 47188 47189 47190 47191 47192 47193 47194 47195 47196 47197 47198 47199 47200 47201 47202 47203 47204 47205 47206 47207 47208 47209 47210 47211 47212 47213 47214 47215 47216 47217 47218 47219 47220 47221 47222 47223 47224 47225 47226 47227 47228 47229 47230 47231 47232 47233 47234 47235 47236 47237 47238 47239 47240 47241 47242 47243 47244 47245 47246 47247 47248 47249 47250 47251 47252 47253 47254 47255 47256 47257 47258 47259 47260 47261 47262 47263 47264 47265 47266 47267 47268 47269 47270 47271 47272 47273 47274 47275 47276 47277 47278 47279 47280 47281 47282 47283 47284 47285 47286 47287 47288 47289 47290 47291 47292 47293 47294 47295 47296 47297 47298 47299 47300 47301 47302 47303 47304 47305 47306 47307 47308 47309 47310 47311 47312 47313 47314 47315 47316 47317 47318 47319 47320 47321 47322 47323 47324 47325 47326 47327 47328 47329 47330 47331 47332 47333 47334 47335 47336 47337 47338 47339 47340 47341 47342 47343 47344 47345 47346 47347 47348 47349 47350 47351 47352 47353 47354 47355 47356 47357 47358 47359 47360 47361 47362 47363 47364 47365 47366 47367 47368 47369 47370 47371 47372 47373 47374 47375 47376 47377 47378 47379 47380 47381 47382 47383 47384 47385 47386 47387 47388 47389 47390 47391 47392 47393 47394 47395 47396 47397 47398 47399 47400 47401 47402 47403 47404 47405 47406 47407 47408 47409 47410 47411 47412 47413 47414 47415 47416 47417 47418 47419 47420 47421 47422 47423 47424 47425 47426 47427 47428 47429 47430 47431 47432 47433 47434 47435 47436 47437 47438 47439 47440 47441 47442 47443 47444 47445 47446 47447 47448 47449 47450 47451 47452 47453 47454 47455 47456 47457 47458 47459 47460 47461 47462 47463 47464 47465 47466 47467 47468 47469 47470 47471 47472 47473 47474 47475 47476 47477 47478 47479 47480 47481 47482 47483 47484 47485 47486 47487 47488 47489 47490 47491 47492 47493 47494 47495 47496 47497 47498 47499 47500 47501 47502 47503 47504 47505 47506 47507 47508 47509 47510 47511 47512 47513 47514 47515 47516 47517 47518 47519 47520 47521 47522 47523 47524 47525 47526 47527 47528 47529 47530 47531 47532 47533 47534 47535 47536 47537 47538 47539 47540 47541 47542 47543 47544 47545 47546 47547 47548 47549 47550 47551 47552 47553 47554 47555 47556 47557 47558 47559 47560 47561 47562 47563 47564 47565 47566 47567 47568 47569 47570 47571 47572 47573 47574 47575 47576 47577 47578 47579 47580 47581 47582 47583 47584 47585 47586 47587 47588 47589 47590 47591 47592 47593 47594 47595 47596 47597 47598 47599 47600 47601 47602 47603 47604 47605 47606 47607 47608 47609 47610 47611 47612 47613 47614 47615 47616 47617 47618 47619 47620 47621 47622 47623 47624 47625 47626 47627 47628 47629 47630 47631 47632 47633 47634 47635 47636 47637 47638 47639 47640 47641 47642 47643 47644 47645 47646 47647 47648 47649 47650 47651 47652 47653 47654 47655 47656 47657 47658 47659 47660 47661 47662 47663 47664 47665 47666 47667 47668 47669 47670 47671 47672 47673 47674 47675 47676 47677 47678 47679 47680 47681 47682 47683 47684 47685 47686 47687 47688 47689 47690 47691 47692 47693 47694 47695 47696 47697 47698 47699 47700 47701 47702 47703 47704 47705 47706 47707 47708 47709 47710 47711 47712 47713 47714 47715 47716 47717 47718 47719 47720 47721 47722 47723 47724 47725 47726 47727 47728 47729 47730 47731 47732 47733 47734 47735 47736 47737 47738 47739 47740 47741 47742 47743 47744 47745 47746 47747 47748 47749 47750 47751 47752 47753 47754 47755 47756 47757 47758 47759 47760 47761 47762 47763 47764 47765 47766 47767 47768 47769 47770 47771 47772 47773 47774 47775 47776 47777 47778 47779 47780 47781 47782 47783 47784 47785 47786 47787 47788 47789 47790 47791 47792 47793 47794 47795 47796 47797 47798 47799 47800 47801 47802 47803 47804 47805 47806 47807 47808 47809 47810 47811 47812 47813 47814 47815 47816 47817 47818 47819 47820 47821 47822 47823 47824 47825 47826 47827 47828 47829 47830 47831 47832 47833 47834 47835 47836 47837 47838 47839 47840 47841 47842 47843 47844 47845 47846 47847 47848 47849 47850 47851 47852 47853 47854 47855 47856 47857 47858 47859 47860 47861 47862 47863 47864 47865 47866 47867 47868 47869 47870 47871 47872 47873 47874 47875 47876 47877 47878 47879 47880 47881 47882 47883 47884 47885 47886 47887 47888 47889 47890 47891 47892 47893 47894 47895 47896 47897 47898 47899 47900 47901 47902 47903 47904 47905 47906 47907 47908 47909 47910 47911 47912 47913 47914 47915 47916 47917 47918 47919 47920 47921 47922 47923 47924 47925 47926 47927 47928 47929 47930 47931 47932 47933 47934 47935 47936 47937 47938 47939 47940 47941 47942 47943 47944 47945 47946 47947 47948 47949 47950 47951 47952 47953 47954 47955 47956 47957 47958 47959 47960 47961 47962 47963 47964 47965 47966 47967 47968 47969 47970 47971 47972 47973 47974 47975 47976 47977 47978 47979 47980 47981 47982 47983 47984 47985 47986 47987 47988 47989 47990 47991 47992 47993 47994 47995 47996 47997 47998 47999 48000 48001 48002 48003 48004 48005 48006 48007 48008 48009 48010 48011 48012 48013 48014 48015 48016 48017 48018 48019 48020 48021 48022 48023 48024 48025 48026 48027 48028 48029 48030 48031 48032 48033 48034 48035 48036 48037 48038 48039 48040 48041 48042 48043 48044 48045 48046 48047 48048 48049 48050 48051 48052 48053 48054 48055 48056 48057 48058 48059 48060 48061 48062 48063 48064 48065 48066 48067 48068 48069 48070 48071 48072 48073 48074 48075 48076 48077 48078 48079 48080 48081 48082 48083 48084 48085 48086 48087 48088 48089 48090 48091 48092 48093 48094 48095 48096 48097 48098 48099 48100 48101 48102 48103 48104 48105 48106 48107 48108 48109 48110 48111 48112 48113 48114 48115 48116 48117 48118 48119 48120 48121 48122 48123 48124 48125 48126 48127 48128 48129 48130 48131 48132 48133 48134 48135 48136 48137 48138 48139 48140 48141 48142 48143 48144 48145 48146 48147 48148 48149 48150 48151 48152 48153 48154 48155 48156 48157 48158 48159 48160 48161 48162 48163 48164 48165 48166 48167 48168 48169 48170 48171 48172 48173 48174 48175 48176 48177 48178 48179 48180 48181 48182 48183 48184 48185 48186 48187 48188 48189 48190 48191 48192 48193 48194 48195 48196 48197 48198 48199 48200 48201 48202 48203 48204 48205 48206 48207 48208 48209 48210 48211 48212 48213 48214 48215 48216 48217 48218 48219 48220 48221 48222 48223 48224 48225 48226 48227 48228 48229 48230 48231 48232 48233 48234 48235 48236 48237 48238 48239 48240 48241 48242 48243 48244 48245 48246 48247 48248 48249 48250 48251 48252 48253 48254 48255 48256 48257 48258 48259 48260 48261 48262 48263 48264 48265 48266 48267 48268 48269 48270 48271 48272 48273 48274 48275 48276 48277 48278 48279 48280 48281 48282 48283 48284 48285 48286 48287 48288 48289 48290 48291 48292 48293 48294 48295 48296 48297 48298 48299 48300 48301 48302 48303 48304 48305 48306 48307 48308 48309 48310 48311 48312 48313 48314 48315 48316 48317 48318 48319 48320 48321 48322 48323 48324 48325 48326 48327 48328 48329 48330 48331 48332 48333 48334 48335 48336 48337 48338 48339 48340 48341 48342 48343 48344 48345 48346 48347 48348 48349 48350 48351 48352 48353 48354 48355 48356 48357 48358 48359 48360 48361 48362 48363 48364 48365 48366 48367 48368 48369 48370 48371 48372 48373 48374 48375 48376 48377 48378 48379 48380 48381 48382 48383 48384 48385 48386 48387 48388 48389 48390 48391 48392 48393 48394 48395 48396 48397 48398 48399 48400 48401 48402 48403 48404 48405 48406 48407 48408 48409 48410 48411 48412 48413 48414 48415 48416 48417 48418 48419 48420 48421 48422 48423 48424 48425 48426 48427 48428 48429 48430 48431 48432 48433 48434 48435 48436 48437 48438 48439 48440 48441 48442 48443 48444 48445 48446 48447 48448 48449 48450 48451 48452 48453 48454 48455 48456 48457 48458 48459 48460 48461 48462 48463 48464 48465 48466 48467 48468 48469 48470 48471 48472 48473 48474 48475 48476 48477 48478 48479 48480 48481 48482 48483 48484 48485 48486 48487 48488 48489 48490 48491 48492 48493 48494 48495 48496 48497 48498 48499 48500 48501 48502 48503 48504 48505 48506 48507 48508 48509 48510 48511 48512 48513 48514 48515 48516 48517 48518 48519 48520 48521 48522 48523 48524 48525 48526 48527 48528 48529 48530 48531 48532 48533 48534 48535 48536 48537 48538 48539 48540 48541 48542 48543 48544 48545 48546 48547 48548 48549 48550 48551 48552 48553 48554 48555 48556 48557 48558 48559 48560 48561 48562 48563 48564 48565 48566 48567 48568 48569 48570 48571 48572 48573 48574 48575 48576 48577 48578 48579 48580 48581 48582 48583 48584 48585 48586 48587 48588 48589 48590 48591 48592 48593 48594 48595 48596 48597 48598 48599 48600 48601 48602 48603 48604 48605 48606 48607 48608 48609 48610 48611 48612 48613 48614 48615 48616 48617 48618 48619 48620 48621 48622 48623 48624 48625 48626 48627 48628 48629 48630 48631 48632 48633 48634 48635 48636 48637 48638 48639 48640 48641 48642 48643 48644 48645 48646 48647 48648 48649 48650 48651 48652 48653 48654 48655 48656 48657 48658 48659 48660 48661 48662 48663 48664 48665 48666 48667 48668 48669 48670 48671 48672 48673 48674 48675 48676 48677 48678 48679 48680 48681 48682 48683 48684 48685 48686 48687 48688 48689 48690 48691 48692 48693 48694 48695 48696 48697 48698 48699 48700 48701 48702 48703 48704 48705 48706 48707 48708 48709 48710 48711 48712 48713 48714 48715 48716 48717 48718 48719 48720 48721 48722 48723 48724 48725 48726 48727 48728 48729 48730 48731 48732 48733 48734 48735 48736 48737 48738 48739 48740 48741 48742 48743 48744 48745 48746 48747 48748 48749 48750 48751 48752 48753 48754 48755 48756 48757 48758 48759 48760 48761 48762 48763 48764 48765 48766 48767 48768 48769 48770 48771 48772 48773 48774 48775 48776 48777 48778 48779 48780 48781 48782 48783 48784 48785 48786 48787 48788 48789 48790 48791 48792 48793 48794 48795 48796 48797 48798 48799 48800 48801 48802 48803 48804 48805 48806 48807 48808 48809 48810 48811 48812 48813 48814 48815 48816 48817 48818 48819 48820 48821 48822 48823 48824 48825 48826 48827 48828 48829 48830 48831 48832 48833 48834 48835 48836 48837 48838 48839 48840 48841 48842 48843 48844 48845 48846 48847 48848 48849 48850 48851 48852 48853 48854 48855 48856 48857 48858 48859 48860 48861 48862 48863 48864 48865 48866 48867 48868 48869 48870 48871 48872 48873 48874 48875 48876 48877 48878 48879 48880 48881 48882 48883 48884 48885 48886 48887 48888 48889 48890 48891 48892 48893 48894 48895 48896 48897 48898 48899 48900 48901 48902 48903 48904 48905 48906 48907 48908 48909 48910 48911 48912 48913 48914 48915 48916 48917 48918 48919 48920 48921 48922 48923 48924 48925 48926 48927 48928 48929 48930 48931 48932 48933 48934 48935 48936 48937 48938 48939 48940 48941 48942 48943 48944 48945 48946 48947 48948 48949 48950 48951 48952 48953 48954 48955 48956 48957 48958 48959 48960 48961 48962 48963 48964 48965 48966 48967 48968 48969 48970 48971 48972 48973 48974 48975 48976 48977 48978 48979 48980 48981 48982 48983 48984 48985 48986 48987 48988 48989 48990 48991 48992 48993 48994 48995 48996 48997 48998 48999 49000 49001 49002 49003 49004 49005 49006 49007 49008 49009 49010 49011 49012 49013 49014 49015 49016 49017 49018 49019 49020 49021 49022 49023 49024 49025 49026 49027 49028 49029 49030 49031 49032 49033 49034 49035 49036 49037 49038 49039 49040 49041 49042 49043 49044 49045 49046 49047 49048 49049 49050 49051 49052 49053 49054 49055 49056 49057 49058 49059 49060 49061 49062 49063 49064 49065 49066 49067 49068 49069 49070 49071 49072 49073 49074 49075 49076 49077 49078 49079 49080 49081 49082 49083 49084 49085 49086 49087 49088 49089 49090 49091 49092 49093 49094 49095 49096 49097 49098 49099 49100 49101 49102 49103 49104 49105 49106 49107 49108 49109 49110 49111 49112 49113 49114 49115 49116 49117 49118 49119 49120 49121 49122 49123 49124 49125 49126 49127 49128 49129 49130 49131 49132 49133 49134 49135 49136 49137 49138 49139 49140 49141 49142 49143 49144 49145 49146 49147 49148 49149 49150 49151 49152 49153 49154 49155 49156 49157 49158 49159 49160 49161 49162 49163 49164 49165 49166 49167 49168 49169 49170 49171 49172 49173 49174 49175 49176 49177 49178 49179 49180 49181 49182 49183 49184 49185 49186 49187 49188 49189 49190 49191 49192 49193 49194 49195 49196 49197 49198 49199 49200 49201 49202 49203 49204 49205 49206 49207 49208 49209 49210 49211 49212 49213 49214 49215 49216 49217 49218 49219 49220 49221 49222 49223 49224 49225 49226 49227 49228 49229 49230 49231 49232 49233 49234 49235 49236 49237 49238 49239 49240 49241 49242 49243 49244 49245 49246 49247 49248 49249 49250 49251 49252 49253 49254 49255 49256 49257 49258 49259 49260 49261 49262 49263 49264 49265 49266 49267 49268 49269 49270 49271 49272 49273 49274 49275 49276 49277 49278 49279 49280 49281 49282 49283 49284 49285 49286 49287 49288 49289 49290 49291 49292 49293 49294 49295 49296 49297 49298 49299 49300 49301 49302 49303 49304 49305 49306 49307 49308 49309 49310 49311 49312 49313 49314 49315 49316 49317 49318 49319 49320 49321 49322 49323 49324 49325 49326 49327 49328 49329 49330 49331 49332 49333 49334 49335 49336 49337 49338 49339 49340 49341 49342 49343 49344 49345 49346 49347 49348 49349 49350 49351 49352 49353 49354 49355 49356 49357 49358 49359 49360 49361 49362 49363 49364 49365 49366 49367 49368 49369 49370 49371 49372 49373 49374 49375 49376 49377 49378 49379 49380 49381 49382 49383 49384 49385 49386 49387 49388 49389 49390 49391 49392 49393 49394 49395 49396 49397 49398 49399 49400 49401 49402 49403 49404 49405 49406 49407 49408 49409 49410 49411 49412 49413 49414 49415 49416 49417 49418 49419 49420 49421 49422 49423 49424 49425 49426 49427 49428 49429 49430 49431 49432 49433 49434 49435 49436 49437 49438 49439 49440 49441 49442 49443 49444 49445 49446 49447 49448 49449 49450 49451 49452 49453 49454 49455 49456 49457 49458 49459 49460 49461 49462 49463 49464 49465 49466 49467 49468 49469 49470 49471 49472 49473 49474 49475 49476 49477 49478 49479 49480 49481 49482 49483 49484 49485 49486 49487 49488 49489 49490 49491 49492 49493 49494 49495 49496 49497 49498 49499 49500 49501 49502 49503 49504 49505 49506 49507 49508 49509 49510 49511 49512 49513 49514 49515 49516 49517 49518 49519 49520 49521 49522 49523 49524 49525 49526 49527 49528 49529 49530 49531 49532 49533 49534 49535 49536 49537 49538 49539 49540 49541 49542 49543 49544 49545 49546 49547 49548 49549 49550 49551 49552 49553 49554 49555 49556 49557 49558 49559 49560 49561 49562 49563 49564 49565 49566 49567 49568 49569 49570 49571 49572 49573 49574 49575 49576 49577 49578 49579 49580 49581 49582 49583 49584 49585 49586 49587 49588 49589 49590 49591 49592 49593 49594 49595 49596 49597 49598 49599 49600 49601 49602 49603 49604 49605 49606 49607 49608 49609 49610 49611 49612 49613 49614 49615 49616 49617 49618 49619 49620 49621 49622 49623 49624 49625 49626 49627 49628 49629 49630 49631 49632 49633 49634 49635 49636 49637 49638 49639 49640 49641 49642 49643 49644 49645 49646 49647 49648 49649 49650 49651 49652 49653 49654 49655 49656 49657 49658 49659 49660 49661 49662 49663 49664 49665 49666 49667 49668 49669 49670 49671 49672 49673 49674 49675 49676 49677 49678 49679 49680 49681 49682 49683 49684 49685 49686 49687 49688 49689 49690 49691 49692 49693 49694 49695 49696 49697 49698 49699 49700 49701 49702 49703 49704 49705 49706 49707 49708 49709 49710 49711 49712 49713 49714 49715 49716 49717 49718 49719 49720 49721 49722 49723 49724 49725 49726 49727 49728 49729 49730 49731 49732 49733 49734 49735 49736 49737 49738 49739 49740 49741 49742 49743 49744 49745 49746 49747 49748 49749 49750 49751 49752 49753 49754 49755 49756 49757 49758 49759 49760 49761 49762 49763 49764 49765 49766 49767 49768 49769 49770 49771 49772 49773 49774 49775 49776 49777 49778 49779 49780 49781 49782 49783 49784 49785 49786 49787 49788 49789 49790 49791 49792 49793 49794 49795 49796 49797 49798 49799 49800 49801 49802 49803 49804 49805 49806 49807 49808 49809 49810 49811 49812 49813 49814 49815 49816 49817 49818 49819 49820 49821 49822 49823 49824 49825 49826 49827 49828 49829 49830 49831 49832 49833 49834 49835 49836 49837 49838 49839 49840 49841 49842 49843 49844 49845 49846 49847 49848 49849 49850 49851 49852 49853 49854 49855 49856 49857 49858 49859 49860 49861 49862 49863 49864 49865 49866 49867 49868 49869 49870 49871 49872 49873 49874 49875 49876 49877 49878 49879 49880 49881 49882 49883 49884 49885 49886 49887 49888 49889 49890 49891 49892 49893 49894 49895 49896 49897 49898 49899 49900 49901 49902 49903 49904 49905 49906 49907 49908 49909 49910 49911 49912 49913 49914 49915 49916 49917 49918 49919 49920 49921 49922 49923 49924 49925 49926 49927 49928 49929 49930 49931 49932 49933 49934 49935 49936 49937 49938 49939 49940 49941 49942 49943 49944 49945 49946 49947 49948 49949 49950 49951 49952 49953 49954 49955 49956 49957 49958 49959 49960 49961 49962 49963 49964 49965 49966 49967 49968 49969 49970 49971 49972 49973 49974 49975 49976 49977 49978 49979 49980 49981 49982 49983 49984 49985 49986 49987 49988 49989 49990 49991 49992 49993 49994 49995 49996 49997 49998 49999 50000 50001 50002 50003 50004 50005 50006 50007 50008 50009 50010 50011 50012 50013 50014 50015 50016 50017 50018 50019 50020 50021 50022 50023 50024 50025 50026 50027 50028 50029 50030 50031 50032 50033 50034 50035 50036 50037 50038 50039 50040 50041 50042 50043 50044 50045 50046 50047 50048 50049 50050 50051 50052 50053 50054 50055 50056 50057 50058 50059 50060 50061 50062 50063 50064 50065 50066 50067 50068 50069 50070 50071 50072 50073 50074 50075 50076 50077 50078 50079 50080 50081 50082 50083 50084 50085 50086 50087 50088 50089 50090 50091 50092 50093 50094 50095 50096 50097 50098 50099 50100 50101 50102 50103 50104 50105 50106 50107 50108 50109 50110 50111 50112 50113 50114 50115 50116 50117 50118 50119 50120 50121 50122 50123 50124 50125 50126 50127 50128 50129 50130 50131 50132 50133 50134 50135 50136 50137 50138 50139 50140 50141 50142 50143 50144 50145 50146 50147 50148 50149 50150 50151 50152 50153 50154 50155 50156 50157 50158 50159 50160 50161 50162 50163 50164 50165 50166 50167 50168 50169 50170 50171 50172 50173 50174 50175 50176 50177 50178 50179 50180 50181 50182 50183 50184 50185 50186 50187 50188 50189 50190 50191 50192 50193 50194 50195 50196 50197 50198 50199 50200 50201 50202 50203 50204 50205 50206 50207 50208 50209 50210 50211 50212 50213 50214 50215 50216 50217 50218 50219 50220 50221 50222 50223 50224 50225 50226 50227 50228 50229 50230 50231 50232 50233 50234 50235 50236 50237 50238 50239 50240 50241 50242 50243 50244 50245 50246 50247 50248 50249 50250 50251 50252 50253 50254 50255 50256 50257 50258 50259 50260 50261 50262 50263 50264 50265 50266 50267 50268 50269 50270 50271 50272 50273 50274 50275 50276 50277 50278 50279 50280 50281 50282 50283 50284 50285 50286 50287 50288 50289 50290 50291 50292 50293 50294 50295 50296 50297 50298 50299 50300 50301 50302 50303 50304 50305 50306 50307 50308 50309 50310 50311 50312 50313 50314 50315 50316 50317 50318 50319 50320 50321 50322 50323 50324 50325 50326 50327 50328 50329 50330 50331 50332 50333 50334 50335 50336 50337 50338 50339 50340 50341 50342 50343 50344 50345 50346 50347 50348 50349 50350 50351 50352 50353 50354 50355 50356 50357 50358 50359 50360 50361 50362 50363 50364 50365 50366 50367 50368 50369 50370 50371 50372 50373 50374 50375 50376 50377 50378 50379 50380 50381 50382 50383 50384 50385 50386 50387 50388 50389 50390 50391 50392 50393 50394 50395 50396 50397 50398 50399 50400 50401 50402 50403 50404 50405 50406 50407 50408 50409 50410 50411 50412 50413 50414 50415 50416 50417 50418 50419 50420 50421 50422 50423 50424 50425 50426 50427 50428 50429 50430 50431 50432 50433 50434 50435 50436 50437 50438 50439 50440 50441 50442 50443 50444 50445 50446 50447 50448 50449 50450 50451 50452 50453 50454 50455 50456 50457 50458 50459 50460 50461 50462 50463 50464 50465 50466 50467 50468 50469 50470 50471 50472 50473 50474 50475 50476 50477 50478 50479 50480 50481 50482 50483 50484 50485 50486 50487 50488 50489 50490 50491 50492 50493 50494 50495 50496 50497 50498 50499 50500 50501 50502 50503 50504 50505 50506 50507 50508 50509 50510 50511 50512 50513 50514 50515 50516 50517 50518 50519 50520 50521 50522 50523 50524 50525 50526 50527 50528 50529 50530 50531 50532 50533 50534 50535 50536 50537 50538 50539 50540 50541 50542 50543 50544 50545 50546 50547 50548 50549 50550 50551 50552 50553 50554 50555 50556 50557 50558 50559 50560 50561 50562 50563 50564 50565 50566 50567 50568 50569 50570 50571 50572 50573 50574 50575 50576 50577 50578 50579 50580 50581 50582 50583 50584 50585 50586 50587 50588 50589 50590 50591 50592 50593 50594 50595 50596 50597 50598 50599 50600 50601 50602 50603 50604 50605 50606 50607 50608 50609 50610 50611 50612 50613 50614 50615 50616 50617 50618 50619 50620 50621 50622 50623 50624 50625 50626 50627 50628 50629 50630 50631 50632 50633 50634 50635 50636 50637 50638 50639 50640 50641 50642 50643 50644 50645 50646 50647 50648 50649 50650 50651 50652 50653 50654 50655 50656 50657 50658 50659 50660 50661 50662 50663 50664 50665 50666 50667 50668 50669 50670 50671 50672 50673 50674 50675 50676 50677 50678 50679 50680 50681 50682 50683 50684 50685 50686 50687 50688 50689 50690 50691 50692 50693 50694 50695 50696 50697 50698 50699 50700 50701 50702 50703 50704 50705 50706 50707 50708 50709 50710 50711 50712 50713 50714 50715 50716 50717 50718 50719 50720 50721 50722 50723 50724 50725 50726 50727 50728 50729 50730 50731 50732 50733 50734 50735 50736 50737 50738 50739 50740 50741 50742 50743 50744 50745 50746 50747 50748 50749 50750 50751 50752 50753 50754 50755 50756 50757 50758 50759 50760 50761 50762 50763 50764 50765 50766 50767 50768 50769 50770 50771 50772 50773 50774 50775 50776 50777 50778 50779 50780 50781 50782 50783 50784 50785 50786 50787 50788 50789 50790 50791 50792 50793 50794 50795 50796 50797 50798 50799 50800 50801 50802 50803 50804 50805 50806 50807 50808 50809 50810 50811 50812 50813 50814 50815 50816 50817 50818 50819 50820 50821 50822 50823 50824 50825 50826 50827 50828 50829 50830 50831 50832 50833 50834 50835 50836 50837 50838 50839 50840 50841 50842 50843 50844 50845 50846 50847 50848 50849 50850 50851 50852 50853 50854 50855 50856 50857 50858 50859 50860 50861 50862 50863 50864 50865 50866 50867 50868 50869 50870 50871 50872 50873 50874 50875 50876 50877 50878 50879 50880 50881 50882 50883 50884 50885 50886 50887 50888 50889 50890 50891 50892 50893 50894 50895 50896 50897 50898 50899 50900 50901 50902 50903 50904 50905 50906 50907 50908 50909 50910 50911 50912 50913 50914 50915 50916 50917 50918 50919 50920 50921 50922 50923 50924 50925 50926 50927 50928 50929 50930 50931 50932 50933 50934 50935 50936 50937 50938 50939 50940 50941 50942 50943 50944 50945 50946 50947 50948 50949 50950 50951 50952 50953 50954 50955 50956 50957 50958 50959 50960 50961 50962 50963 50964 50965 50966 50967 50968 50969 50970 50971 50972 50973 50974 50975 50976 50977 50978 50979 50980 50981 50982 50983 50984 50985 50986 50987 50988 50989 50990 50991 50992 50993 50994 50995 50996 50997 50998 50999 51000 51001 51002 51003 51004 51005 51006 51007 51008 51009 51010 51011 51012 51013 51014 51015 51016 51017 51018 51019 51020 51021 51022 51023 51024 51025 51026 51027 51028 51029 51030 51031 51032 51033 51034 51035 51036 51037 51038 51039 51040 51041 51042 51043 51044 51045 51046 51047 51048 51049 51050 51051 51052 51053 51054 51055 51056 51057 51058 51059 51060 51061 51062 51063 51064 51065 51066 51067 51068 51069 51070 51071 51072 51073 51074 51075 51076 51077 51078 51079 51080 51081 51082 51083 51084 51085 51086 51087 51088 51089 51090 51091 51092 51093 51094 51095 51096 51097 51098 51099 51100 51101 51102 51103 51104 51105 51106 51107 51108 51109 51110 51111 51112 51113 51114 51115 51116 51117 51118 51119 51120 51121 51122 51123 51124 51125 51126 51127 51128 51129 51130 51131 51132 51133 51134 51135 51136 51137 51138 51139 51140 51141 51142 51143 51144 51145 51146 51147 51148 51149 51150 51151 51152 51153 51154 51155 51156 51157 51158 51159 51160 51161 51162 51163 51164 51165 51166 51167 51168 51169 51170 51171 51172 51173 51174 51175 51176 51177 51178 51179 51180 51181 51182 51183 51184 51185 51186 51187 51188 51189 51190 51191 51192 51193 51194 51195 51196 51197 51198 51199 51200 51201 51202 51203 51204 51205 51206 51207 51208 51209 51210 51211 51212 51213 51214 51215 51216 51217 51218 51219 51220 51221 51222 51223 51224 51225 51226 51227 51228 51229 51230 51231 51232 51233 51234 51235 51236 51237 51238 51239 51240 51241 51242 51243 51244 51245 51246 51247 51248 51249 51250 51251 51252 51253 51254 51255 51256 51257 51258 51259 51260 51261 51262 51263 51264 51265 51266 51267 51268 51269 51270 51271 51272 51273 51274 51275 51276 51277 51278 51279 51280 51281 51282 51283 51284 51285 51286 51287 51288 51289 51290 51291 51292 51293 51294 51295 51296 51297 51298 51299 51300 51301 51302 51303 51304 51305 51306 51307 51308 51309 51310 51311 51312 51313 51314 51315 51316 51317 51318 51319 51320 51321 51322 51323 51324 51325 51326 51327 51328 51329 51330 51331 51332 51333 51334 51335 51336 51337 51338 51339 51340 51341 51342 51343 51344 51345 51346 51347 51348 51349 51350 51351 51352 51353 51354 51355 51356 51357 51358 51359 51360 51361 51362 51363 51364 51365 51366 51367 51368 51369 51370 51371 51372 51373 51374 51375 51376 51377 51378 51379 51380 51381 51382 51383 51384 51385 51386 51387 51388 51389 51390 51391 51392 51393 51394 51395 51396 51397 51398 51399 51400 51401 51402 51403 51404 51405 51406 51407 51408 51409 51410 51411 51412 51413 51414 51415 51416 51417 51418 51419 51420 51421 51422 51423 51424 51425 51426 51427 51428 51429 51430 51431 51432 51433 51434 51435 51436 51437 51438 51439 51440 51441 51442 51443 51444 51445 51446 51447 51448 51449 51450 51451 51452 51453 51454 51455 51456 51457 51458 51459 51460 51461 51462 51463 51464 51465 51466 51467 51468 51469 51470 51471 51472 51473 51474 51475 51476 51477 51478 51479 51480 51481 51482 51483 51484 51485 51486 51487 51488 51489 51490 51491 51492 51493 51494 51495 51496 51497 51498 51499 51500 51501 51502 51503 51504 51505 51506 51507 51508 51509 51510 51511 51512 51513 51514 51515 51516 51517 51518 51519 51520 51521 51522 51523 51524 51525 51526 51527 51528 51529 51530 51531 51532 51533 51534 51535 51536 51537 51538 51539 51540 51541 51542 51543 51544 51545 51546 51547 51548 51549 51550 51551 51552 51553 51554 51555 51556 51557 51558 51559 51560 51561 51562 51563 51564 51565 51566 51567 51568 51569 51570 51571 51572 51573 51574 51575 51576 51577 51578 51579 51580 51581 51582 51583 51584 51585 51586 51587 51588 51589 51590 51591 51592 51593 51594 51595 51596 51597 51598 51599 51600 51601 51602 51603 51604 51605 51606 51607 51608 51609 51610 51611 51612 51613 51614 51615 51616 51617 51618 51619 51620 51621 51622 51623 51624 51625 51626 51627 51628 51629 51630 51631 51632 51633 51634 51635 51636 51637 51638 51639 51640 51641 51642 51643 51644 51645 51646 51647 51648 51649 51650 51651 51652 51653 51654 51655 51656 51657 51658 51659 51660 51661 51662 51663 51664 51665 51666 51667 51668 51669 51670 51671 51672 51673 51674 51675 51676 51677 51678 51679 51680 51681 51682 51683 51684 51685 51686 51687 51688 51689 51690 51691 51692 51693 51694 51695 51696 51697 51698 51699 51700 51701 51702 51703 51704 51705 51706 51707 51708 51709 51710 51711 51712 51713 51714 51715 51716 51717 51718 51719 51720 51721 51722 51723 51724 51725 51726 51727 51728 51729 51730 51731 51732 51733 51734 51735 51736 51737 51738 51739 51740 51741 51742 51743 51744 51745 51746 51747 51748 51749 51750 51751 51752 51753 51754 51755 51756 51757 51758 51759 51760 51761 51762 51763 51764 51765 51766 51767 51768 51769 51770 51771 51772 51773 51774 51775 51776 51777 51778 51779 51780 51781 51782 51783 51784 51785 51786 51787 51788 51789 51790 51791 51792 51793 51794 51795 51796 51797 51798 51799 51800 51801 51802 51803 51804 51805 51806 51807 51808 51809 51810 51811 51812 51813 51814 51815 51816 51817 51818 51819 51820 51821 51822 51823 51824 51825 51826 51827 51828 51829 51830 51831 51832 51833 51834 51835 51836 51837 51838 51839 51840 51841 51842 51843 51844 51845 51846 51847 51848 51849 51850 51851 51852 51853 51854 51855 51856 51857 51858 51859 51860 51861 51862 51863 51864 51865 51866 51867 51868 51869 51870 51871 51872 51873 51874 51875 51876 51877 51878 51879 51880 51881 51882 51883 51884 51885 51886 51887 51888 51889 51890 51891 51892 51893 51894 51895 51896 51897 51898 51899 51900 51901 51902 51903 51904 51905 51906 51907 51908 51909 51910 51911 51912 51913 51914 51915 51916 51917 51918 51919 51920 51921 51922 51923 51924 51925 51926 51927 51928 51929 51930 51931 51932 51933 51934 51935 51936 51937 51938 51939 51940 51941 51942 51943 51944 51945 51946 51947 51948 51949 51950 51951 51952 51953 51954 51955 51956 51957 51958 51959 51960 51961 51962 51963 51964 51965 51966 51967 51968 51969 51970 51971 51972 51973 51974 51975 51976 51977 51978 51979 51980 51981 51982 51983 51984 51985 51986 51987 51988 51989 51990 51991 51992 51993 51994 51995 51996 51997 51998 51999 52000 52001 52002 52003 52004 52005 52006 52007 52008 52009 52010 52011 52012 52013 52014 52015 52016 52017 52018 52019 52020 52021 52022 52023 52024 52025 52026 52027 52028 52029 52030 52031 52032 52033 52034 52035 52036 52037 52038 52039 52040 52041 52042 52043 52044 52045 52046 52047 52048 52049 52050 52051 52052 52053 52054 52055 52056 52057 52058 52059 52060 52061 52062 52063 52064 52065 52066 52067 52068 52069 52070 52071 52072 52073 52074 52075 52076 52077 52078 52079 52080 52081 52082 52083 52084 52085 52086 52087 52088 52089 52090 52091 52092 52093 52094 52095 52096 52097 52098 52099 52100 52101 52102 52103 52104 52105 52106 52107 52108 52109 52110 52111 52112 52113 52114 52115 52116 52117 52118 52119 52120 52121 52122 52123 52124 52125 52126 52127 52128 52129 52130 52131 52132 52133 52134 52135 52136 52137 52138 52139 52140 52141 52142 52143 52144 52145 52146 52147 52148 52149 52150 52151 52152 52153 52154 52155 52156 52157 52158 52159 52160 52161 52162 52163 52164 52165 52166 52167 52168 52169 52170 52171 52172 52173 52174 52175 52176 52177 52178 52179 52180 52181 52182 52183 52184 52185 52186 52187 52188 52189 52190 52191 52192 52193 52194 52195 52196 52197 52198 52199 52200 52201 52202 52203 52204 52205 52206 52207 52208 52209 52210 52211 52212 52213 52214 52215 52216 52217 52218 52219 52220 52221 52222 52223 52224 52225 52226 52227 52228 52229 52230 52231 52232 52233 52234 52235 52236 52237 52238 52239 52240 52241 52242 52243 52244 52245 52246 52247 52248 52249 52250 52251 52252 52253 52254 52255 52256 52257 52258 52259 52260 52261 52262 52263 52264 52265 52266 52267 52268 52269 52270 52271 52272 52273 52274 52275 52276 52277 52278 52279 52280 52281 52282 52283 52284 52285 52286 52287 52288 52289 52290 52291 52292 52293 52294 52295 52296 52297 52298 52299 52300 52301 52302 52303 52304 52305 52306 52307 52308 52309 52310 52311 52312 52313 52314 52315 52316 52317 52318 52319 52320 52321 52322 52323 52324 52325 52326 52327 52328 52329 52330 52331 52332 52333 52334 52335 52336 52337 52338 52339 52340 52341 52342 52343 52344 52345 52346 52347 52348 52349 52350 52351 52352 52353 52354 52355 52356 52357 52358 52359 52360 52361 52362 52363 52364 52365 52366 52367 52368 52369 52370 52371 52372 52373 52374 52375 52376 52377 52378 52379 52380 52381 52382 52383 52384 52385 52386 52387 52388 52389 52390 52391 52392 52393 52394 52395 52396 52397 52398 52399 52400 52401 52402 52403 52404 52405 52406 52407 52408 52409 52410 52411 52412 52413 52414 52415 52416 52417 52418 52419 52420 52421 52422 52423 52424 52425 52426 52427 52428 52429 52430 52431 52432 52433 52434 52435 52436 52437 52438 52439 52440 52441 52442 52443 52444 52445 52446 52447 52448 52449 52450 52451 52452 52453 52454 52455 52456 52457 52458 52459 52460 52461 52462 52463 52464 52465 52466 52467 52468 52469 52470 52471 52472 52473 52474 52475 52476 52477 52478 52479 52480 52481 52482 52483 52484 52485 52486 52487 52488 52489 52490 52491 52492 52493 52494 52495 52496 52497 52498 52499 52500 52501 52502 52503 52504 52505 52506 52507 52508 52509 52510 52511 52512 52513 52514 52515 52516 52517 52518 52519 52520 52521 52522 52523 52524 52525 52526 52527 52528 52529 52530 52531 52532 52533 52534 52535 52536 52537 52538 52539 52540 52541 52542 52543 52544 52545 52546 52547 52548 52549 52550 52551 52552 52553 52554 52555 52556 52557 52558 52559 52560 52561 52562 52563 52564 52565 52566 52567 52568 52569 52570 52571 52572 52573 52574 52575 52576 52577 52578 52579 52580 52581 52582 52583 52584 52585 52586 52587 52588 52589 52590 52591 52592 52593 52594 52595 52596 52597 52598 52599 52600 52601 52602 52603 52604 52605 52606 52607 52608 52609 52610 52611 52612 52613 52614 52615 52616 52617 52618 52619 52620 52621 52622 52623 52624 52625 52626 52627 52628 52629 52630 52631 52632 52633 52634 52635 52636 52637 52638 52639 52640 52641 52642 52643 52644 52645 52646 52647 52648 52649 52650 52651 52652 52653 52654 52655 52656 52657 52658 52659 52660 52661 52662 52663 52664 52665 52666 52667 52668 52669 52670 52671 52672 52673 52674 52675 52676 52677 52678 52679 52680 52681 52682 52683 52684 52685 52686 52687 52688 52689 52690 52691 52692 52693 52694 52695 52696 52697 52698 52699 52700 52701 52702 52703 52704 52705 52706 52707 52708 52709 52710 52711 52712 52713 52714 52715 52716 52717 52718 52719 52720 52721 52722 52723 52724 52725 52726 52727 52728 52729 52730 52731 52732 52733 52734 52735 52736 52737 52738 52739 52740 52741 52742 52743 52744 52745 52746 52747 52748 52749 52750 52751 52752 52753 52754 52755 52756 52757 52758 52759 52760 52761 52762 52763 52764 52765 52766 52767 52768 52769 52770 52771 52772 52773 52774 52775 52776 52777 52778 52779 52780 52781 52782 52783 52784 52785 52786 52787 52788 52789 52790 52791 52792 52793 52794 52795 52796 52797 52798 52799 52800 52801 52802 52803 52804 52805 52806 52807 52808 52809 52810 52811 52812 52813 52814 52815 52816 52817 52818 52819 52820 52821 52822 52823 52824 52825 52826 52827 52828 52829 52830 52831 52832 52833 52834 52835 52836 52837 52838 52839 52840 52841 52842 52843 52844 52845 52846 52847 52848 52849 52850 52851 52852 52853 52854 52855 52856 52857 52858 52859 52860 52861 52862 52863 52864 52865 52866 52867 52868 52869 52870 52871 52872 52873 52874 52875 52876 52877 52878 52879 52880 52881 52882 52883 52884 52885 52886 52887 52888 52889 52890 52891 52892 52893 52894 52895 52896 52897 52898 52899 52900 52901 52902 52903 52904 52905 52906 52907 52908 52909 52910 52911 52912 52913 52914 52915 52916 52917 52918 52919 52920 52921 52922 52923 52924 52925 52926 52927 52928 52929 52930 52931 52932 52933 52934 52935 52936 52937 52938 52939 52940 52941 52942 52943 52944 52945 52946 52947 52948 52949 52950 52951 52952 52953 52954 52955 52956 52957 52958 52959 52960 52961 52962 52963 52964 52965 52966 52967 52968 52969 52970 52971 52972 52973 52974 52975 52976 52977 52978 52979 52980 52981 52982 52983 52984 52985 52986 52987 52988 52989 52990 52991 52992 52993 52994 52995 52996 52997 52998 52999 53000 53001 53002 53003 53004 53005 53006 53007 53008 53009 53010 53011 53012 53013 53014 53015 53016 53017 53018 53019 53020 53021 53022 53023 53024 53025 53026 53027 53028 53029 53030 53031 53032 53033 53034 53035 53036 53037 53038 53039 53040 53041 53042 53043 53044 53045 53046 53047 53048 53049 53050 53051 53052 53053 53054 53055 53056 53057 53058 53059 53060 53061 53062 53063 53064 53065 53066 53067 53068 53069 53070 53071 53072 53073 53074 53075 53076 53077 53078 53079 53080 53081 53082 53083 53084 53085 53086 53087 53088 53089 53090 53091 53092 53093 53094 53095 53096 53097 53098 53099 53100 53101 53102 53103 53104 53105 53106 53107 53108 53109 53110 53111 53112 53113 53114 53115 53116 53117 53118 53119 53120 53121 53122 53123 53124 53125 53126 53127 53128 53129 53130 53131 53132 53133 53134 53135 53136 53137 53138 53139 53140 53141 53142 53143 53144 53145 53146 53147 53148 53149 53150 53151 53152 53153 53154 53155 53156 53157 53158 53159 53160 53161 53162 53163 53164 53165 53166 53167 53168 53169 53170 53171 53172 53173 53174 53175 53176 53177 53178 53179 53180 53181 53182 53183 53184 53185 53186 53187 53188 53189 53190 53191 53192 53193 53194 53195 53196 53197 53198 53199 53200 53201 53202 53203 53204 53205 53206 53207 53208 53209 53210 53211 53212 53213 53214 53215 53216 53217 53218 53219 53220 53221 53222 53223 53224 53225 53226 53227 53228 53229 53230 53231 53232 53233 53234 53235 53236 53237 53238 53239 53240 53241 53242 53243 53244 53245 53246 53247 53248 53249 53250 53251 53252 53253 53254 53255 53256 53257 53258 53259 53260 53261 53262 53263 53264 53265 53266 53267 53268 53269 53270 53271 53272 53273 53274 53275 53276 53277 53278 53279 53280 53281 53282 53283 53284 53285 53286 53287 53288 53289 53290 53291 53292 53293 53294 53295 53296 53297 53298 53299 53300 53301 53302 53303 53304 53305 53306 53307 53308 53309 53310 53311 53312 53313 53314 53315 53316 53317 53318 53319 53320 53321 53322 53323 53324 53325 53326 53327 53328 53329 53330 53331 53332 53333 53334 53335 53336 53337 53338 53339 53340 53341 53342 53343 53344 53345 53346 53347 53348 53349 53350 53351 53352 53353 53354 53355 53356 53357 53358 53359 53360 53361 53362 53363 53364 53365 53366 53367 53368 53369 53370 53371 53372 53373 53374 53375 53376 53377 53378 53379 53380 53381 53382 53383 53384 53385 53386 53387 53388 53389 53390 53391 53392 53393 53394 53395 53396 53397 53398 53399 53400 53401 53402 53403 53404 53405 53406 53407 53408 53409 53410 53411 53412 53413 53414 53415 53416 53417 53418 53419 53420 53421 53422 53423 53424 53425 53426 53427 53428 53429 53430 53431 53432 53433 53434 53435 53436 53437 53438 53439 53440 53441 53442 53443 53444 53445 53446 53447 53448 53449 53450 53451 53452 53453 53454 53455 53456 53457 53458 53459 53460 53461 53462 53463 53464 53465 53466 53467 53468 53469 53470 53471 53472 53473 53474 53475 53476 53477 53478 53479 53480 53481 53482 53483 53484 53485 53486 53487 53488 53489 53490 53491 53492 53493 53494 53495 53496 53497 53498 53499 53500 53501 53502 53503 53504 53505 53506 53507 53508 53509 53510 53511 53512 53513 53514 53515 53516 53517 53518 53519 53520 53521 53522 53523 53524 53525 53526 53527 53528 53529 53530 53531 53532 53533 53534 53535 53536 53537 53538 53539 53540 53541 53542 53543 53544 53545 53546 53547 53548 53549 53550 53551 53552 53553 53554 53555 53556 53557 53558 53559 53560 53561 53562 53563 53564 53565 53566 53567 53568 53569 53570 53571 53572 53573 53574 53575 53576 53577 53578 53579 53580 53581 53582 53583 53584 53585 53586 53587 53588 53589 53590 53591 53592 53593 53594 53595 53596 53597 53598 53599 53600 53601 53602 53603 53604 53605 53606 53607 53608 53609 53610 53611 53612 53613 53614 53615 53616 53617 53618 53619 53620 53621 53622 53623 53624 53625 53626 53627 53628 53629 53630 53631 53632 53633 53634 53635 53636 53637 53638 53639 53640 53641 53642 53643 53644 53645 53646 53647 53648 53649 53650 53651 53652 53653 53654 53655 53656 53657 53658 53659 53660 53661 53662 53663 53664 53665 53666 53667 53668 53669 53670 53671 53672 53673 53674 53675 53676 53677 53678 53679 53680 53681 53682 53683 53684 53685 53686 53687 53688 53689 53690 53691 53692 53693 53694 53695 53696 53697 53698 53699 53700 53701 53702 53703 53704 53705 53706 53707 53708 53709 53710 53711 53712 53713 53714 53715 53716 53717 53718 53719 53720 53721 53722 53723 53724 53725 53726 53727 53728 53729 53730 53731 53732 53733 53734 53735 53736 53737 53738 53739 53740 53741 53742 53743 53744 53745 53746 53747 53748 53749 53750 53751 53752 53753 53754 53755 53756 53757 53758 53759 53760 53761 53762 53763 53764 53765 53766 53767 53768 53769 53770 53771 53772 53773 53774 53775 53776 53777 53778 53779 53780 53781 53782 53783 53784 53785 53786 53787 53788 53789 53790 53791 53792 53793 53794 53795 53796 53797 53798 53799 53800 53801 53802 53803 53804 53805 53806 53807 53808 53809 53810 53811 53812 53813 53814 53815 53816 53817 53818 53819 53820 53821 53822 53823 53824 53825 53826 53827 53828 53829 53830 53831 53832 53833 53834 53835 53836 53837 53838 53839 53840 53841 53842 53843 53844 53845 53846 53847 53848 53849 53850 53851 53852 53853 53854 53855 53856 53857 53858 53859 53860 53861 53862 53863 53864 53865 53866 53867 53868 53869 53870 53871 53872 53873 53874 53875 53876 53877 53878 53879 53880 53881 53882 53883 53884 53885 53886 53887 53888 53889 53890 53891 53892 53893 53894 53895 53896 53897 53898 53899 53900 53901 53902 53903 53904 53905 53906 53907 53908 53909 53910 53911 53912 53913 53914 53915 53916 53917 53918 53919 53920 53921 53922 53923 53924 53925 53926 53927 53928 53929 53930 53931 53932 53933 53934 53935 53936 53937 53938 53939 53940 53941 53942 53943 53944 53945 53946 53947 53948 53949 53950 53951 53952 53953 53954 53955 53956 53957 53958 53959 53960 53961 53962 53963 53964 53965 53966 53967 53968 53969 53970 53971 53972 53973 53974 53975 53976 53977 53978 53979 53980 53981 53982 53983 53984 53985 53986 53987 53988 53989 53990 53991 53992 53993 53994 53995 53996 53997 53998 53999 54000 54001 54002 54003 54004 54005 54006 54007 54008 54009 54010 54011 54012 54013 54014 54015 54016 54017 54018 54019 54020 54021 54022 54023 54024 54025 54026 54027 54028 54029 54030 54031 54032 54033 54034 54035 54036 54037 54038 54039 54040 54041 54042 54043 54044 54045 54046 54047 54048 54049 54050 54051 54052 54053 54054 54055 54056 54057 54058 54059 54060 54061 54062 54063 54064 54065 54066 54067 54068 54069 54070 54071 54072 54073 54074 54075 54076 54077 54078 54079 54080 54081 54082 54083 54084 54085 54086 54087 54088 54089 54090 54091 54092 54093 54094 54095 54096 54097 54098 54099 54100 54101 54102 54103 54104 54105 54106 54107 54108 54109 54110 54111 54112 54113 54114 54115 54116 54117 54118 54119 54120 54121 54122 54123 54124 54125 54126 54127 54128 54129 54130 54131 54132 54133 54134 54135 54136 54137 54138 54139 54140 54141 54142 54143 54144 54145 54146 54147 54148 54149 54150 54151 54152 54153 54154 54155 54156 54157 54158 54159 54160 54161 54162 54163 54164 54165 54166 54167 54168 54169 54170 54171 54172 54173 54174 54175 54176 54177 54178 54179 54180 54181 54182 54183 54184 54185 54186 54187 54188 54189 54190 54191 54192 54193 54194 54195 54196 54197 54198 54199 54200 54201 54202 54203 54204 54205 54206 54207 54208 54209 54210 54211 54212 54213 54214 54215 54216 54217 54218 54219 54220 54221 54222 54223 54224 54225 54226 54227 54228 54229 54230 54231 54232 54233 54234 54235 54236 54237 54238 54239 54240 54241 54242 54243 54244 54245 54246 54247 54248 54249 54250 54251 54252 54253 54254 54255 54256 54257 54258 54259 54260 54261 54262 54263 54264 54265 54266 54267 54268 54269 54270 54271 54272 54273 54274 54275 54276 54277 54278 54279 54280 54281 54282 54283 54284 54285 54286 54287 54288 54289 54290 54291 54292 54293 54294 54295 54296 54297 54298 54299 54300 54301 54302 54303 54304 54305 54306 54307 54308 54309 54310 54311 54312 54313 54314 54315 54316 54317 54318 54319 54320 54321 54322 54323 54324 54325 54326 54327 54328 54329 54330 54331 54332 54333 54334 54335 54336 54337 54338 54339 54340 54341 54342 54343 54344 54345 54346 54347 54348 54349 54350 54351 54352 54353 54354 54355 54356 54357 54358 54359 54360 54361 54362 54363 54364 54365 54366 54367 54368 54369 54370 54371 54372 54373 54374 54375 54376 54377 54378 54379 54380 54381 54382 54383 54384 54385 54386 54387 54388 54389 54390 54391 54392 54393 54394 54395 54396 54397 54398 54399 54400 54401 54402 54403 54404 54405 54406 54407 54408 54409 54410 54411 54412 54413 54414 54415 54416 54417 54418 54419 54420 54421 54422 54423 54424 54425 54426 54427 54428 54429 54430 54431 54432 54433 54434 54435 54436 54437 54438 54439 54440 54441 54442 54443 54444 54445 54446 54447 54448 54449 54450 54451 54452 54453 54454 54455 54456 54457 54458 54459 54460 54461 54462 54463 54464 54465 54466 54467 54468 54469 54470 54471 54472 54473 54474 54475 54476 54477 54478 54479 54480 54481 54482 54483 54484 54485 54486 54487 54488 54489 54490 54491 54492 54493 54494 54495 54496 54497 54498 54499 54500 54501 54502 54503 54504 54505 54506 54507 54508 54509 54510 54511 54512 54513 54514 54515 54516 54517 54518 54519 54520 54521 54522 54523 54524 54525 54526 54527 54528 54529 54530 54531 54532 54533 54534 54535 54536 54537 54538 54539 54540 54541 54542 54543 54544 54545 54546 54547 54548 54549 54550 54551 54552 54553 54554 54555 54556 54557 54558 54559 54560 54561 54562 54563 54564 54565 54566 54567 54568 54569 54570 54571 54572 54573 54574 54575 54576 54577 54578 54579 54580 54581 54582 54583 54584 54585 54586 54587 54588 54589 54590 54591 54592 54593 54594 54595 54596 54597 54598 54599 54600 54601 54602 54603 54604 54605 54606 54607 54608 54609 54610 54611 54612 54613 54614 54615 54616 54617 54618 54619 54620 54621 54622 54623 54624 54625 54626 54627 54628 54629 54630 54631 54632 54633 54634 54635 54636 54637 54638 54639 54640 54641 54642 54643 54644 54645 54646 54647 54648 54649 54650 54651 54652 54653 54654 54655 54656 54657 54658 54659 54660 54661 54662 54663 54664 54665 54666 54667 54668 54669 54670 54671 54672 54673 54674 54675 54676 54677 54678 54679 54680 54681 54682 54683 54684 54685 54686 54687 54688 54689 54690 54691 54692 54693 54694 54695 54696 54697 54698 54699 54700 54701 54702 54703 54704 54705 54706 54707 54708 54709 54710 54711 54712 54713 54714 54715 54716 54717 54718 54719 54720 54721 54722 54723 54724 54725 54726 54727 54728 54729 54730 54731 54732 54733 54734 54735 54736 54737 54738 54739 54740 54741 54742 54743 54744 54745 54746 54747 54748 54749 54750 54751 54752 54753 54754 54755 54756 54757 54758 54759 54760 54761 54762 54763 54764 54765 54766 54767 54768 54769 54770 54771 54772 54773 54774 54775 54776 54777 54778 54779 54780 54781 54782 54783 54784 54785 54786 54787 54788 54789 54790 54791 54792 54793 54794 54795 54796 54797 54798 54799 54800 54801 54802 54803 54804 54805 54806 54807 54808 54809 54810 54811 54812 54813 54814 54815 54816 54817 54818 54819 54820 54821 54822 54823 54824 54825 54826 54827 54828 54829 54830 54831 54832 54833 54834 54835 54836 54837 54838 54839 54840 54841 54842 54843 54844 54845 54846 54847 54848 54849 54850 54851 54852 54853 54854 54855 54856 54857 54858 54859 54860 54861 54862 54863 54864 54865 54866 54867 54868 54869 54870 54871 54872 54873 54874 54875 54876 54877 54878 54879 54880 54881 54882 54883 54884 54885 54886 54887 54888 54889 54890 54891 54892 54893 54894 54895 54896 54897 54898 54899 54900 54901 54902 54903 54904 54905 54906 54907 54908 54909 54910 54911 54912 54913 54914 54915 54916 54917 54918 54919 54920 54921 54922 54923 54924 54925 54926 54927 54928 54929 54930 54931 54932 54933 54934 54935 54936 54937 54938 54939 54940 54941 54942 54943 54944 54945 54946 54947 54948 54949 54950 54951 54952 54953 54954 54955 54956 54957 54958 54959 54960 54961 54962 54963 54964 54965 54966 54967 54968 54969 54970 54971 54972 54973 54974 54975 54976 54977 54978 54979 54980 54981 54982 54983 54984 54985 54986 54987 54988 54989 54990 54991 54992 54993 54994 54995 54996 54997 54998 54999 55000 55001 55002 55003 55004 55005 55006 55007 55008 55009 55010 55011 55012 55013 55014 55015 55016 55017 55018 55019 55020 55021 55022 55023 55024 55025 55026 55027 55028 55029 55030 55031 55032 55033 55034 55035 55036 55037 55038 55039 55040 55041 55042 55043 55044 55045 55046 55047 55048 55049 55050 55051 55052 55053 55054 55055 55056 55057 55058 55059 55060 55061 55062 55063 55064 55065 55066 55067 55068 55069 55070 55071 55072 55073 55074 55075 55076 55077 55078 55079 55080 55081 55082 55083 55084 55085 55086 55087 55088 55089 55090 55091 55092 55093 55094 55095 55096 55097 55098 55099 55100 55101 55102 55103 55104 55105 55106 55107 55108 55109 55110 55111 55112 55113 55114 55115 55116 55117 55118 55119 55120 55121 55122 55123 55124 55125 55126 55127 55128 55129 55130 55131 55132 55133 55134 55135 55136 55137 55138 55139 55140 55141 55142 55143 55144 55145 55146 55147 55148 55149 55150 55151 55152 55153 55154 55155 55156 55157 55158 55159 55160 55161 55162 55163 55164 55165 55166 55167 55168 55169 55170 55171 55172 55173 55174 55175 55176 55177 55178 55179 55180 55181 55182 55183 55184 55185 55186 55187 55188 55189 55190 55191 55192 55193 55194 55195 55196 55197 55198 55199 55200 55201 55202 55203 55204 55205 55206 55207 55208 55209 55210 55211 55212 55213 55214 55215 55216 55217 55218 55219 55220 55221 55222 55223 55224 55225 55226 55227 55228 55229 55230 55231 55232 55233 55234 55235 55236 55237 55238 55239 55240 55241 55242 55243 55244 55245 55246 55247 55248 55249 55250 55251 55252 55253 55254 55255 55256 55257 55258 55259 55260 55261 55262 55263 55264 55265 55266 55267 55268 55269 55270 55271 55272 55273 55274 55275 55276 55277 55278 55279 55280 55281 55282 55283 55284 55285 55286 55287 55288 55289 55290 55291 55292 55293 55294 55295 55296 55297 55298 55299 55300 55301 55302 55303 55304 55305 55306 55307 55308 55309 55310 55311 55312 55313 55314 55315 55316 55317 55318 55319 55320 55321 55322 55323 55324 55325 55326 55327 55328 55329 55330 55331 55332 55333 55334 55335 55336 55337 55338 55339 55340 55341 55342 55343 55344 55345 55346 55347 55348 55349 55350 55351 55352 55353 55354 55355 55356 55357 55358 55359 55360 55361 55362 55363 55364 55365 55366 55367 55368 55369 55370 55371 55372 55373 55374 55375 55376 55377 55378 55379 55380 55381 55382 55383 55384 55385 55386 55387 55388 55389 55390 55391 55392 55393 55394 55395 55396 55397 55398 55399 55400 55401 55402 55403 55404 55405 55406 55407 55408 55409 55410 55411 55412 55413 55414 55415 55416 55417 55418 55419 55420 55421 55422 55423 55424 55425 55426 55427 55428 55429 55430 55431 55432 55433 55434 55435 55436 55437 55438 55439 55440 55441 55442 55443 55444 55445 55446 55447 55448 55449 55450 55451 55452 55453 55454 55455 55456 55457 55458 55459 55460 55461 55462 55463 55464 55465 55466 55467 55468 55469 55470 55471 55472 55473 55474 55475 55476 55477 55478 55479 55480 55481 55482 55483 55484 55485 55486 55487 55488 55489 55490 55491 55492 55493 55494 55495 55496 55497 55498 55499 55500 55501 55502 55503 55504 55505 55506 55507 55508 55509 55510 55511 55512 55513 55514 55515 55516 55517 55518 55519 55520 55521 55522 55523 55524 55525 55526 55527 55528 55529 55530 55531 55532 55533 55534 55535 55536 55537 55538 55539 55540 55541 55542 55543 55544 55545 55546 55547 55548 55549 55550 55551 55552 55553 55554 55555 55556 55557 55558 55559 55560 55561 55562 55563 55564 55565 55566 55567 55568 55569 55570 55571 55572 55573 55574 55575 55576 55577 55578 55579 55580 55581 55582 55583 55584 55585 55586 55587 55588 55589 55590 55591 55592 55593 55594 55595 55596 55597 55598 55599 55600 55601 55602 55603 55604 55605 55606 55607 55608 55609 55610 55611 55612 55613 55614 55615 55616 55617 55618 55619 55620 55621 55622 55623 55624 55625 55626 55627 55628 55629 55630 55631 55632 55633 55634 55635 55636 55637 55638 55639 55640 55641 55642 55643 55644 55645 55646 55647 55648 55649 55650 55651 55652 55653 55654 55655 55656 55657 55658 55659 55660 55661 55662 55663 55664 55665 55666 55667 55668 55669 55670 55671 55672 55673 55674 55675 55676 55677 55678 55679 55680 55681 55682 55683 55684 55685 55686 55687 55688 55689 55690 55691 55692 55693 55694 55695 55696 55697 55698 55699 55700 55701 55702 55703 55704 55705 55706 55707 55708 55709 55710 55711 55712 55713 55714 55715 55716 55717 55718 55719 55720 55721 55722 557232           2   1       2 2 2 2 2 2 1   2         2                 2           2         2   2 2 1 6 6 6 6 6 6   2     2     2             2                 2       2         2     2     2           2     2     2     2           2     2           2     2           2     2           2           2           2         2           2         2             2                   2       2     2           2 2 2 6 2 2 2 2 2 2   2 2 1             2             2         2                   2     2     2             2     2                       2                 2             2     2     2             2     2             2               2                     2         2           2       2     2                             2   2 2 1 6 6   2     2     2           2           2         2         2         2     2         2         2     2     2         2         2         2     2         2     2     2         2     2         2     2     2         2     2       2                 2       2 6   2       2       2                     2                 2                     2         2     2         2         2         2         2           2             2     2         2         2                   2   2 2 1 30 30 30   2     2     2             2         2             2                           2           2     2           2           2     2           2     2           2     2           2     2         2     2       2     2           2     2           2     2     2           2                 2                   2     2       2                   2     2           2             2           2           2           2         2         2         2 24   2     2     2     2     2         2                 2                 2         2               2         2                           2                       2                       2           2     2         2           2         2       2                       2                         2                         2         2         2     2           2                   2               2                                                                                                                                                                                                             2   2   2 1 6 6 6 6   2     2     2               2         2                   2             2     2             2             2     2             2     2             2     2             2     2           2     2               2     2             2     2             2     2     2             2                     2                       2     2       2                     2     2     2             2               2           2           2           2           2 6   2         2       2         2         2     2             2         2   2 2 1       2     2     2         2       2       2     2     2           2             2     2       2       2         2   2 2 1 4 4 4 4 4 4 4 4   2     2     2             2     2     2     2             2             2     2     2     2         2               2       2       2           2       2     2               2           2                                                         2                                                       2         2         2                                                                       2     2     2     2                 2           2         2                               2         2                   2         2                                                 2   2 2 1 16     2                   2                       2     2     2       2           2         2           2           2                                                                                                                   2           2     2         2           2             2       2                                                                                                     2             2     2     2             2                                         2         2                     2               2         2         2                                   2             2                     2 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16   2               2     2     2 16   2         2         2                                       2         2                                       2         2                                       2         2                                     2         2       2         2                                   2         2     2             2                           2         2                                         2         2                                         2         2             2         2                       2         2       2                         2         2                                             2         2                                             2                                         2               2           2             2                                       2         2                                                 2                                   2                                                     2 2 2 2 2   2 2 1       2       2     2     2         2                       2                       2     2                                               2       2       2     2         2             2       2   2 2 1           2     2   2 2 1   2               2                                                                           2   2 2 2 2   2 2 1   2 2 2 2   2   2 1   2                                     2   2 2 2 2   2 2 1               2         2     2     2   2 2 1                                                   2   2 2 1           2                     2                                           2       2                 2     2                                             2     2   2 2                 1                               2           2           2           2           2             2                   2                                                                                                           2                     2                       2                                                   2   2 2           1                       2                                       2                                       2                     2           2               2                   2             2   2   2 1                     2                         2                     2   2   2 1                     2           2                         2   2   2 1           2     2   2 2 1               2     2   2         2 1   2 2 2   2 2 2       2   2                 2 2 1                   1     2 1     2 1     2 1     2 1     2 1     2 1     2 1     2 2 1   2                                                                                     2                                                                               2                                                       2   2         2 2       2       1       2           2   2       2 1       2   2               2 1                   2                                     2                       2                             2                                     2           2           2         2   2         2 2 2 1                                   2   1                                                                                                                 2   1                                                                                                       2                                     2                                                                       2                                                                                                                                                           2               2                                                                                       2                                                                         2                                         2                                                                       2                                                                                                                                                           2 2 2               2               2   2         2 2 2 2           2 1   2                                       2                                                                                                                                                                                                                                                   2                               2                               2                             2                             2                               2                             2 2 2 2 2 2 2 2 2 2 2 2 2 2   2           2 2 2 1           2                   2             2     2       2                     2                       2               2 2   2         2 2           2 1                 2                   2                             2                                 2                         2                 2               2                     2                           2                     2       2                       2                       2                   2   2         2 2   2 2                           2 1   2                     2               2             2                 2           2                     2     2     2                                                 2                                           2                                                 2                             2                                           2           2                       2                                     2           2                           2                                 2       2                                                                                                                 2                                                                                         2                 2                                       2             2       2                           2                                                                             2           2                         2                         2                                                               2                                                       2                                                                           2                                                                                                           2                                                                                   2           2             2             2             2             2             2           2         2     2           2     2           2     2             2             2       2                                               2             2             2             2                                   2   2   2             2               2                   2                   2                               2                                 2                           2                                                   2                                         2                       2 2 2   2 2 2 2 2 2 2 2 2   2 2 2 2                             1                                                                                                                                                                                                                                                                                 1                                   1                                                                                                                                                                         1                                                                                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1           1                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                       1                     1                                                                                                                                       1                                                                                                       1                                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1                                                                                                                                                                         1                                                                                                                                                                                                           1                                                                                                 1                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                 1                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                             1                                                                                                                                                 1                                                                                                                               1                                                                                                                                                                                                                                   1                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                       1                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                                             1                                                                                         1                                                                                                                                                     1                                                                                   1                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                           1                         1                           1                     1                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                                                                       1                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                               1                                                                                                   1                                                                                                                                                                                                                   1                                                                                                                                                           1                       1                                                                                                                                                                                                                         1                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                 1                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                               1                                                                                                                                                                                                                                                                                             1                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                             1                   1                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                       1                                                                                                               1                       1                           1                                                               1                     1                                               1                               1                           1                     1                     1                     1                     1                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                 1                                             1                                                                                                                   1                           1                                                     1                                                     1                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                     1                                                                                                                                                                                                   1                                                                                         1                                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                       1                                                                                                                                           1                                                                                                                                                                                             1                                                     1                                                                                                                                                                               1                       1                                                       1                                                                                                                                                                                                                                                                                                 1                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                 1                                                   1                                           1                                                             1                                                                   1                                                         1                                         1                                 1                                                             1                       1                                                           1                                         1                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                         1                                         1                                                             1                                                                   1                                   1                                                                             1                                                                     1                                                                 1                                       1                                                             1                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                               1                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                     1                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                       1                                                                                                                                                                                                                                                                                                                                         1                                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                 1                                                                       1                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                         1                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1           1                                                 1                                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                         1                 1                                                                                                                                                           1                       1                               1                                                                                         1                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                             1                                                               1                                 1                                           1                                                                                 1                           1                                                             1                                   1                                             1                                   1       1               1                                                                                       1                             1                                                                                                           1                             1                   1           1                 1       1       1               1                           1           1                     1                         1                           1               1                                         1                                             1                     1                                                                   1                                               1                                                                                                                                                                                                 1                                           1                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                           1                                                                                                                               1                                   1                                                                                                                                                                               1                                                         1                                                 1                                                 1                                                         1                                                           1                                                         1                                                                                                                                                                           1                                                                                                                                                                   1                                                                                                                                                                                                                                                                               1                       1                                                         1                                     1                       1                       1                       1                       1                       1                                                                                                                                                                     1                                                                                                                                         1                                                                                                                         1                                           1                                                                                                                         1             1                                                                                       1                                                                           1                                                                                                                                                                                                                                                                                                 1                                                                                                                                                                                     1                                                                                                                                                                                                                                                                       1                                                         1                                                                               1                                       1                                                                   1                                                 1                                                       1                                             1                                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                                           1                             1                                                           1                                                                                                       1                                                                                                                                                                                                                                                           1               1                                                                                                                               1                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                                                                                           1                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                       1                         1                         1                         1                         1                           1                           1                           1                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1                                                               1                                                                                                                                                                                                                   1                                                                                                                                               1                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                           1                                                                                                                                                                                                                         1                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1                                                                                                                                                                                                                                                             1                                                                                                                                                                         1                                                                                                                         1                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var BABYLON;
(function (BABYLON) {
    BABYLON.ToGammaSpace = 1 / 2.2;
    BABYLON.ToLinearSpace = 2.2;
    BABYLON.Epsilon = 0.001;
    var MathTools = (function () {
        function MathTools() {
        }
        MathTools.WithinEpsilon = function (a, b, epsilon) {
            if (epsilon === void 0) { epsilon = 1.401298E-45; }
            var num = a - b;
            return -epsilon <= num && num <= epsilon;
        };
        MathTools.ToHex = function (i) {
            var str = i.toString(16);
            if (i <= 15) {
                return ("0" + str).toUpperCase();
            }
            return str.toUpperCase();
        };
        // Returns -1 when value is a negative number and
        // +1 when value is a positive number. 
        MathTools.Sign = function (value) {
            value = +value; // convert to a number
            if (value === 0 || isNaN(value))
                return value;
            return value > 0 ? 1 : -1;
        };
        MathTools.Clamp = function (value, min, max) {
            if (min === void 0) { min = 0; }
            if (max === void 0) { max = 1; }
            return Math.min(max, Math.max(min, value));
        };
        return MathTools;
    }());
    BABYLON.MathTools = MathTools;
    var Color3 = (function () {
        function Color3(r, g, b) {
            Iif (r === void 0) { r = 0; }
            Iif (g === void 0) { g = 0; }
            Iif (b === void 0) { b = 0; }
            this.r = r;
            this.g = g;
            this.b = b;
        }
        Color3.prototype.toString = function () {
            return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
        };
        Color3.prototype.getClassName = function () {
            return "Color3";
        };
        Color3.prototype.getHashCode = function () {
            var hash = this.r || 0;
            hash = (hash * 397) ^ (this.g || 0);
            hash = (hash * 397) ^ (this.b || 0);
            return hash;
        };
        // Operators
        Color3.prototype.toArray = function (array, index) {
            if (index === undefined) {
                index = 0;
            }
            array[index] = this.r;
            array[index + 1] = this.g;
            array[index + 2] = this.b;
            return this;
        };
        Color3.prototype.toColor4 = function (alpha) {
            if (alpha === void 0) { alpha = 1; }
            return new Color4(this.r, this.g, this.b, alpha);
        };
        Color3.prototype.asArray = function () {
            var result = [];
            this.toArray(result, 0);
            return result;
        };
        Color3.prototype.toLuminance = function () {
            return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
        };
        Color3.prototype.multiply = function (otherColor) {
            return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
        };
        Color3.prototype.multiplyToRef = function (otherColor, result) {
            result.r = this.r * otherColor.r;
            result.g = this.g * otherColor.g;
            result.b = this.b * otherColor.b;
            return this;
        };
        Color3.prototype.equals = function (otherColor) {
            return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
        };
        Color3.prototype.equalsFloats = function (r, g, b) {
            return this.r === r && this.g === g && this.b === b;
        };
        Color3.prototype.scale = function (scale) {
            return new Color3(this.r * scale, this.g * scale, this.b * scale);
        };
        Color3.prototype.scaleToRef = function (scale, result) {
            result.r = this.r * scale;
            result.g = this.g * scale;
            result.b = this.b * scale;
            return this;
        };
        Color3.prototype.add = function (otherColor) {
            return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
        };
        Color3.prototype.addToRef = function (otherColor, result) {
            result.r = this.r + otherColor.r;
            result.g = this.g + otherColor.g;
            result.b = this.b + otherColor.b;
            return this;
        };
        Color3.prototype.subtract = function (otherColor) {
            return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
        };
        Color3.prototype.subtractToRef = function (otherColor, result) {
            result.r = this.r - otherColor.r;
            result.g = this.g - otherColor.g;
            result.b = this.b - otherColor.b;
            return this;
        };
        Color3.prototype.clone = function () {
            return new Color3(this.r, this.g, this.b);
        };
        Color3.prototype.copyFrom = function (source) {
            this.r = source.r;
            this.g = source.g;
            this.b = source.b;
            return this;
        };
        Color3.prototype.copyFromFloats = function (r, g, b) {
            this.r = r;
            this.g = g;
            this.b = b;
            return this;
        };
        Color3.prototype.toHexString = function () {
            var intR = (this.r * 255) | 0;
            var intG = (this.g * 255) | 0;
            var intB = (this.b * 255) | 0;
            return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
        };
        Color3.prototype.toLinearSpace = function () {
            var convertedColor = new Color3();
            this.toLinearSpaceToRef(convertedColor);
            return convertedColor;
        };
        Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
            convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
            convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
            convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
            return this;
        };
        Color3.prototype.toGammaSpace = function () {
            var convertedColor = new Color3();
            this.toGammaSpaceToRef(convertedColor);
            return convertedColor;
        };
        Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
            convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
            convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
            convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
            return this;
        };
        // Statics
        Color3.FromHexString = function (hex) {
            if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
                //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
                return new Color3(0, 0, 0);
            }
            var r = parseInt(hex.substring(1, 3), 16);
            var g = parseInt(hex.substring(3, 5), 16);
            var b = parseInt(hex.substring(5, 7), 16);
            return Color3.FromInts(r, g, b);
        };
        Color3.FromArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            return new Color3(array[offset], array[offset + 1], array[offset + 2]);
        };
        Color3.FromInts = function (r, g, b) {
            return new Color3(r / 255.0, g / 255.0, b / 255.0);
        };
        Color3.Lerp = function (start, end, amount) {
            var r = start.r + ((end.r - start.r) * amount);
            var g = start.g + ((end.g - start.g) * amount);
            var b = start.b + ((end.b - start.b) * amount);
            return new Color3(r, g, b);
        };
        Color3.Red = function () { return new Color3(1, 0, 0); };
        Color3.Green = function () { return new Color3(0, 1, 0); };
        Color3.Blue = function () { return new Color3(0, 0, 1); };
        Color3.Black = function () { return new Color3(0, 0, 0); };
        Color3.White = function () { return new Color3(1, 1, 1); };
        Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
        Color3.Magenta = function () { return new Color3(1, 0, 1); };
        Color3.Yellow = function () { return new Color3(1, 1, 0); };
        Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
        return Color3;
    }());
    BABYLON.Color3 = Color3;
    var Color4 = (function () {
        function Color4(r, g, b, a) {
            this.r = r;
            this.g = g;
            this.b = b;
            this.a = a;
        }
        // Operators
        Color4.prototype.addInPlace = function (right) {
            this.r += right.r;
            this.g += right.g;
            this.b += right.b;
            this.a += right.a;
            return this;
        };
        Color4.prototype.asArray = function () {
            var result = [];
            this.toArray(result, 0);
            return result;
        };
        Color4.prototype.toArray = function (array, index) {
            if (index === undefined) {
                index = 0;
            }
            array[index] = this.r;
            array[index + 1] = this.g;
            array[index + 2] = this.b;
            array[index + 3] = this.a;
            return this;
        };
        Color4.prototype.add = function (right) {
            return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
        };
        Color4.prototype.subtract = function (right) {
            return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
        };
        Color4.prototype.subtractToRef = function (right, result) {
            result.r = this.r - right.r;
            result.g = this.g - right.g;
            result.b = this.b - right.b;
            result.a = this.a - right.a;
            return this;
        };
        Color4.prototype.scale = function (scale) {
            return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
        };
        Color4.prototype.scaleToRef = function (scale, result) {
            result.r = this.r * scale;
            result.g = this.g * scale;
            result.b = this.b * scale;
            result.a = this.a * scale;
            return this;
        };
        /**
          * Multipy an RGBA Color4 value by another and return a new Color4 object
          * @param color The Color4 (RGBA) value to multiply by
          * @returns A new Color4.
          */
        Color4.prototype.multiply = function (color) {
            return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
        };
        /**
         * Multipy an RGBA Color4 value by another and push the result in a reference value
         * @param color The Color4 (RGBA) value to multiply by
         * @param result The Color4 (RGBA) to fill the result in
         * @returns the result Color4.
         */
        Color4.prototype.multiplyToRef = function (color, result) {
            result.r = this.r * color.r;
            result.g = this.g * color.g;
            result.b = this.b * color.b;
            result.a = this.a * color.a;
            return result;
        };
        Color4.prototype.toString = function () {
            return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
        };
        Color4.prototype.getClassName = function () {
            return "Color4";
        };
        Color4.prototype.getHashCode = function () {
            var hash = this.r || 0;
            hash = (hash * 397) ^ (this.g || 0);
            hash = (hash * 397) ^ (this.b || 0);
            hash = (hash * 397) ^ (this.a || 0);
            return hash;
        };
        Color4.prototype.clone = function () {
            return new Color4(this.r, this.g, this.b, this.a);
        };
        Color4.prototype.copyFrom = function (source) {
            this.r = source.r;
            this.g = source.g;
            this.b = source.b;
            this.a = source.a;
            return this;
        };
        Color4.prototype.toHexString = function () {
            var intR = (this.r * 255) | 0;
            var intG = (this.g * 255) | 0;
            var intB = (this.b * 255) | 0;
            var intA = (this.a * 255) | 0;
            return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
        };
        // Statics
        Color4.FromHexString = function (hex) {
            if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
                //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
                return new Color4(0, 0, 0, 0);
            }
            var r = parseInt(hex.substring(1, 3), 16);
            var g = parseInt(hex.substring(3, 5), 16);
            var b = parseInt(hex.substring(5, 7), 16);
            var a = parseInt(hex.substring(7, 9), 16);
            return Color4.FromInts(r, g, b, a);
        };
        Color4.Lerp = function (left, right, amount) {
            var result = new Color4(0, 0, 0, 0);
            Color4.LerpToRef(left, right, amount, result);
            return result;
        };
        Color4.LerpToRef = function (left, right, amount, result) {
            result.r = left.r + (right.r - left.r) * amount;
            result.g = left.g + (right.g - left.g) * amount;
            result.b = left.b + (right.b - left.b) * amount;
            result.a = left.a + (right.a - left.a) * amount;
        };
        Color4.FromArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
        };
        Color4.FromInts = function (r, g, b, a) {
            return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
        };
        Color4.CheckColors4 = function (colors, count) {
            // Check if color3 was used
            if (colors.length === count * 3) {
                var colors4 = [];
                for (var index = 0; index < colors.length; index += 3) {
                    var newIndex = (index / 3) * 4;
                    colors4[newIndex] = colors[index];
                    colors4[newIndex + 1] = colors[index + 1];
                    colors4[newIndex + 2] = colors[index + 2];
                    colors4[newIndex + 3] = 1.0;
                }
                return colors4;
            }
            return colors;
        };
        return Color4;
    }());
    BABYLON.Color4 = Color4;
    var Vector2 = (function () {
        function Vector2(x, y) {
            this.x = x;
            this.y = y;
        }
        Vector2.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + "}";
        };
        Vector2.prototype.getClassName = function () {
            return "Vector2";
        };
        Vector2.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            return hash;
        };
        // Operators
        Vector2.prototype.toArray = function (array, index) {
            if (index === void 0) { index = 0; }
            array[index] = this.x;
            array[index + 1] = this.y;
            return this;
        };
        Vector2.prototype.asArray = function () {
            var result = [];
            this.toArray(result, 0);
            return result;
        };
        Vector2.prototype.copyFrom = function (source) {
            this.x = source.x;
            this.y = source.y;
            return this;
        };
        Vector2.prototype.copyFromFloats = function (x, y) {
            this.x = x;
            this.y = y;
            return this;
        };
        Vector2.prototype.add = function (otherVector) {
            return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
        };
        Vector2.prototype.addToRef = function (otherVector, result) {
            result.x = this.x + otherVector.x;
            result.y = this.y + otherVector.y;
            return this;
        };
        Vector2.prototype.addInPlace = function (otherVector) {
            this.x += otherVector.x;
            this.y += otherVector.y;
            return this;
        };
        Vector2.prototype.addVector3 = function (otherVector) {
            return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
        };
        Vector2.prototype.subtract = function (otherVector) {
            return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
        };
        Vector2.prototype.subtractToRef = function (otherVector, result) {
            result.x = this.x - otherVector.x;
            result.y = this.y - otherVector.y;
            return this;
        };
        Vector2.prototype.subtractInPlace = function (otherVector) {
            this.x -= otherVector.x;
            this.y -= otherVector.y;
            return this;
        };
        Vector2.prototype.multiplyInPlace = function (otherVector) {
            this.x *= otherVector.x;
            this.y *= otherVector.y;
            return this;
        };
        Vector2.prototype.multiply = function (otherVector) {
            return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
        };
        Vector2.prototype.multiplyToRef = function (otherVector, result) {
            result.x = this.x * otherVector.x;
            result.y = this.y * otherVector.y;
            return this;
        };
        Vector2.prototype.multiplyByFloats = function (x, y) {
            return new Vector2(this.x * x, this.y * y);
        };
        Vector2.prototype.divide = function (otherVector) {
            return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
        };
        Vector2.prototype.divideToRef = function (otherVector, result) {
            result.x = this.x / otherVector.x;
            result.y = this.y / otherVector.y;
            return this;
        };
        Vector2.prototype.negate = function () {
            return new Vector2(-this.x, -this.y);
        };
        Vector2.prototype.scaleInPlace = function (scale) {
            this.x *= scale;
            this.y *= scale;
            return this;
        };
        Vector2.prototype.scale = function (scale) {
            return new Vector2(this.x * scale, this.y * scale);
        };
        Vector2.prototype.equals = function (otherVector) {
            return otherVector && this.x === otherVector.x && this.y === otherVector.y;
        };
        Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
            if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
            return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
        };
        // Properties
        Vector2.prototype.length = function () {
            return Math.sqrt(this.x * this.x + this.y * this.y);
        };
        Vector2.prototype.lengthSquared = function () {
            return (this.x * this.x + this.y * this.y);
        };
        // Methods
        Vector2.prototype.normalize = function () {
            var len = this.length();
            if (len === 0)
                return this;
            var num = 1.0 / len;
            this.x *= num;
            this.y *= num;
            return this;
        };
        Vector2.prototype.clone = function () {
            return new Vector2(this.x, this.y);
        };
        // Statics
        Vector2.Zero = function () {
            return new Vector2(0, 0);
        };
        Vector2.FromArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            return new Vector2(array[offset], array[offset + 1]);
        };
        Vector2.FromArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
        };
        Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
                (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
                ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
            var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
                (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
                ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
            return new Vector2(x, y);
        };
        Vector2.Clamp = function (value, min, max) {
            var x = value.x;
            x = (x > max.x) ? max.x : x;
            x = (x < min.x) ? min.x : x;
            var y = value.y;
            y = (y > max.y) ? max.y : y;
            y = (y < min.y) ? min.y : y;
            return new Vector2(x, y);
        };
        Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
            var part2 = (-2.0 * cubed) + (3.0 * squared);
            var part3 = (cubed - (2.0 * squared)) + amount;
            var part4 = cubed - squared;
            var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
            var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
            return new Vector2(x, y);
        };
        Vector2.Lerp = function (start, end, amount) {
            var x = start.x + ((end.x - start.x) * amount);
            var y = start.y + ((end.y - start.y) * amount);
            return new Vector2(x, y);
        };
        Vector2.Dot = function (left, right) {
            return left.x * right.x + left.y * right.y;
        };
        Vector2.Normalize = function (vector) {
            var newVector = vector.clone();
            newVector.normalize();
            return newVector;
        };
        Vector2.Minimize = function (left, right) {
            var x = (left.x < right.x) ? left.x : right.x;
            var y = (left.y < right.y) ? left.y : right.y;
            return new Vector2(x, y);
        };
        Vector2.Maximize = function (left, right) {
            var x = (left.x > right.x) ? left.x : right.x;
            var y = (left.y > right.y) ? left.y : right.y;
            return new Vector2(x, y);
        };
        Vector2.Transform = function (vector, transformation) {
            var r = Vector2.Zero();
            Vector2.TransformToRef(vector, transformation, r);
            return r;
        };
        Vector2.TransformToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
            result.x = x;
            result.y = y;
        };
        Vector2.PointInTriangle = function (p, p0, p1, p2) {
            var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
            var sign = a < 0 ? -1 : 1;
            var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
            var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
            return s > 0 && t > 0 && (s + t) < 2 * a * sign;
        };
        Vector2.Distance = function (value1, value2) {
            return Math.sqrt(Vector2.DistanceSquared(value1, value2));
        };
        Vector2.DistanceSquared = function (value1, value2) {
            var x = value1.x - value2.x;
            var y = value1.y - value2.y;
            return (x * x) + (y * y);
        };
        Vector2.Center = function (value1, value2) {
            var center = value1.add(value2);
            center.scaleInPlace(0.5);
            return center;
        };
        Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
            var l2 = Vector2.DistanceSquared(segA, segB);
            if (l2 === 0.0) {
                return Vector2.Distance(p, segA);
            }
            var v = segB.subtract(segA);
            var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
            var proj = segA.add(v.multiplyByFloats(t, t));
            return Vector2.Distance(p, proj);
        };
        return Vector2;
    }());
    BABYLON.Vector2 = Vector2;
    var Vector3 = (function () {
        function Vector3(x, y, z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }
        Vector3.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
        };
        Vector3.prototype.getClassName = function () {
            return "Vector3";
        };
        Vector3.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            hash = (hash * 397) ^ (this.z || 0);
            return hash;
        };
        // Operators
        Vector3.prototype.asArray = function () {
            var result = [];
            this.toArray(result, 0);
            return result;
        };
        Vector3.prototype.toArray = function (array, index) {
            if (index === void 0) { index = 0; }
            array[index] = this.x;
            array[index + 1] = this.y;
            array[index + 2] = this.z;
            return this;
        };
        Vector3.prototype.toQuaternion = function () {
            var result = new Quaternion(0, 0, 0, 1);
            var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
            var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
            var coszMinusx = Math.cos((this.z - this.x) * 0.5);
            var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
            var cosy = Math.cos(this.y * 0.5);
            var siny = Math.sin(this.y * 0.5);
            result.x = coszMinusx * siny;
            result.y = -sinzMinusx * siny;
            result.z = sinxPlusz * cosy;
            result.w = cosxPlusz * cosy;
            return result;
        };
        Vector3.prototype.addInPlace = function (otherVector) {
            this.x += otherVector.x;
            this.y += otherVector.y;
            this.z += otherVector.z;
            return this;
        };
        Vector3.prototype.add = function (otherVector) {
            return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
        };
        Vector3.prototype.addToRef = function (otherVector, result) {
            result.x = this.x + otherVector.x;
            result.y = this.y + otherVector.y;
            result.z = this.z + otherVector.z;
            return this;
        };
        Vector3.prototype.subtractInPlace = function (otherVector) {
            this.x -= otherVector.x;
            this.y -= otherVector.y;
            this.z -= otherVector.z;
            return this;
        };
        Vector3.prototype.subtract = function (otherVector) {
            return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
        };
        Vector3.prototype.subtractToRef = function (otherVector, result) {
            result.x = this.x - otherVector.x;
            result.y = this.y - otherVector.y;
            result.z = this.z - otherVector.z;
            return this;
        };
        Vector3.prototype.subtractFromFloats = function (x, y, z) {
            return new Vector3(this.x - x, this.y - y, this.z - z);
        };
        Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
            result.x = this.x - x;
            result.y = this.y - y;
            result.z = this.z - z;
            return this;
        };
        Vector3.prototype.negate = function () {
            return new Vector3(-this.x, -this.y, -this.z);
        };
        Vector3.prototype.scaleInPlace = function (scale) {
            this.x *= scale;
            this.y *= scale;
            this.z *= scale;
            return this;
        };
        Vector3.prototype.scale = function (scale) {
            return new Vector3(this.x * scale, this.y * scale, this.z * scale);
        };
        Vector3.prototype.scaleToRef = function (scale, result) {
            result.x = this.x * scale;
            result.y = this.y * scale;
            result.z = this.z * scale;
        };
        Vector3.prototype.equals = function (otherVector) {
            return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
        };
        Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
            if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
            return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
        };
        Vector3.prototype.equalsToFloats = function (x, y, z) {
            return this.x === x && this.y === y && this.z === z;
        };
        Vector3.prototype.multiplyInPlace = function (otherVector) {
            this.x *= otherVector.x;
            this.y *= otherVector.y;
            this.z *= otherVector.z;
            return this;
        };
        Vector3.prototype.multiply = function (otherVector) {
            return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
        };
        Vector3.prototype.multiplyToRef = function (otherVector, result) {
            result.x = this.x * otherVector.x;
            result.y = this.y * otherVector.y;
            result.z = this.z * otherVector.z;
            return this;
        };
        Vector3.prototype.multiplyByFloats = function (x, y, z) {
            return new Vector3(this.x * x, this.y * y, this.z * z);
        };
        Vector3.prototype.divide = function (otherVector) {
            return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
        };
        Vector3.prototype.divideToRef = function (otherVector, result) {
            result.x = this.x / otherVector.x;
            result.y = this.y / otherVector.y;
            result.z = this.z / otherVector.z;
            return this;
        };
        Vector3.prototype.MinimizeInPlace = function (other) {
            if (other.x < this.x)
                this.x = other.x;
            if (other.y < this.y)
                this.y = other.y;
            if (other.z < this.z)
                this.z = other.z;
            return this;
        };
        Vector3.prototype.MaximizeInPlace = function (other) {
            if (other.x > this.x)
                this.x = other.x;
            if (other.y > this.y)
                this.y = other.y;
            if (other.z > this.z)
                this.z = other.z;
            return this;
        };
        // Properties
        Vector3.prototype.length = function () {
            return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
        };
        Vector3.prototype.lengthSquared = function () {
            return (this.x * this.x + this.y * this.y + this.z * this.z);
        };
        // Methods
        Vector3.prototype.normalize = function () {
            var len = this.length();
            if (len === 0 || len === 1.0)
                return this;
            var num = 1.0 / len;
            this.x *= num;
            this.y *= num;
            this.z *= num;
            return this;
        };
        Vector3.prototype.clone = function () {
            return new Vector3(this.x, this.y, this.z);
        };
        Vector3.prototype.copyFrom = function (source) {
            this.x = source.x;
            this.y = source.y;
            this.z = source.z;
            return this;
        };
        Vector3.prototype.copyFromFloats = function (x, y, z) {
            this.x = x;
            this.y = y;
            this.z = z;
            return this;
        };
        // Statics
        Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
            var d0 = Vector3.Dot(vector0, axis) - size;
            var d1 = Vector3.Dot(vector1, axis) - size;
            var s = d0 / (d0 - d1);
            return s;
        };
        Vector3.FromArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
        };
        Vector3.FromFloatArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
        };
        Vector3.FromArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
            result.z = array[offset + 2];
        };
        Vector3.FromFloatArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
            result.z = array[offset + 2];
        };
        Vector3.FromFloatsToRef = function (x, y, z, result) {
            result.x = x;
            result.y = y;
            result.z = z;
        };
        Vector3.Zero = function () {
            return new Vector3(0, 0, 0);
        };
        Vector3.Up = function () {
            return new Vector3(0, 1.0, 0);
        };
        Vector3.Forward = function () {
            return new Vector3(0, 0, 1.0);
        };
        Vector3.Right = function () {
            return new Vector3(1.0, 0, 0);
        };
        Vector3.Left = function () {
            return new Vector3(-1.0, 0, 0);
        };
        Vector3.TransformCoordinates = function (vector, transformation) {
            var result = Vector3.Zero();
            Vector3.TransformCoordinatesToRef(vector, transformation, result);
            return result;
        };
        Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
            var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
            var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
            result.x = x / w;
            result.y = y / w;
            result.z = z / w;
        };
        Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
            var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
            var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
            var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
            var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
            result.x = rx / rw;
            result.y = ry / rw;
            result.z = rz / rw;
        };
        Vector3.TransformNormal = function (vector, transformation) {
            var result = Vector3.Zero();
            Vector3.TransformNormalToRef(vector, transformation, result);
            return result;
        };
        Vector3.TransformNormalToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
            var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
            result.x = x;
            result.y = y;
            result.z = z;
        };
        Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
            result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
            result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
            result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
        };
        Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
                (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
                ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
            var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
                (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
                ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
            var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
                (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
                ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
            return new Vector3(x, y, z);
        };
        Vector3.Clamp = function (value, min, max) {
            var x = value.x;
            x = (x > max.x) ? max.x : x;
            x = (x < min.x) ? min.x : x;
            var y = value.y;
            y = (y > max.y) ? max.y : y;
            y = (y < min.y) ? min.y : y;
            var z = value.z;
            z = (z > max.z) ? max.z : z;
            z = (z < min.z) ? min.z : z;
            return new Vector3(x, y, z);
        };
        Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
            var part2 = (-2.0 * cubed) + (3.0 * squared);
            var part3 = (cubed - (2.0 * squared)) + amount;
            var part4 = cubed - squared;
            var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
            var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
            var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
            return new Vector3(x, y, z);
        };
        Vector3.Lerp = function (start, end, amount) {
            var x = start.x + ((end.x - start.x) * amount);
            var y = start.y + ((end.y - start.y) * amount);
            var z = start.z + ((end.z - start.z) * amount);
            return new Vector3(x, y, z);
        };
        Vector3.Dot = function (left, right) {
            return (left.x * right.x + left.y * right.y + left.z * right.z);
        };
        Vector3.Cross = function (left, right) {
            var result = Vector3.Zero();
            Vector3.CrossToRef(left, right, result);
            return result;
        };
        Vector3.CrossToRef = function (left, right, result) {
            Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
            Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
            Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
            result.copyFrom(Tmp.Vector3[0]);
        };
        Vector3.Normalize = function (vector) {
            var result = Vector3.Zero();
            Vector3.NormalizeToRef(vector, result);
            return result;
        };
        Vector3.NormalizeToRef = function (vector, result) {
            result.copyFrom(vector);
            result.normalize();
        };
        Vector3.Project = function (vector, world, transform, viewport) {
            var cw = viewport.width;
            var ch = viewport.height;
            var cx = viewport.x;
            var cy = viewport.y;
            var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
            Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
            var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
            world.multiplyToRef(transform, matrix);
            matrix.multiplyToRef(viewportMatrix, matrix);
            return Vector3.TransformCoordinates(vector, matrix);
        };
        Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
            var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
            world.multiplyToRef(transform, matrix);
            matrix.invert();
            source.x = source.x / viewportWidth * 2 - 1;
            source.y = -(source.y / viewportHeight * 2 - 1);
            var vector = Vector3.TransformCoordinates(source, matrix);
            var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
            if (MathTools.WithinEpsilon(num, 1.0)) {
                vector = vector.scale(1.0 / num);
            }
            return vector;
        };
        Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
            var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
            world.multiplyToRef(view, matrix);
            matrix.multiplyToRef(projection, matrix);
            matrix.invert();
            var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
            var vector = Vector3.TransformCoordinates(screenSource, matrix);
            var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
            if (MathTools.WithinEpsilon(num, 1.0)) {
                vector = vector.scale(1.0 / num);
            }
            return vector;
        };
        Vector3.Minimize = function (left, right) {
            var min = left.clone();
            min.MinimizeInPlace(right);
            return min;
        };
        Vector3.Maximize = function (left, right) {
            var max = left.clone();
            max.MaximizeInPlace(right);
            return max;
        };
        Vector3.Distance = function (value1, value2) {
            return Math.sqrt(Vector3.DistanceSquared(value1, value2));
        };
        Vector3.DistanceSquared = function (value1, value2) {
            var x = value1.x - value2.x;
            var y = value1.y - value2.y;
            var z = value1.z - value2.z;
            return (x * x) + (y * y) + (z * z);
        };
        Vector3.Center = function (value1, value2) {
            var center = value1.add(value2);
            center.scaleInPlace(0.5);
            return center;
        };
        /**
         * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
         * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
         * to something in order to rotate it from its local system to the given target system.
         */
        Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
            var rotation = Vector3.Zero();
            Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
            return rotation;
        };
        /**
         * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
         */
        Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
            var u = axis1.normalize();
            var w = axis3.normalize();
            // world axis
            var X = Axis.X;
            var Y = Axis.Y;
            // equation unknowns and vars
            var yaw = 0.0;
            var pitch = 0.0;
            var roll = 0.0;
            var x = 0.0;
            var y = 0.0;
            var z = 0.0;
            var t = 0.0;
            var sign = -1.0;
            var nbRevert = 0;
            var cross = Tmp.Vector3[0];
            var dot = 0.0;
            // step 1  : rotation around w
            // Rv3(u) = u1, and u1 belongs to plane xOz
            // Rv3(w) = w1 = w invariant
            var u1 = Tmp.Vector3[1];
            if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
                z = 1.0;
            }
            else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
                x = 1.0;
            }
            else {
                t = w.z / w.x;
                x = -t * Math.sqrt(1 / (1 + t * t));
                z = Math.sqrt(1 / (1 + t * t));
            }
            u1.x = x;
            u1.y = y;
            u1.z = z;
            u1.normalize();
            Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
            cross.normalize();
            if (Vector3.Dot(w, cross) < 0) {
                sign = 1.0;
            }
            dot = Vector3.Dot(u, u1);
            dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
            roll = Math.acos(dot) * sign;
            if (Vector3.Dot(u1, X) < 0) {
                roll = Math.PI + roll;
                u1 = u1.scaleInPlace(-1);
                nbRevert++;
            }
            // step 2 : rotate around u1
            // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
            // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
            var w2 = Tmp.Vector3[2];
            var v2 = Tmp.Vector3[3];
            x = 0.0;
            y = 0.0;
            z = 0.0;
            sign = -1.0;
            if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
                x = 1.0;
            }
            else {
                t = u1.z / u1.x;
                x = -t * Math.sqrt(1 / (1 + t * t));
                z = Math.sqrt(1 / (1 + t * t));
            }
            w2.x = x;
            w2.y = y;
            w2.z = z;
            w2.normalize();
            Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
            v2.normalize();
            Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
            cross.normalize();
            if (Vector3.Dot(u1, cross) < 0) {
                sign = 1.0;
            }
            dot = Vector3.Dot(w, w2);
            dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
            pitch = Math.acos(dot) * sign;
            if (Vector3.Dot(v2, Y) < 0) {
                pitch = Math.PI + pitch;
                nbRevert++;
            }
            // step 3 : rotate around v2
            // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
            sign = -1.0;
            Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
            cross.normalize();
            if (Vector3.Dot(cross, Y) < 0) {
                sign = 1.0;
            }
            dot = Vector3.Dot(u1, X);
            dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
            yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
            if (dot < 0 && nbRevert < 2) {
                yaw = Math.PI + yaw;
            }
            ref.x = pitch;
            ref.y = yaw;
            ref.z = roll;
        };
        return Vector3;
    }());
    BABYLON.Vector3 = Vector3;
    //Vector4 class created for EulerAngle class conversion to Quaternion
    var Vector4 = (function () {
        function Vector4(x, y, z, w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
        }
        Vector4.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
        };
        Vector4.prototype.getClassName = function () {
            return "Vector4";
        };
        Vector4.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            hash = (hash * 397) ^ (this.z || 0);
            hash = (hash * 397) ^ (this.w || 0);
            return hash;
        };
        // Operators
        Vector4.prototype.asArray = function () {
            var result = [];
            this.toArray(result, 0);
            return result;
        };
        Vector4.prototype.toArray = function (array, index) {
            if (index === undefined) {
                index = 0;
            }
            array[index] = this.x;
            array[index + 1] = this.y;
            array[index + 2] = this.z;
            array[index + 3] = this.w;
            return this;
        };
        Vector4.prototype.addInPlace = function (otherVector) {
            this.x += otherVector.x;
            this.y += otherVector.y;
            this.z += otherVector.z;
            this.w += otherVector.w;
            return this;
        };
        Vector4.prototype.add = function (otherVector) {
            return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
        };
        Vector4.prototype.addToRef = function (otherVector, result) {
            result.x = this.x + otherVector.x;
            result.y = this.y + otherVector.y;
            result.z = this.z + otherVector.z;
            result.w = this.w + otherVector.w;
            return this;
        };
        Vector4.prototype.subtractInPlace = function (otherVector) {
            this.x -= otherVector.x;
            this.y -= otherVector.y;
            this.z -= otherVector.z;
            this.w -= otherVector.w;
            return this;
        };
        Vector4.prototype.subtract = function (otherVector) {
            return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
        };
        Vector4.prototype.subtractToRef = function (otherVector, result) {
            result.x = this.x - otherVector.x;
            result.y = this.y - otherVector.y;
            result.z = this.z - otherVector.z;
            result.w = this.w - otherVector.w;
            return this;
        };
        Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
            return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
        };
        Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
            result.x = this.x - x;
            result.y = this.y - y;
            result.z = this.z - z;
            result.w = this.w - w;
            return this;
        };
        Vector4.prototype.negate = function () {
            return new Vector4(-this.x, -this.y, -this.z, -this.w);
        };
        Vector4.prototype.scaleInPlace = function (scale) {
            this.x *= scale;
            this.y *= scale;
            this.z *= scale;
            this.w *= scale;
            return this;
        };
        Vector4.prototype.scale = function (scale) {
            return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
        };
        Vector4.prototype.scaleToRef = function (scale, result) {
            result.x = this.x * scale;
            result.y = this.y * scale;
            result.z = this.z * scale;
            result.w = this.w * scale;
        };
        Vector4.prototype.equals = function (otherVector) {
            return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
        };
        Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
            if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
            return otherVector
                && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
                && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
                && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
                && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
        };
        Vector4.prototype.equalsToFloats = function (x, y, z, w) {
            return this.x === x && this.y === y && this.z === z && this.w === w;
        };
        Vector4.prototype.multiplyInPlace = function (otherVector) {
            this.x *= otherVector.x;
            this.y *= otherVector.y;
            this.z *= otherVector.z;
            this.w *= otherVector.w;
            return this;
        };
        Vector4.prototype.multiply = function (otherVector) {
            return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
        };
        Vector4.prototype.multiplyToRef = function (otherVector, result) {
            result.x = this.x * otherVector.x;
            result.y = this.y * otherVector.y;
            result.z = this.z * otherVector.z;
            result.w = this.w * otherVector.w;
            return this;
        };
        Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
            return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
        };
        Vector4.prototype.divide = function (otherVector) {
            return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
        };
        Vector4.prototype.divideToRef = function (otherVector, result) {
            result.x = this.x / otherVector.x;
            result.y = this.y / otherVector.y;
            result.z = this.z / otherVector.z;
            result.w = this.w / otherVector.w;
            return this;
        };
        Vector4.prototype.MinimizeInPlace = function (other) {
            if (other.x < this.x)
                this.x = other.x;
            if (other.y < this.y)
                this.y = other.y;
            if (other.z < this.z)
                this.z = other.z;
            if (other.w < this.w)
                this.w = other.w;
            return this;
        };
        Vector4.prototype.MaximizeInPlace = function (other) {
            if (other.x > this.x)
                this.x = other.x;
            if (other.y > this.y)
                this.y = other.y;
            if (other.z > this.z)
                this.z = other.z;
            if (other.w > this.w)
                this.w = other.w;
            return this;
        };
        // Properties
        Vector4.prototype.length = function () {
            return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
        };
        Vector4.prototype.lengthSquared = function () {
            return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
        };
        // Methods
        Vector4.prototype.normalize = function () {
            var len = this.length();
            if (len === 0)
                return this;
            var num = 1.0 / len;
            this.x *= num;
            this.y *= num;
            this.z *= num;
            this.w *= num;
            return this;
        };
        Vector4.prototype.toVector3 = function () {
            return new Vector3(this.x, this.y, this.z);
        };
        Vector4.prototype.clone = function () {
            return new Vector4(this.x, this.y, this.z, this.w);
        };
        Vector4.prototype.copyFrom = function (source) {
            this.x = source.x;
            this.y = source.y;
            this.z = source.z;
            this.w = source.w;
            return this;
        };
        Vector4.prototype.copyFromFloats = function (x, y, z, w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
            return this;
        };
        // Statics
        Vector4.FromArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
        };
        Vector4.FromArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
            result.z = array[offset + 2];
            result.w = array[offset + 3];
        };
        Vector4.FromFloatArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
            result.z = array[offset + 2];
            result.w = array[offset + 3];
        };
        Vector4.FromFloatsToRef = function (x, y, z, w, result) {
            result.x = x;
            result.y = y;
            result.z = z;
            result.w = w;
        };
        Vector4.Zero = function () {
            return new Vector4(0, 0, 0, 0);
        };
        Vector4.Normalize = function (vector) {
            var result = Vector4.Zero();
            Vector4.NormalizeToRef(vector, result);
            return result;
        };
        Vector4.NormalizeToRef = function (vector, result) {
            result.copyFrom(vector);
            result.normalize();
        };
        Vector4.Minimize = function (left, right) {
            var min = left.clone();
            min.MinimizeInPlace(right);
            return min;
        };
        Vector4.Maximize = function (left, right) {
            var max = left.clone();
            max.MaximizeInPlace(right);
            return max;
        };
        Vector4.Distance = function (value1, value2) {
            return Math.sqrt(Vector4.DistanceSquared(value1, value2));
        };
        Vector4.DistanceSquared = function (value1, value2) {
            var x = value1.x - value2.x;
            var y = value1.y - value2.y;
            var z = value1.z - value2.z;
            var w = value1.w - value2.w;
            return (x * x) + (y * y) + (z * z) + (w * w);
        };
        Vector4.Center = function (value1, value2) {
            var center = value1.add(value2);
            center.scaleInPlace(0.5);
            return center;
        };
        return Vector4;
    }());
    BABYLON.Vector4 = Vector4;
    var Size = (function () {
        function Size(width, height) {
            this.width = width;
            this.height = height;
        }
        Size.prototype.toString = function () {
            return "{W: " + this.width + ", H: " + this.height + "}";
        };
        Size.prototype.getClassName = function () {
            return "Size";
        };
        Size.prototype.getHashCode = function () {
            var hash = this.width || 0;
            hash = (hash * 397) ^ (this.height || 0);
            return hash;
        };
        Size.prototype.copyFrom = function (src) {
            this.width = src.width;
            this.height = src.height;
        };
        Size.prototype.copyFromFloats = function (width, height) {
            this.width = width;
            this.height = height;
        };
        Size.prototype.multiplyByFloats = function (w, h) {
            return new Size(this.width * w, this.height * h);
        };
        Size.prototype.clone = function () {
            return new Size(this.width, this.height);
        };
        Size.prototype.equals = function (other) {
            if (!other) {
                return false;
            }
            return (this.width === other.width) && (this.height === other.height);
        };
        Object.defineProperty(Size.prototype, "surface", {
            get: function () {
                return this.width * this.height;
            },
            enumerable: true,
            configurable: true
        });
        Size.Zero = function () {
            return new Size(0, 0);
        };
        Size.prototype.add = function (otherSize) {
            var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
            return r;
        };
        Size.prototype.substract = function (otherSize) {
            var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
            return r;
        };
        Size.Lerp = function (start, end, amount) {
            var w = start.width + ((end.width - start.width) * amount);
            var h = start.height + ((end.height - start.height) * amount);
            return new Size(w, h);
        };
        return Size;
    }());
    BABYLON.Size = Size;
    var Quaternion = (function () {
        function Quaternion(x, y, z, w) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (z === void 0) { z = 0; }
            if (w === void 0) { w = 1; }
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
        }
        Quaternion.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
        };
        Quaternion.prototype.getClassName = function () {
            return "Quaternion";
        };
        Quaternion.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            hash = (hash * 397) ^ (this.z || 0);
            hash = (hash * 397) ^ (this.w || 0);
            return hash;
        };
        Quaternion.prototype.asArray = function () {
            return [this.x, this.y, this.z, this.w];
        };
        Quaternion.prototype.equals = function (otherQuaternion) {
            return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
        };
        Quaternion.prototype.clone = function () {
            return new Quaternion(this.x, this.y, this.z, this.w);
        };
        Quaternion.prototype.copyFrom = function (other) {
            this.x = other.x;
            this.y = other.y;
            this.z = other.z;
            this.w = other.w;
            return this;
        };
        Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
            return this;
        };
        Quaternion.prototype.add = function (other) {
            return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
        };
        Quaternion.prototype.subtract = function (other) {
            return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
        };
        Quaternion.prototype.scale = function (value) {
            return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
        };
        Quaternion.prototype.multiply = function (q1) {
            var result = new Quaternion(0, 0, 0, 1.0);
            this.multiplyToRef(q1, result);
            return result;
        };
        Quaternion.prototype.multiplyToRef = function (q1, result) {
            var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
            var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
            var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
            var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
            result.copyFromFloats(x, y, z, w);
            return this;
        };
        Quaternion.prototype.multiplyInPlace = function (q1) {
            this.multiplyToRef(q1, this);
            return this;
        };
        Quaternion.prototype.conjugateToRef = function (ref) {
            ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
            return this;
        };
        Quaternion.prototype.conjugateInPlace = function () {
            this.x *= -1;
            this.y *= -1;
            this.z *= -1;
            return this;
        };
        Quaternion.prototype.conjugate = function () {
            var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
            return result;
        };
        Quaternion.prototype.length = function () {
            return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
        };
        Quaternion.prototype.normalize = function () {
            var length = 1.0 / this.length();
            this.x *= length;
            this.y *= length;
            this.z *= length;
            this.w *= length;
            return this;
        };
        Quaternion.prototype.toEulerAngles = function (order) {
            if (order === void 0) { order = "YZX"; }
            var result = Vector3.Zero();
            this.toEulerAnglesToRef(result, order);
            return result;
        };
        Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
            if (order === void 0) { order = "YZX"; }
            var qz = this.z;
            var qx = this.x;
            var qy = this.y;
            var qw = this.w;
            var sqw = qw * qw;
            var sqz = qz * qz;
            var sqx = qx * qx;
            var sqy = qy * qy;
            var zAxisY = qy * qz - qx * qw;
            var limit = .4999999;
            if (zAxisY < -limit) {
                result.y = 2 * Math.atan2(qy, qw);
                result.x = Math.PI / 2;
                result.z = 0;
            }
            else if (zAxisY > limit) {
                result.y = 2 * Math.atan2(qy, qw);
                result.x = -Math.PI / 2;
                result.z = 0;
            }
            else {
                result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
                result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
                result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
            }
            return this;
        };
        Quaternion.prototype.toRotationMatrix = function (result) {
            var xx = this.x * this.x;
            var yy = this.y * this.y;
            var zz = this.z * this.z;
            var xy = this.x * this.y;
            var zw = this.z * this.w;
            var zx = this.z * this.x;
            var yw = this.y * this.w;
            var yz = this.y * this.z;
            var xw = this.x * this.w;
            result.m[0] = 1.0 - (2.0 * (yy + zz));
            result.m[1] = 2.0 * (xy + zw);
            result.m[2] = 2.0 * (zx - yw);
            result.m[3] = 0;
            result.m[4] = 2.0 * (xy - zw);
            result.m[5] = 1.0 - (2.0 * (zz + xx));
            result.m[6] = 2.0 * (yz + xw);
            result.m[7] = 0;
            result.m[8] = 2.0 * (zx + yw);
            result.m[9] = 2.0 * (yz - xw);
            result.m[10] = 1.0 - (2.0 * (yy + xx));
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
            result.m[15] = 1.0;
            return this;
        };
        Quaternion.prototype.fromRotationMatrix = function (matrix) {
            Quaternion.FromRotationMatrixToRef(matrix, this);
            return this;
        };
        // Statics
        Quaternion.FromRotationMatrix = function (matrix) {
            var result = new Quaternion();
            Quaternion.FromRotationMatrixToRef(matrix, result);
            return result;
        };
        Quaternion.FromRotationMatrixToRef = function (matrix, result) {
            var data = matrix.m;
            var m11 = data[0], m12 = data[4], m13 = data[8];
            var m21 = data[1], m22 = data[5], m23 = data[9];
            var m31 = data[2], m32 = data[6], m33 = data[10];
            var trace = m11 + m22 + m33;
            var s;
            if (trace > 0) {
                s = 0.5 / Math.sqrt(trace + 1.0);
                result.w = 0.25 / s;
                result.x = (m32 - m23) * s;
                result.y = (m13 - m31) * s;
                result.z = (m21 - m12) * s;
            }
            else if (m11 > m22 && m11 > m33) {
                s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
                result.w = (m32 - m23) / s;
                result.x = 0.25 * s;
                result.y = (m12 + m21) / s;
                result.z = (m13 + m31) / s;
            }
            else if (m22 > m33) {
                s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
                result.w = (m13 - m31) / s;
                result.x = (m12 + m21) / s;
                result.y = 0.25 * s;
                result.z = (m23 + m32) / s;
            }
            else {
                s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
                result.w = (m21 - m12) / s;
                result.x = (m13 + m31) / s;
                result.y = (m23 + m32) / s;
                result.z = 0.25 * s;
            }
        };
        Quaternion.Inverse = function (q) {
            return new Quaternion(-q.x, -q.y, -q.z, q.w);
        };
        Quaternion.Identity = function () {
            return new Quaternion(0, 0, 0, 1);
        };
        Quaternion.RotationAxis = function (axis, angle) {
            return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
        };
        Quaternion.RotationAxisToRef = function (axis, angle, result) {
            var sin = Math.sin(angle / 2);
            axis.normalize();
            result.w = Math.cos(angle / 2);
            result.x = axis.x * sin;
            result.y = axis.y * sin;
            result.z = axis.z * sin;
            return result;
        };
        Quaternion.FromArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
        };
        Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
            var q = new Quaternion();
            Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
            return q;
        };
        Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
            // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
            var halfRoll = roll * 0.5;
            var halfPitch = pitch * 0.5;
            var halfYaw = yaw * 0.5;
            var sinRoll = Math.sin(halfRoll);
            var cosRoll = Math.cos(halfRoll);
            var sinPitch = Math.sin(halfPitch);
            var cosPitch = Math.cos(halfPitch);
            var sinYaw = Math.sin(halfYaw);
            var cosYaw = Math.cos(halfYaw);
            result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
            result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
            result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
            result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
        };
        Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
            var result = new Quaternion();
            Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
            return result;
        };
        Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
            // Produces a quaternion from Euler angles in the z-x-z orientation
            var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
            var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
            var halfBeta = beta * 0.5;
            result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
            result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
            result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
            result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
        };
        Quaternion.Slerp = function (left, right, amount) {
            var result = Quaternion.Identity();
            Quaternion.SlerpToRef(left, right, amount, result);
            return result;
        };
        Quaternion.SlerpToRef = function (left, right, amount, result) {
            var num2;
            var num3;
            var num = amount;
            var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
            var flag = false;
            if (num4 < 0) {
                flag = true;
                num4 = -num4;
            }
            if (num4 > 0.999999) {
                num3 = 1 - num;
                num2 = flag ? -num : num;
            }
            else {
                var num5 = Math.acos(num4);
                var num6 = (1.0 / Math.sin(num5));
                num3 = (Math.sin((1.0 - num) * num5)) * num6;
                num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
            }
            result.x = (num3 * left.x) + (num2 * right.x);
            result.y = (num3 * left.y) + (num2 * right.y);
            result.z = (num3 * left.z) + (num2 * right.z);
            result.w = (num3 * left.w) + (num2 * right.w);
        };
        return Quaternion;
    }());
    BABYLON.Quaternion = Quaternion;
    var Matrix = (function () {
        function Matrix() {
            this.m = new Float32Array(16);
        }
        // Properties
        Matrix.prototype.isIdentity = function () {
            if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
                return false;
            if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
                this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
                this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
                this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
                return false;
            return true;
        };
        Matrix.prototype.determinant = function () {
            var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
            var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
            var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
            var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
            var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
            var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
            return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
                (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
                (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
        };
        // Methods
        Matrix.prototype.toArray = function () {
            return this.m;
        };
        Matrix.prototype.asArray = function () {
            return this.toArray();
        };
        Matrix.prototype.invert = function () {
            this.invertToRef(this);
            return this;
        };
        Matrix.prototype.reset = function () {
            for (var index = 0; index < 16; index++) {
                this.m[index] = 0;
            }
            return this;
        };
        Matrix.prototype.add = function (other) {
            var result = new Matrix();
            this.addToRef(other, result);
            return result;
        };
        Matrix.prototype.addToRef = function (other, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = this.m[index] + other.m[index];
            }
            return this;
        };
        Matrix.prototype.addToSelf = function (other) {
            for (var index = 0; index < 16; index++) {
                this.m[index] += other.m[index];
            }
            return this;
        };
        Matrix.prototype.invertToRef = function (other) {
            var l1 = this.m[0];
            var l2 = this.m[1];
            var l3 = this.m[2];
            var l4 = this.m[3];
            var l5 = this.m[4];
            var l6 = this.m[5];
            var l7 = this.m[6];
            var l8 = this.m[7];
            var l9 = this.m[8];
            var l10 = this.m[9];
            var l11 = this.m[10];
            var l12 = this.m[11];
            var l13 = this.m[12];
            var l14 = this.m[13];
            var l15 = this.m[14];
            var l16 = this.m[15];
            var l17 = (l11 * l16) - (l12 * l15);
            var l18 = (l10 * l16) - (l12 * l14);
            var l19 = (l10 * l15) - (l11 * l14);
            var l20 = (l9 * l16) - (l12 * l13);
            var l21 = (l9 * l15) - (l11 * l13);
            var l22 = (l9 * l14) - (l10 * l13);
            var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
            var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
            var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
            var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
            var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
            var l28 = (l7 * l16) - (l8 * l15);
            var l29 = (l6 * l16) - (l8 * l14);
            var l30 = (l6 * l15) - (l7 * l14);
            var l31 = (l5 * l16) - (l8 * l13);
            var l32 = (l5 * l15) - (l7 * l13);
            var l33 = (l5 * l14) - (l6 * l13);
            var l34 = (l7 * l12) - (l8 * l11);
            var l35 = (l6 * l12) - (l8 * l10);
            var l36 = (l6 * l11) - (l7 * l10);
            var l37 = (l5 * l12) - (l8 * l9);
            var l38 = (l5 * l11) - (l7 * l9);
            var l39 = (l5 * l10) - (l6 * l9);
            other.m[0] = l23 * l27;
            other.m[4] = l24 * l27;
            other.m[8] = l25 * l27;
            other.m[12] = l26 * l27;
            other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
            other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
            other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
            other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
            other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
            other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
            other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
            other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
            other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
            other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
            other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
            other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
            return this;
        };
        Matrix.prototype.setTranslation = function (vector3) {
            this.m[12] = vector3.x;
            this.m[13] = vector3.y;
            this.m[14] = vector3.z;
            return this;
        };
        Matrix.prototype.getTranslation = function () {
            return new Vector3(this.m[12], this.m[13], this.m[14]);
        };
        Matrix.prototype.multiply = function (other) {
            var result = new Matrix();
            this.multiplyToRef(other, result);
            return result;
        };
        Matrix.prototype.copyFrom = function (other) {
            for (var index = 0; index < 16; index++) {
                this.m[index] = other.m[index];
            }
            return this;
        };
        Matrix.prototype.copyToArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            for (var index = 0; index < 16; index++) {
                array[offset + index] = this.m[index];
            }
            return this;
        };
        Matrix.prototype.multiplyToRef = function (other, result) {
            this.multiplyToArray(other, result.m, 0);
            return this;
        };
        Matrix.prototype.multiplyToArray = function (other, result, offset) {
            var tm0 = this.m[0];
            var tm1 = this.m[1];
            var tm2 = this.m[2];
            var tm3 = this.m[3];
            var tm4 = this.m[4];
            var tm5 = this.m[5];
            var tm6 = this.m[6];
            var tm7 = this.m[7];
            var tm8 = this.m[8];
            var tm9 = this.m[9];
            var tm10 = this.m[10];
            var tm11 = this.m[11];
            var tm12 = this.m[12];
            var tm13 = this.m[13];
            var tm14 = this.m[14];
            var tm15 = this.m[15];
            var om0 = other.m[0];
            var om1 = other.m[1];
            var om2 = other.m[2];
            var om3 = other.m[3];
            var om4 = other.m[4];
            var om5 = other.m[5];
            var om6 = other.m[6];
            var om7 = other.m[7];
            var om8 = other.m[8];
            var om9 = other.m[9];
            var om10 = other.m[10];
            var om11 = other.m[11];
            var om12 = other.m[12];
            var om13 = other.m[13];
            var om14 = other.m[14];
            var om15 = other.m[15];
            result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
            result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
            result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
            result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
            result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
            result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
            result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
            result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
            result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
            result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
            result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
            result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
            result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
            result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
            result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
            result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
            return this;
        };
        Matrix.prototype.equals = function (value) {
            return value &&
                (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
                    this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
                    this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
                    this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
        };
        Matrix.prototype.clone = function () {
            return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
        };
        Matrix.prototype.getClassName = function () {
            return "Matrix";
        };
        Matrix.prototype.getHashCode = function () {
            var hash = this.m[0] || 0;
            for (var i = 1; i < 16; i++) {
                hash = (hash * 397) ^ (this.m[i] || 0);
            }
            return hash;
        };
        Matrix.prototype.decompose = function (scale, rotation, translation) {
            translation.x = this.m[12];
            translation.y = this.m[13];
            translation.z = this.m[14];
            var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
            var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
            var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
            scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
            scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
            scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
            if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
                rotation.x = 0;
                rotation.y = 0;
                rotation.z = 0;
                rotation.w = 1;
                return false;
            }
            Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, Tmp.Matrix[0]);
            Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
            return true;
        };
        Matrix.prototype.getRotationMatrix = function () {
            var result = Matrix.Identity();
            this.getRotationMatrixToRef(result);
            return result;
        };
        Matrix.prototype.getRotationMatrixToRef = function (result) {
            var m = this.m;
            var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
            var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
            var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
            var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
            var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
            var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
            Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
        };
        // Statics
        Matrix.FromArray = function (array, offset) {
            var result = new Matrix();
            if (!offset) {
                offset = 0;
            }
            Matrix.FromArrayToRef(array, offset, result);
            return result;
        };
        Matrix.FromArrayToRef = function (array, offset, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = array[index + offset];
            }
        };
        Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = array[index + offset] * scale;
            }
        };
        Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
            result.m[0] = initialM11;
            result.m[1] = initialM12;
            result.m[2] = initialM13;
            result.m[3] = initialM14;
            result.m[4] = initialM21;
            result.m[5] = initialM22;
            result.m[6] = initialM23;
            result.m[7] = initialM24;
            result.m[8] = initialM31;
            result.m[9] = initialM32;
            result.m[10] = initialM33;
            result.m[11] = initialM34;
            result.m[12] = initialM41;
            result.m[13] = initialM42;
            result.m[14] = initialM43;
            result.m[15] = initialM44;
        };
        Matrix.prototype.getRow = function (index) {
            if (index < 0 || index > 3) {
                return null;
            }
            var i = index * 4;
            return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
        };
        Matrix.prototype.setRow = function (index, row) {
            if (index < 0 || index > 3) {
                return this;
            }
            var i = index * 4;
            this.m[i + 0] = row.x;
            this.m[i + 1] = row.y;
            this.m[i + 2] = row.z;
            this.m[i + 3] = row.w;
            return this;
        };
        Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
            var result = new Matrix();
            result.m[0] = initialM11;
            result.m[1] = initialM12;
            result.m[2] = initialM13;
            result.m[3] = initialM14;
            result.m[4] = initialM21;
            result.m[5] = initialM22;
            result.m[6] = initialM23;
            result.m[7] = initialM24;
            result.m[8] = initialM31;
            result.m[9] = initialM32;
            result.m[10] = initialM33;
            result.m[11] = initialM34;
            result.m[12] = initialM41;
            result.m[13] = initialM42;
            result.m[14] = initialM43;
            result.m[15] = initialM44;
            return result;
        };
        Matrix.Compose = function (scale, rotation, translation) {
            var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
            var rotationMatrix = Matrix.Identity();
            rotation.toRotationMatrix(rotationMatrix);
            result = result.multiply(rotationMatrix);
            result.setTranslation(translation);
            return result;
        };
        Matrix.Identity = function () {
            return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
        };
        Matrix.IdentityToRef = function (result) {
            Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
        };
        Matrix.Zero = function () {
            return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        };
        Matrix.RotationX = function (angle) {
            var result = new Matrix();
            Matrix.RotationXToRef(angle, result);
            return result;
        };
        Matrix.Invert = function (source) {
            var result = new Matrix();
            source.invertToRef(result);
            return result;
        };
        Matrix.RotationXToRef = function (angle, result) {
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            result.m[0] = 1.0;
            result.m[15] = 1.0;
            result.m[5] = c;
            result.m[10] = c;
            result.m[9] = -s;
            result.m[6] = s;
            result.m[1] = 0;
            result.m[2] = 0;
            result.m[3] = 0;
            result.m[4] = 0;
            result.m[7] = 0;
            result.m[8] = 0;
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
        };
        Matrix.RotationY = function (angle) {
            var result = new Matrix();
            Matrix.RotationYToRef(angle, result);
            return result;
        };
        Matrix.RotationYToRef = function (angle, result) {
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            result.m[5] = 1.0;
            result.m[15] = 1.0;
            result.m[0] = c;
            result.m[2] = -s;
            result.m[8] = s;
            result.m[10] = c;
            result.m[1] = 0;
            result.m[3] = 0;
            result.m[4] = 0;
            result.m[6] = 0;
            result.m[7] = 0;
            result.m[9] = 0;
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
        };
        Matrix.RotationZ = function (angle) {
            var result = new Matrix();
            Matrix.RotationZToRef(angle, result);
            return result;
        };
        Matrix.RotationZToRef = function (angle, result) {
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            result.m[10] = 1.0;
            result.m[15] = 1.0;
            result.m[0] = c;
            result.m[1] = s;
            result.m[4] = -s;
            result.m[5] = c;
            result.m[2] = 0;
            result.m[3] = 0;
            result.m[6] = 0;
            result.m[7] = 0;
            result.m[8] = 0;
            result.m[9] = 0;
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
        };
        Matrix.RotationAxis = function (axis, angle) {
            var result = Matrix.Zero();
            Matrix.RotationAxisToRef(axis, angle, result);
            return result;
        };
        Matrix.RotationAxisToRef = function (axis, angle, result) {
            var s = Math.sin(-angle);
            var c = Math.cos(-angle);
            var c1 = 1 - c;
            axis.normalize();
            result.m[0] = (axis.x * axis.x) * c1 + c;
            result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
            result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
            result.m[3] = 0.0;
            result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
            result.m[5] = (axis.y * axis.y) * c1 + c;
            result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
            result.m[7] = 0.0;
            result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
            result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
            result.m[10] = (axis.z * axis.z) * c1 + c;
            result.m[11] = 0.0;
            result.m[15] = 1.0;
        };
        Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
            var result = new Matrix();
            Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
            return result;
        };
        Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
            Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
            this._tempQuaternion.toRotationMatrix(result);
        };
        Matrix.Scaling = function (x, y, z) {
            var result = Matrix.Zero();
            Matrix.ScalingToRef(x, y, z, result);
            return result;
        };
        Matrix.ScalingToRef = function (x, y, z, result) {
            result.m[0] = x;
            result.m[1] = 0;
            result.m[2] = 0;
            result.m[3] = 0;
            result.m[4] = 0;
            result.m[5] = y;
            result.m[6] = 0;
            result.m[7] = 0;
            result.m[8] = 0;
            result.m[9] = 0;
            result.m[10] = z;
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
            result.m[15] = 1.0;
        };
        Matrix.Translation = function (x, y, z) {
            var result = Matrix.Identity();
            Matrix.TranslationToRef(x, y, z, result);
            return result;
        };
        Matrix.TranslationToRef = function (x, y, z, result) {
            Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
        };
        Matrix.Lerp = function (startValue, endValue, gradient) {
            var result = Matrix.Zero();
            for (var index = 0; index < 16; index++) {
                result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
            }
            return result;
        };
        Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
            var startScale = new Vector3(0, 0, 0);
            var startRotation = new Quaternion();
            var startTranslation = new Vector3(0, 0, 0);
            startValue.decompose(startScale, startRotation, startTranslation);
            var endScale = new Vector3(0, 0, 0);
            var endRotation = new Quaternion();
            var endTranslation = new Vector3(0, 0, 0);
            endValue.decompose(endScale, endRotation, endTranslation);
            var resultScale = Vector3.Lerp(startScale, endScale, gradient);
            var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
            var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
            return Matrix.Compose(resultScale, resultRotation, resultTranslation);
        };
        Matrix.LookAtLH = function (eye, target, up) {
            var result = Matrix.Zero();
            Matrix.LookAtLHToRef(eye, target, up, result);
            return result;
        };
        Matrix.LookAtLHToRef = function (eye, target, up, result) {
            // Z axis
            target.subtractToRef(eye, this._zAxis);
            this._zAxis.normalize();
            // X axis
            Vector3.CrossToRef(up, this._zAxis, this._xAxis);
            if (this._xAxis.lengthSquared() === 0) {
                this._xAxis.x = 1.0;
            }
            else {
                this._xAxis.normalize();
            }
            // Y axis
            Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
            this._yAxis.normalize();
            // Eye angles
            var ex = -Vector3.Dot(this._xAxis, eye);
            var ey = -Vector3.Dot(this._yAxis, eye);
            var ez = -Vector3.Dot(this._zAxis, eye);
            return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
        };
        Matrix.LookAtRH = function (eye, target, up) {
            var result = Matrix.Zero();
            Matrix.LookAtRHToRef(eye, target, up, result);
            return result;
        };
        Matrix.LookAtRHToRef = function (eye, target, up, result) {
            // Z axis
            eye.subtractToRef(target, this._zAxis);
            this._zAxis.normalize();
            // X axis
            Vector3.CrossToRef(up, this._zAxis, this._xAxis);
            if (this._xAxis.lengthSquared() === 0) {
                this._xAxis.x = 1.0;
            }
            else {
                this._xAxis.normalize();
            }
            // Y axis
            Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
            this._yAxis.normalize();
            // Eye angles
            var ex = -Vector3.Dot(this._xAxis, eye);
            var ey = -Vector3.Dot(this._yAxis, eye);
            var ez = -Vector3.Dot(this._zAxis, eye);
            return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
        };
        Matrix.OrthoLH = function (width, height, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
            return matrix;
        };
        Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
            var hw = 2.0 / width;
            var hh = 2.0 / height;
            var id = 1.0 / (zfar - znear);
            var nid = znear / (znear - zfar);
            Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
        };
        Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
            return matrix;
        };
        Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
            result.m[0] = 2.0 / (right - left);
            result.m[1] = result.m[2] = result.m[3] = 0;
            result.m[5] = 2.0 / (top - bottom);
            result.m[4] = result.m[6] = result.m[7] = 0;
            result.m[10] = 1.0 / (zfar - znear);
            result.m[8] = result.m[9] = result.m[11] = 0;
            result.m[12] = (left + right) / (left - right);
            result.m[13] = (top + bottom) / (bottom - top);
            result.m[14] = -znear / (zfar - znear);
            result.m[15] = 1.0;
        };
        Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
            return matrix;
        };
        Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
            Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
            result.m[10] *= -1.0;
        };
        Matrix.PerspectiveLH = function (width, height, znear, zfar) {
            var matrix = Matrix.Zero();
            matrix.m[0] = (2.0 * znear) / width;
            matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
            matrix.m[5] = (2.0 * znear) / height;
            matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
            matrix.m[10] = -zfar / (znear - zfar);
            matrix.m[8] = matrix.m[9] = 0.0;
            matrix.m[11] = 1.0;
            matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
            matrix.m[14] = (znear * zfar) / (znear - zfar);
            return matrix;
        };
        Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
            return matrix;
        };
        Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
            if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
            var tan = 1.0 / (Math.tan(fov * 0.5));
            if (isVerticalFovFixed) {
                result.m[0] = tan / aspect;
            }
            else {
                result.m[0] = tan;
            }
            result.m[1] = result.m[2] = result.m[3] = 0.0;
            if (isVerticalFovFixed) {
                result.m[5] = tan;
            }
            else {
                result.m[5] = tan * aspect;
            }
            result.m[4] = result.m[6] = result.m[7] = 0.0;
            result.m[8] = result.m[9] = 0.0;
            result.m[10] = zfar / (zfar - znear);
            result.m[11] = 1.0;
            result.m[12] = result.m[13] = result.m[15] = 0.0;
            result.m[14] = -(znear * zfar) / (zfar - znear);
        };
        Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
            return matrix;
        };
        Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
            if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
            var tan = 1.0 / (Math.tan(fov * 0.5));
            if (isVerticalFovFixed) {
                result.m[0] = tan / aspect;
            }
            else {
                result.m[0] = tan;
            }
            result.m[1] = result.m[2] = result.m[3] = 0.0;
            if (isVerticalFovFixed) {
                result.m[5] = tan;
            }
            else {
                result.m[5] = tan * aspect;
            }
            result.m[4] = result.m[6] = result.m[7] = 0.0;
            result.m[8] = result.m[9] = 0.0;
            result.m[10] = zfar / (znear - zfar);
            result.m[11] = -1.0;
            result.m[12] = result.m[13] = result.m[15] = 0.0;
            result.m[14] = (znear * zfar) / (znear - zfar);
        };
        Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
            if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
            var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
            var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
            var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
            var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
            var xScale = 2.0 / (leftTan + rightTan);
            var yScale = 2.0 / (upTan + downTan);
            result.m[0] = xScale;
            result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
            result.m[5] = yScale;
            result.m[6] = result.m[7] = 0.0;
            result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
            result.m[9] = -((upTan - downTan) * yScale * 0.5);
            //result.m[10] = -(znear + zfar) / (zfar - znear);
            result.m[10] = -zfar / (znear - zfar);
            result.m[11] = 1.0;
            result.m[12] = result.m[13] = result.m[15] = 0.0;
            //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
            result.m[14] = (znear * zfar) / (znear - zfar);
        };
        Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
            var cw = viewport.width;
            var ch = viewport.height;
            var cx = viewport.x;
            var cy = viewport.y;
            var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
            return world.multiply(view).multiply(projection).multiply(viewportMatrix);
        };
        Matrix.GetAsMatrix2x2 = function (matrix) {
            return new Float32Array([
                matrix.m[0], matrix.m[1],
                matrix.m[4], matrix.m[5]
            ]);
        };
        Matrix.GetAsMatrix3x3 = function (matrix) {
            return new Float32Array([
                matrix.m[0], matrix.m[1], matrix.m[2],
                matrix.m[4], matrix.m[5], matrix.m[6],
                matrix.m[8], matrix.m[9], matrix.m[10]
            ]);
        };
        Matrix.Transpose = function (matrix) {
            var result = new Matrix();
            result.m[0] = matrix.m[0];
            result.m[1] = matrix.m[4];
            result.m[2] = matrix.m[8];
            result.m[3] = matrix.m[12];
            result.m[4] = matrix.m[1];
            result.m[5] = matrix.m[5];
            result.m[6] = matrix.m[9];
            result.m[7] = matrix.m[13];
            result.m[8] = matrix.m[2];
            result.m[9] = matrix.m[6];
            result.m[10] = matrix.m[10];
            result.m[11] = matrix.m[14];
            result.m[12] = matrix.m[3];
            result.m[13] = matrix.m[7];
            result.m[14] = matrix.m[11];
            result.m[15] = matrix.m[15];
            return result;
        };
        Matrix.Reflection = function (plane) {
            var matrix = new Matrix();
            Matrix.ReflectionToRef(plane, matrix);
            return matrix;
        };
        Matrix.ReflectionToRef = function (plane, result) {
            plane.normalize();
            var x = plane.normal.x;
            var y = plane.normal.y;
            var z = plane.normal.z;
            var temp = -2 * x;
            var temp2 = -2 * y;
            var temp3 = -2 * z;
            result.m[0] = (temp * x) + 1;
            result.m[1] = temp2 * x;
            result.m[2] = temp3 * x;
            result.m[3] = 0.0;
            result.m[4] = temp * y;
            result.m[5] = (temp2 * y) + 1;
            result.m[6] = temp3 * y;
            result.m[7] = 0.0;
            result.m[8] = temp * z;
            result.m[9] = temp2 * z;
            result.m[10] = (temp3 * z) + 1;
            result.m[11] = 0.0;
            result.m[12] = temp * plane.d;
            result.m[13] = temp2 * plane.d;
            result.m[14] = temp3 * plane.d;
            result.m[15] = 1.0;
        };
        Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
            mat.m[0] = xaxis.x;
            mat.m[1] = xaxis.y;
            mat.m[2] = xaxis.z;
            mat.m[3] = 0;
            mat.m[4] = yaxis.x;
            mat.m[5] = yaxis.y;
            mat.m[6] = yaxis.z;
            mat.m[7] = 0;
            mat.m[8] = zaxis.x;
            mat.m[9] = zaxis.y;
            mat.m[10] = zaxis.z;
            mat.m[11] = 0;
            mat.m[12] = 0;
            mat.m[13] = 0;
            mat.m[14] = 0;
            mat.m[15] = 1;
        };
        Matrix.FromQuaternionToRef = function (quat, result) {
            var xx = quat.x * quat.x;
            var yy = quat.y * quat.y;
            var zz = quat.z * quat.z;
            var xy = quat.x * quat.y;
            var zw = quat.z * quat.w;
            var zx = quat.z * quat.x;
            var yw = quat.y * quat.w;
            var yz = quat.y * quat.z;
            var xw = quat.x * quat.w;
            result.m[0] = 1.0 - (2.0 * (yy + zz));
            result.m[1] = 2.0 * (xy + zw);
            result.m[2] = 2.0 * (zx - yw);
            result.m[3] = 0;
            result.m[4] = 2.0 * (xy - zw);
            result.m[5] = 1.0 - (2.0 * (zz + xx));
            result.m[6] = 2.0 * (yz + xw);
            result.m[7] = 0;
            result.m[8] = 2.0 * (zx + yw);
            result.m[9] = 2.0 * (yz - xw);
            result.m[10] = 1.0 - (2.0 * (yy + xx));
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
            result.m[15] = 1.0;
        };
        Matrix._tempQuaternion = new Quaternion();
        Matrix._xAxis = Vector3.Zero();
        Matrix._yAxis = Vector3.Zero();
        Matrix._zAxis = Vector3.Zero();
        return Matrix;
    }());
    BABYLON.Matrix = Matrix;
    var Plane = (function () {
        function Plane(a, b, c, d) {
            this.normal = new Vector3(a, b, c);
            this.d = d;
        }
        Plane.prototype.asArray = function () {
            return [this.normal.x, this.normal.y, this.normal.z, this.d];
        };
        // Methods
        Plane.prototype.clone = function () {
            return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
        };
        Plane.prototype.getClassName = function () {
            return "Plane";
        };
        Plane.prototype.getHashCode = function () {
            var hash = this.normal.getHashCode();
            hash = (hash * 397) ^ (this.d || 0);
            return hash;
        };
        Plane.prototype.normalize = function () {
            var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
            var magnitude = 0;
            if (norm !== 0) {
                magnitude = 1.0 / norm;
            }
            this.normal.x *= magnitude;
            this.normal.y *= magnitude;
            this.normal.z *= magnitude;
            this.d *= magnitude;
            return this;
        };
        Plane.prototype.transform = function (transformation) {
            var transposedMatrix = Matrix.Transpose(transformation);
            var x = this.normal.x;
            var y = this.normal.y;
            var z = this.normal.z;
            var d = this.d;
            var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
            var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
            var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
            var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
            return new Plane(normalX, normalY, normalZ, finalD);
        };
        Plane.prototype.dotCoordinate = function (point) {
            return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
        };
        Plane.prototype.copyFromPoints = function (point1, point2, point3) {
            var x1 = point2.x - point1.x;
            var y1 = point2.y - point1.y;
            var z1 = point2.z - point1.z;
            var x2 = point3.x - point1.x;
            var y2 = point3.y - point1.y;
            var z2 = point3.z - point1.z;
            var yz = (y1 * z2) - (z1 * y2);
            var xz = (z1 * x2) - (x1 * z2);
            var xy = (x1 * y2) - (y1 * x2);
            var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
            var invPyth;
            if (pyth !== 0) {
                invPyth = 1.0 / pyth;
            }
            else {
                invPyth = 0;
            }
            this.normal.x = yz * invPyth;
            this.normal.y = xz * invPyth;
            this.normal.z = xy * invPyth;
            this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
            return this;
        };
        Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
            var dot = Vector3.Dot(this.normal, direction);
            return (dot <= epsilon);
        };
        Plane.prototype.signedDistanceTo = function (point) {
            return Vector3.Dot(point, this.normal) + this.d;
        };
        // Statics
        Plane.FromArray = function (array) {
            return new Plane(array[0], array[1], array[2], array[3]);
        };
        Plane.FromPoints = function (point1, point2, point3) {
            var result = new Plane(0, 0, 0, 0);
            result.copyFromPoints(point1, point2, point3);
            return result;
        };
        Plane.FromPositionAndNormal = function (origin, normal) {
            var result = new Plane(0, 0, 0, 0);
            normal.normalize();
            result.normal = normal;
            result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
            return result;
        };
        Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
            var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
            return Vector3.Dot(point, normal) + d;
        };
        return Plane;
    }());
    BABYLON.Plane = Plane;
    var Viewport = (function () {
        function Viewport(x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
        Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
            return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
        };
        return Viewport;
    }());
    BABYLON.Viewport = Viewport;
    var Frustum = (function () {
        function Frustum() {
        }
        Frustum.GetPlanes = function (transform) {
            var frustumPlanes = [];
            for (var index = 0; index < 6; index++) {
                frustumPlanes.push(new Plane(0, 0, 0, 0));
            }
            Frustum.GetPlanesToRef(transform, frustumPlanes);
            return frustumPlanes;
        };
        Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
            // Near
            frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
            frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
            frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
            frustumPlanes[0].d = transform.m[15] + transform.m[14];
            frustumPlanes[0].normalize();
            // Far
            frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
            frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
            frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
            frustumPlanes[1].d = transform.m[15] - transform.m[14];
            frustumPlanes[1].normalize();
            // Left
            frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
            frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
            frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
            frustumPlanes[2].d = transform.m[15] + transform.m[12];
            frustumPlanes[2].normalize();
            // Right
            frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
            frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
            frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
            frustumPlanes[3].d = transform.m[15] - transform.m[12];
            frustumPlanes[3].normalize();
            // Top
            frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
            frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
            frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
            frustumPlanes[4].d = transform.m[15] - transform.m[13];
            frustumPlanes[4].normalize();
            // Bottom
            frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
            frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
            frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
            frustumPlanes[5].d = transform.m[15] + transform.m[13];
            frustumPlanes[5].normalize();
        };
        return Frustum;
    }());
    BABYLON.Frustum = Frustum;
    (function (Space) {
        Space[Space["LOCAL"] = 0] = "LOCAL";
        Space[Space["WORLD"] = 1] = "WORLD";
    })(BABYLON.Space || (BABYLON.Space = {}));
    var Space = BABYLON.Space;
    var Axis = (function () {
        function Axis() {
        }
        Axis.X = new Vector3(1, 0, 0);
        Axis.Y = new Vector3(0, 1, 0);
        Axis.Z = new Vector3(0, 0, 1);
        return Axis;
    }());
    BABYLON.Axis = Axis;
    ;
    var BezierCurve = (function () {
        function BezierCurve() {
        }
        BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
            // Extract X (which is equal to time here)
            var f0 = 1 - 3 * x2 + 3 * x1;
            var f1 = 3 * x2 - 6 * x1;
            var f2 = 3 * x1;
            var refinedT = t;
            for (var i = 0; i < 5; i++) {
                var refinedT2 = refinedT * refinedT;
                var refinedT3 = refinedT2 * refinedT;
                var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
                var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
                refinedT -= (x - t) * slope;
                refinedT = Math.min(1, Math.max(0, refinedT));
            }
            // Resolve cubic bezier for the given x
            return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
                3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
                Math.pow(refinedT, 3);
        };
        return BezierCurve;
    }());
    BABYLON.BezierCurve = BezierCurve;
    (function (Orientation) {
        Orientation[Orientation["CW"] = 0] = "CW";
        Orientation[Orientation["CCW"] = 1] = "CCW";
    })(BABYLON.Orientation || (BABYLON.Orientation = {}));
    var Orientation = BABYLON.Orientation;
    var Angle = (function () {
        function Angle(radians) {
            var _this = this;
            this.degrees = function () { return _this._radians * 180 / Math.PI; };
            this.radians = function () { return _this._radians; };
            this._radians = radians;
            if (this._radians < 0)
                this._radians += (2 * Math.PI);
        }
        Angle.BetweenTwoPoints = function (a, b) {
            var delta = b.subtract(a);
            var theta = Math.atan2(delta.y, delta.x);
            return new Angle(theta);
        };
        Angle.FromRadians = function (radians) {
            return new Angle(radians);
        };
        Angle.FromDegrees = function (degrees) {
            return new Angle(degrees * Math.PI / 180);
        };
        return Angle;
    }());
    BABYLON.Angle = Angle;
    var Arc2 = (function () {
        function Arc2(startPoint, midPoint, endPoint) {
            this.startPoint = startPoint;
            this.midPoint = midPoint;
            this.endPoint = endPoint;
            var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
            var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
            var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
            var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
            this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
            this.radius = this.centerPoint.subtract(this.startPoint).length();
            this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
            var a1 = this.startAngle.degrees();
            var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
            var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
            // angles correction
            if (a2 - a1 > +180.0)
                a2 -= 360.0;
            if (a2 - a1 < -180.0)
                a2 += 360.0;
            if (a3 - a2 > +180.0)
                a3 -= 360.0;
            if (a3 - a2 < -180.0)
                a3 += 360.0;
            this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
            this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
        }
        return Arc2;
    }());
    BABYLON.Arc2 = Arc2;
    var Path2 = (function () {
        function Path2(x, y) {
            this._points = new Array();
            this._length = 0;
            this.closed = false;
            this._points.push(new Vector2(x, y));
        }
        Path2.prototype.addLineTo = function (x, y) {
            if (closed) {
                //Tools.Error("cannot add lines to closed paths");
                return this;
            }
            var newPoint = new Vector2(x, y);
            var previousPoint = this._points[this._points.length - 1];
            this._points.push(newPoint);
            this._length += newPoint.subtract(previousPoint).length();
            return this;
        };
        Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
            if (numberOfSegments === void 0) { numberOfSegments = 36; }
            if (closed) {
                //Tools.Error("cannot add arcs to closed paths");
                return this;
            }
            var startPoint = this._points[this._points.length - 1];
            var midPoint = new Vector2(midX, midY);
            var endPoint = new Vector2(endX, endY);
            var arc = new Arc2(startPoint, midPoint, endPoint);
            var increment = arc.angle.radians() / numberOfSegments;
            if (arc.orientation === Orientation.CW)
                increment *= -1;
            var currentAngle = arc.startAngle.radians() + increment;
            for (var i = 0; i < numberOfSegments; i++) {
                var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
                var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
                this.addLineTo(x, y);
                currentAngle += increment;
            }
            return this;
        };
        Path2.prototype.close = function () {
            this.closed = true;
            return this;
        };
        Path2.prototype.length = function () {
            var result = this._length;
            if (!this.closed) {
                var lastPoint = this._points[this._points.length - 1];
                var firstPoint = this._points[0];
                result += (firstPoint.subtract(lastPoint).length());
            }
            return result;
        };
        Path2.prototype.getPoints = function () {
            return this._points;
        };
        Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
            if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
                //Tools.Error("normalized length position should be between 0 and 1.");
                return Vector2.Zero();
            }
            var lengthPosition = normalizedLengthPosition * this.length();
            var previousOffset = 0;
            for (var i = 0; i < this._points.length; i++) {
                var j = (i + 1) % this._points.length;
                var a = this._points[i];
                var b = this._points[j];
                var bToA = b.subtract(a);
                var nextOffset = (bToA.length() + previousOffset);
                if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
                    var dir = bToA.normalize();
                    var localOffset = lengthPosition - previousOffset;
                    return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
                }
                previousOffset = nextOffset;
            }
            //Tools.Error("internal error");
            return Vector2.Zero();
        };
        Path2.StartingAt = function (x, y) {
            return new Path2(x, y);
        };
        return Path2;
    }());
    BABYLON.Path2 = Path2;
    var Path3D = (function () {
        /**
        * new Path3D(path, normal, raw)
        * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
        * please read the description in the tutorial :  http://doc.babylonjs.com/tutorials/How_to_use_Path3D
        * path : an array of Vector3, the curve axis of the Path3D
        * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
        * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
        */
        function Path3D(path, firstNormal, raw) {
            this.path = path;
            this._curve = new Array();
            this._distances = new Array();
            this._tangents = new Array();
            this._normals = new Array();
            this._binormals = new Array();
            for (var p = 0; p < path.length; p++) {
                this._curve[p] = path[p].clone(); // hard copy
            }
            this._raw = raw || false;
            this._compute(firstNormal);
        }
        /**
         * Returns the Path3D array of successive Vector3 designing its curve.
         */
        Path3D.prototype.getCurve = function () {
            return this._curve;
        };
        /**
         * Returns an array populated with tangent vectors on each Path3D curve point.
         */
        Path3D.prototype.getTangents = function () {
            return this._tangents;
        };
        /**
         * Returns an array populated with normal vectors on each Path3D curve point.
         */
        Path3D.prototype.getNormals = function () {
            return this._normals;
        };
        /**
         * Returns an array populated with binormal vectors on each Path3D curve point.
         */
        Path3D.prototype.getBinormals = function () {
            return this._binormals;
        };
        /**
         * Returns an array populated with distances (float) of the i-th point from the first curve point.
         */
        Path3D.prototype.getDistances = function () {
            return this._distances;
        };
        /**
         * Forces the Path3D tangent, normal, binormal and distance recomputation.
         * Returns the same object updated.
         */
        Path3D.prototype.update = function (path, firstNormal) {
            for (var p = 0; p < path.length; p++) {
                this._curve[p].x = path[p].x;
                this._curve[p].y = path[p].y;
                this._curve[p].z = path[p].z;
            }
            this._compute(firstNormal);
            return this;
        };
        // private function compute() : computes tangents, normals and binormals
        Path3D.prototype._compute = function (firstNormal) {
            var l = this._curve.length;
            // first and last tangents
            this._tangents[0] = this._getFirstNonNullVector(0);
            if (!this._raw) {
                this._tangents[0].normalize();
            }
            this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
            if (!this._raw) {
                this._tangents[l - 1].normalize();
            }
            // normals and binormals at first point : arbitrary vector with _normalVector()
            var tg0 = this._tangents[0];
            var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
            this._normals[0] = pp0;
            if (!this._raw) {
                this._normals[0].normalize();
            }
            this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
            if (!this._raw) {
                this._binormals[0].normalize();
            }
            this._distances[0] = 0.0;
            // normals and binormals : next points
            var prev; // previous vector (segment)
            var cur; // current vector (segment)
            var curTang; // current tangent
            // previous normal
            var prevBinor; // previous binormal
            for (var i = 1; i < l; i++) {
                // tangents
                prev = this._getLastNonNullVector(i);
                if (i < l - 1) {
                    cur = this._getFirstNonNullVector(i);
                    this._tangents[i] = prev.add(cur);
                    this._tangents[i].normalize();
                }
                this._distances[i] = this._distances[i - 1] + prev.length();
                // normals and binormals
                // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
                curTang = this._tangents[i];
                prevBinor = this._binormals[i - 1];
                this._normals[i] = Vector3.Cross(prevBinor, curTang);
                if (!this._raw) {
                    this._normals[i].normalize();
                }
                this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
                if (!this._raw) {
                    this._binormals[i].normalize();
                }
            }
        };
        // private function getFirstNonNullVector(index)
        // returns the first non null vector from index : curve[index + N].subtract(curve[index])
        Path3D.prototype._getFirstNonNullVector = function (index) {
            var i = 1;
            var nNVector = this._curve[index + i].subtract(this._curve[index]);
            while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
                i++;
                nNVector = this._curve[index + i].subtract(this._curve[index]);
            }
            return nNVector;
        };
        // private function getLastNonNullVector(index)
        // returns the last non null vector from index : curve[index].subtract(curve[index - N])
        Path3D.prototype._getLastNonNullVector = function (index) {
            var i = 1;
            var nLVector = this._curve[index].subtract(this._curve[index - i]);
            while (nLVector.length() === 0 && index > i + 1) {
                i++;
                nLVector = this._curve[index].subtract(this._curve[index - i]);
            }
            return nLVector;
        };
        // private function normalVector(v0, vt, va) :
        // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
        // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
        Path3D.prototype._normalVector = function (v0, vt, va) {
            var normal0;
            var tgl = vt.length();
            if (tgl === 0.0) {
                tgl = 1.0;
            }
            if (va === undefined || va === null) {
                var point;
                if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
                    point = new Vector3(0.0, -1.0, 0.0);
                }
                else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
                    point = new Vector3(1.0, 0.0, 0.0);
                }
                else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
                    point = new Vector3(0.0, 0.0, 1.0);
                }
                normal0 = Vector3.Cross(vt, point);
            }
            else {
                normal0 = Vector3.Cross(vt, va);
                Vector3.CrossToRef(normal0, vt, normal0);
            }
            normal0.normalize();
            return normal0;
        };
        return Path3D;
    }());
    BABYLON.Path3D = Path3D;
    var Curve3 = (function () {
        /**
         * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
         * A Curve3 is designed from a series of successive Vector3.
         * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
         */
        function Curve3(points) {
            this._length = 0.0;
            this._points = points;
            this._length = this._computeLength(points);
        }
        /**
         * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
         * @param v0 (Vector3) the origin point of the Quadratic Bezier
         * @param v1 (Vector3) the control point
         * @param v2 (Vector3) the end point of the Quadratic Bezier
         * @param nbPoints (integer) the wanted number of points in the curve
         */
        Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
            nbPoints = nbPoints > 2 ? nbPoints : 3;
            var bez = new Array();
            var equation = function (t, val0, val1, val2) {
                var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
                return res;
            };
            for (var i = 0; i <= nbPoints; i++) {
                bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
            }
            return new Curve3(bez);
        };
        /**
         * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
         * @param v0 (Vector3) the origin point of the Cubic Bezier
         * @param v1 (Vector3) the first control point
         * @param v2 (Vector3) the second control point
         * @param v3 (Vector3) the end point of the Cubic Bezier
         * @param nbPoints (integer) the wanted number of points in the curve
         */
        Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
            nbPoints = nbPoints > 3 ? nbPoints : 4;
            var bez = new Array();
            var equation = function (t, val0, val1, val2, val3) {
                var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
                return res;
            };
            for (var i = 0; i <= nbPoints; i++) {
                bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
            }
            return new Curve3(bez);
        };
        /**
         * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
         * @param p1 (Vector3) the origin point of the Hermite Spline
         * @param t1 (Vector3) the tangent vector at the origin point
         * @param p2 (Vector3) the end point of the Hermite Spline
         * @param t2 (Vector3) the tangent vector at the end point
         * @param nbPoints (integer) the wanted number of points in the curve
         */
        Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
            var hermite = new Array();
            var step = 1.0 / nbPoints;
            for (var i = 0; i <= nbPoints; i++) {
                hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
            }
            return new Curve3(hermite);
        };
        /**
         * Returns the Curve3 stored array of successive Vector3
         */
        Curve3.prototype.getPoints = function () {
            return this._points;
        };
        /**
         * Returns the computed length (float) of the curve.
         */
        Curve3.prototype.length = function () {
            return this._length;
        };
        /**
         * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
         * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
         * curveA and curveB keep unchanged.
         */
        Curve3.prototype.continue = function (curve) {
            var lastPoint = this._points[this._points.length - 1];
            var continuedPoints = this._points.slice();
            var curvePoints = curve.getPoints();
            for (var i = 1; i < curvePoints.length; i++) {
                continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
            }
            var continuedCurve = new Curve3(continuedPoints);
            return continuedCurve;
        };
        Curve3.prototype._computeLength = function (path) {
            var l = 0;
            for (var i = 1; i < path.length; i++) {
                l += (path[i].subtract(path[i - 1])).length();
            }
            return l;
        };
        return Curve3;
    }());
    BABYLON.Curve3 = Curve3;
    // SphericalHarmonics
    var SphericalHarmonics = (function () {
        function SphericalHarmonics() {
            this.L00 = Vector3.Zero();
            this.L1_1 = Vector3.Zero();
            this.L10 = Vector3.Zero();
            this.L11 = Vector3.Zero();
            this.L2_2 = Vector3.Zero();
            this.L2_1 = Vector3.Zero();
            this.L20 = Vector3.Zero();
            this.L21 = Vector3.Zero();
            this.L22 = Vector3.Zero();
        }
        SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
            var colorVector = new Vector3(color.r, color.g, color.b);
            var c = colorVector.scale(deltaSolidAngle);
            this.L00 = this.L00.add(c.scale(0.282095));
            this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
            this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
            this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
            this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
            this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
            this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
            this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
            this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
        };
        SphericalHarmonics.prototype.scale = function (scale) {
            this.L00 = this.L00.scale(scale);
            this.L1_1 = this.L1_1.scale(scale);
            this.L10 = this.L10.scale(scale);
            this.L11 = this.L11.scale(scale);
            this.L2_2 = this.L2_2.scale(scale);
            this.L2_1 = this.L2_1.scale(scale);
            this.L20 = this.L20.scale(scale);
            this.L21 = this.L21.scale(scale);
            this.L22 = this.L22.scale(scale);
        };
        return SphericalHarmonics;
    }());
    BABYLON.SphericalHarmonics = SphericalHarmonics;
    // SphericalPolynomial
    var SphericalPolynomial = (function () {
        function SphericalPolynomial() {
            this.x = Vector3.Zero();
            this.y = Vector3.Zero();
            this.z = Vector3.Zero();
            this.xx = Vector3.Zero();
            this.yy = Vector3.Zero();
            this.zz = Vector3.Zero();
            this.xy = Vector3.Zero();
            this.yz = Vector3.Zero();
            this.zx = Vector3.Zero();
        }
        SphericalPolynomial.prototype.addAmbient = function (color) {
            var colorVector = new Vector3(color.r, color.g, color.b);
            this.xx = this.xx.add(colorVector);
            this.yy = this.yy.add(colorVector);
            this.zz = this.zz.add(colorVector);
        };
        SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
            var result = new SphericalPolynomial();
            result.x = harmonics.L11.scale(1.02333);
            result.y = harmonics.L1_1.scale(1.02333);
            result.z = harmonics.L10.scale(1.02333);
            result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
            result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
            result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
            result.yz = harmonics.L2_1.scale(0.858086);
            result.zx = harmonics.L21.scale(0.858086);
            result.xy = harmonics.L2_2.scale(0.858086);
            return result;
        };
        return SphericalPolynomial;
    }());
    BABYLON.SphericalPolynomial = SphericalPolynomial;
    // Vertex formats
    var PositionNormalVertex = (function () {
        function PositionNormalVertex(position, normal) {
            if (position === void 0) { position = Vector3.Zero(); }
            if (normal === void 0) { normal = Vector3.Up(); }
            this.position = position;
            this.normal = normal;
        }
        PositionNormalVertex.prototype.clone = function () {
            return new PositionNormalVertex(this.position.clone(), this.normal.clone());
        };
        return PositionNormalVertex;
    }());
    BABYLON.PositionNormalVertex = PositionNormalVertex;
    var PositionNormalTextureVertex = (function () {
        function PositionNormalTextureVertex(position, normal, uv) {
            if (position === void 0) { position = Vector3.Zero(); }
            if (normal === void 0) { normal = Vector3.Up(); }
            if (uv === void 0) { uv = Vector2.Zero(); }
            this.position = position;
            this.normal = normal;
            this.uv = uv;
        }
        PositionNormalTextureVertex.prototype.clone = function () {
            return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
        };
        return PositionNormalTextureVertex;
    }());
    BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
    // Temporary pre-allocated objects for engine internal use
    // usage in any internal function :
    // var tmp = Tmp.Vector3[0];   <= gets access to the first pre-created Vector3
    // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
    var Tmp = (function () {
        function Tmp() {
        }
        Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
        Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
        Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
            Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
        Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
        Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
        Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
            Matrix.Zero(), Matrix.Zero(),
            Matrix.Zero(), Matrix.Zero(),
            Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
        return Tmp;
    }());
    BABYLON.Tmp = Tmp;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.math.js.map
 
 
 
//# sourceMappingURL=babylon.mixins.js.map
 
var BABYLON;
(function (BABYLON) {
    function generateSerializableMember(type, sourceName) {
        return function (target, propertyKey) {
            if (!target.__serializableMembers) {
                target.__serializableMembers = {};
            }
            if (!target.__serializableMembers[propertyKey]) {
                target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
            }
        };
    }
    function serialize(sourceName) {
        return generateSerializableMember(0, sourceName); // value member
    }
    BABYLON.serialize = serialize;
    function serializeAsTexture(sourceName) {
        return generateSerializableMember(1, sourceName); // texture member
    }
    BABYLON.serializeAsTexture = serializeAsTexture;
    function serializeAsColor3(sourceName) {
        return generateSerializableMember(2, sourceName); // color3 member
    }
    BABYLON.serializeAsColor3 = serializeAsColor3;
    function serializeAsFresnelParameters(sourceName) {
        return generateSerializableMember(3, sourceName); // fresnel parameters member
    }
    BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
    function serializeAsVector2(sourceName) {
        return generateSerializableMember(4, sourceName); // vector2 member
    }
    BABYLON.serializeAsVector2 = serializeAsVector2;
    function serializeAsVector3(sourceName) {
        return generateSerializableMember(5, sourceName); // vector3 member
    }
    BABYLON.serializeAsVector3 = serializeAsVector3;
    function serializeAsMeshReference(sourceName) {
        return generateSerializableMember(6, sourceName); // mesh reference member
    }
    BABYLON.serializeAsMeshReference = serializeAsMeshReference;
    function serializeAsColorCurves(sourceName) {
        return generateSerializableMember(7, sourceName); // color curves
    }
    BABYLON.serializeAsColorCurves = serializeAsColorCurves;
    var SerializationHelper = (function () {
        function SerializationHelper() {
        }
        SerializationHelper.Serialize = function (entity, serializationObject) {
            if (!serializationObject) {
                serializationObject = {};
            }
            // Tags
            serializationObject.tags = BABYLON.Tags.GetTags(entity);
            // Properties
            for (var property in entity.__serializableMembers) {
                var propertyDescriptor = entity.__serializableMembers[property];
                var targetPropertyName = propertyDescriptor.sourceName || property;
                var propertyType = propertyDescriptor.type;
                var sourceProperty = entity[property];
                if (sourceProperty !== undefined && sourceProperty !== null) {
                    switch (propertyType) {
                        case 0:
                            serializationObject[targetPropertyName] = sourceProperty;
                            break;
                        case 1:
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                        case 2:
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 3:
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                        case 4:
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 5:
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 6:
                            serializationObject[targetPropertyName] = sourceProperty.id;
                            break;
                        case 7:
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                    }
                }
            }
            return serializationObject;
        };
        SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
            var destination = creationFunction();
            // Tags
            BABYLON.Tags.AddTagsTo(destination, source.tags);
            // Properties
            for (var property in destination.__serializableMembers) {
                var propertyDescriptor = destination.__serializableMembers[property];
                var sourceProperty = source[propertyDescriptor.sourceName || property];
                var propertyType = propertyDescriptor.type;
                if (sourceProperty !== undefined && sourceProperty !== null) {
                    switch (propertyType) {
                        case 0:
                            destination[property] = sourceProperty;
                            break;
                        case 1:
                            destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
                            break;
                        case 2:
                            destination[property] = BABYLON.Color3.FromArray(sourceProperty);
                            break;
                        case 3:
                            destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
                            break;
                        case 4:
                            destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
                            break;
                        case 5:
                            destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
                            break;
                        case 6:
                            destination[property] = scene.getLastMeshByID(sourceProperty);
                            break;
                        case 7:
                            destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
                            break;
                    }
                }
            }
            return destination;
        };
        SerializationHelper.Clone = function (creationFunction, source) {
            var destination = creationFunction();
            // Tags
            BABYLON.Tags.AddTagsTo(destination, source.tags);
            // Properties
            for (var property in destination.__serializableMembers) {
                var propertyDescriptor = destination.__serializableMembers[property];
                var sourceProperty = source[property];
                var propertyType = propertyDescriptor.type;
                if (sourceProperty !== undefined && sourceProperty !== null) {
                    switch (propertyType) {
                        case 0: // Value
                        case 6:
                            destination[property] = sourceProperty;
                            break;
                        case 1: // Texture
                        case 2: // Color3
                        case 3: // FresnelParameters
                        case 4: // Vector2
                        case 5: // Vector3
                        case 7:
                            destination[property] = sourceProperty.clone();
                            break;
                    }
                }
            }
            return destination;
        };
        return SerializationHelper;
    }());
    BABYLON.SerializationHelper = SerializationHelper;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.decorators.js.map
 
var BABYLON;
(function (BABYLON) {
    /**
     * A class serves as a medium between the observable and its observers
     */
    var EventState = (function () {
        /**
        * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
        */
        function EventState(mask, skipNextObservers) {
            if (skipNextObservers === void 0) { skipNextObservers = false; }
            this.initalize(mask, skipNextObservers);
        }
        EventState.prototype.initalize = function (mask, skipNextObservers) {
            if (skipNextObservers === void 0) { skipNextObservers = false; }
            this.mask = mask;
            this.skipNextObservers = skipNextObservers;
            return this;
        };
        return EventState;
    }());
    BABYLON.EventState = EventState;
    /**
     * Represent an Observer registered to a given Observable object.
     */
    var Observer = (function () {
        function Observer(callback, mask) {
            this.callback = callback;
            this.mask = mask;
        }
        return Observer;
    }());
    BABYLON.Observer = Observer;
    /**
     * The Observable class is a simple implementation of the Observable pattern.
     * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
     * This enable a more fine grained execution without having to rely on multiple different Observable objects.
     * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
     * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
     */
    var Observable = (function () {
        function Observable() {
            this._observers = new Array();
            this._eventState = new EventState(0);
        }
        /**
         * Create a new Observer with the specified callback
         * @param callback the callback that will be executed for that Observer
         * @param mask the mask used to filter observers
         * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
         */
        Observable.prototype.add = function (callback, mask, insertFirst) {
            if (mask === void 0) { mask = -1; }
            if (insertFirst === void 0) { insertFirst = false; }
            if (!callback) {
                return null;
            }
            var observer = new Observer(callback, mask);
            if (insertFirst) {
                this._observers.unshift(observer);
            }
            else {
                this._observers.push(observer);
            }
            return observer;
        };
        /**
         * Remove an Observer from the Observable object
         * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
         */
        Observable.prototype.remove = function (observer) {
            var index = this._observers.indexOf(observer);
            if (index !== -1) {
                this._observers.splice(index, 1);
                return true;
            }
            return false;
        };
        /**
         * Remove a callback from the Observable object
         * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
        */
        Observable.prototype.removeCallback = function (callback) {
            for (var index = 0; index < this._observers.length; index++) {
                if (this._observers[index].callback === callback) {
                    this._observers.splice(index, 1);
                    return true;
                }
            }
            return false;
        };
        /**
         * Notify all Observers by calling their respective callback with the given data
         * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
         * @param eventData
         * @param mask
         */
        Observable.prototype.notifyObservers = function (eventData, mask) {
            if (mask === void 0) { mask = -1; }
            var state = this._eventState;
            state.mask = mask;
            state.skipNextObservers = false;
            for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
                var obs = _a[_i];
                if (obs.mask & mask) {
                    obs.callback(eventData, state);
                }
                if (state.skipNextObservers) {
                    return false;
                }
            }
            return true;
        };
        /**
         * return true is the Observable has at least one Observer registered
         */
        Observable.prototype.hasObservers = function () {
            return this._observers.length > 0;
        };
        /**
        * Clear the list of observers
        */
        Observable.prototype.clear = function () {
            this._observers = new Array();
        };
        /**
        * Clone the current observable
        */
        Observable.prototype.clone = function () {
            var result = new Observable();
            result._observers = this._observers.slice(0);
            return result;
        };
        return Observable;
    }());
    BABYLON.Observable = Observable;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.observable.js.map
 
var BABYLON;
(function (BABYLON) {
    var Database = (function () {
        function Database(urlToScene, callbackManifestChecked) {
            // Handling various flavors of prefixed version of IndexedDB
            this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
            this.callbackManifestChecked = callbackManifestChecked;
            this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
            this.db = null;
            this.enableSceneOffline = false;
            this.enableTexturesOffline = false;
            this.manifestVersionFound = 0;
            this.mustUpdateRessources = false;
            this.hasReachedQuota = false;
            if (!Database.IDBStorageEnabled) {
                this.callbackManifestChecked(true);
            }
            else {
                this.checkManifestFile();
            }
        }
        Database.prototype.checkManifestFile = function () {
            var _this = this;
            function noManifestFile() {
                that.enableSceneOffline = false;
                that.enableTexturesOffline = false;
                that.callbackManifestChecked(false);
            }
            var that = this;
            var timeStampUsed = false;
            var manifestURL = this.currentSceneUrl + ".manifest";
            var xhr = new XMLHttpRequest();
            if (navigator.onLine) {
                // Adding a timestamp to by-pass browsers' cache
                timeStampUsed = true;
                manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
            }
            xhr.open("GET", manifestURL, true);
            xhr.addEventListener("load", function () {
                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
                    try {
                        var manifestFile = JSON.parse(xhr.response);
                        _this.enableSceneOffline = manifestFile.enableSceneOffline;
                        _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
                        if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
                            _this.manifestVersionFound = manifestFile.version;
                        }
                        if (_this.callbackManifestChecked) {
                            _this.callbackManifestChecked(true);
                        }
                    }
                    catch (ex) {
                        noManifestFile();
                    }
                }
                else {
                    noManifestFile();
                }
            }, false);
            xhr.addEventListener("error", function (event) {
                if (timeStampUsed) {
                    timeStampUsed = false;
                    // Let's retry without the timeStamp
                    // It could fail when coupled with HTML5 Offline API
                    var retryManifestURL = _this.currentSceneUrl + ".manifest";
                    xhr.open("GET", retryManifestURL, true);
                    xhr.send();
                }
                else {
                    noManifestFile();
                }
            }, false);
            try {
                xhr.send();
            }
            catch (ex) {
                BABYLON.Tools.Error("Error on XHR send request.");
                that.callbackManifestChecked(false);
            }
        };
        Database.prototype.openAsync = function (successCallback, errorCallback) {
            var _this = this;
            function handleError() {
                that.isSupported = false;
                if (errorCallback)
                    errorCallback();
            }
            var that = this;
            if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
                // Your browser doesn't support IndexedDB
                this.isSupported = false;
                if (errorCallback)
                    errorCallback();
            }
            else {
                // If the DB hasn't been opened or created yet
                if (!this.db) {
                    this.hasReachedQuota = false;
                    this.isSupported = true;
                    var request = this.idbFactory.open("babylonjs", 1);
                    // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
                    request.onerror = function (event) {
                        handleError();
                    };
                    // executes when a version change transaction cannot complete due to other active transactions
                    request.onblocked = function (event) {
                        BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
                        handleError();
                    };
                    // DB has been opened successfully
                    request.onsuccess = function (event) {
                        _this.db = request.result;
                        successCallback();
                    };
                    // Initialization of the DB. Creating Scenes & Textures stores
                    request.onupgradeneeded = function (event) {
                        _this.db = (event.target).result;
                        try {
                            var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
                            var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
                            var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
                        }
                        catch (ex) {
                            BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
                            handleError();
                        }
                    };
                }
                else {
                    if (successCallback)
                        successCallback();
                }
            }
        };
        Database.prototype.loadImageFromDB = function (url, image) {
            var _this = this;
            var completeURL = Database.ReturnFullUrlLocation(url);
            var saveAndLoadImage = function () {
                if (!_this.hasReachedQuota && _this.db !== null) {
                    // the texture is not yet in the DB, let's try to save it
                    _this._saveImageIntoDBAsync(completeURL, image);
                }
                else {
                    image.src = url;
                }
            };
            if (!this.mustUpdateRessources) {
                this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
            }
            else {
                saveAndLoadImage();
            }
        };
        Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
            if (this.isSupported && this.db !== null) {
                var texture;
                var transaction = this.db.transaction(["textures"]);
                transaction.onabort = function (event) {
                    image.src = url;
                };
                transaction.oncomplete = function (event) {
                    var blobTextureURL;
                    if (texture) {
                        var URL = window.URL || window.webkitURL;
                        blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
                        image.onerror = function () {
                            BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
                            image.src = url;
                        };
                        image.src = blobTextureURL;
                    }
                    else {
                        notInDBCallback();
                    }
                };
                var getRequest = transaction.objectStore("textures").get(url);
                getRequest.onsuccess = function (event) {
                    texture = (event.target).result;
                };
                getRequest.onerror = function (event) {
                    BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
                    image.src = url;
                };
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                image.src = url;
            }
        };
        Database.prototype._saveImageIntoDBAsync = function (url, image) {
            var _this = this;
            if (this.isSupported) {
                // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
                var generateBlobUrl = function () {
                    var blobTextureURL;
                    if (blob) {
                        var URL = window.URL || window.webkitURL;
                        try {
                            blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
                        }
                        // Chrome is raising a type error if we're setting the oneTimeOnly parameter
                        catch (ex) {
                            blobTextureURL = URL.createObjectURL(blob);
                        }
                    }
                    image.src = blobTextureURL;
                };
                if (Database.IsUASupportingBlobStorage) {
                    var xhr = new XMLHttpRequest(), blob;
                    xhr.open("GET", url, true);
                    xhr.responseType = "blob";
                    xhr.addEventListener("load", function () {
                        if (xhr.status === 200) {
                            // Blob as response (XHR2)
                            blob = xhr.response;
                            var transaction = _this.db.transaction(["textures"], "readwrite");
                            // the transaction could abort because of a QuotaExceededError error
                            transaction.onabort = function (event) {
                                try {
                                    //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
                                    if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
                                        _this.hasReachedQuota = true;
                                    }
                                }
                                catch (ex) { }
                                generateBlobUrl();
                            };
                            transaction.oncomplete = function (event) {
                                generateBlobUrl();
                            };
                            var newTexture = { textureUrl: url, data: blob };
                            try {
                                // Put the blob into the dabase
                                var addRequest = transaction.objectStore("textures").put(newTexture);
                                addRequest.onsuccess = function (event) {
                                };
                                addRequest.onerror = function (event) {
                                    generateBlobUrl();
                                };
                            }
                            catch (ex) {
                                // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
                                if (ex.code === 25) {
                                    Database.IsUASupportingBlobStorage = false;
                                }
                                image.src = url;
                            }
                        }
                        else {
                            image.src = url;
                        }
                    }, false);
                    xhr.addEventListener("error", function (event) {
                        BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
                        image.src = url;
                    }, false);
                    xhr.send();
                }
                else {
                    image.src = url;
                }
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                image.src = url;
            }
        };
        Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
            var _this = this;
            var updateVersion = function (event) {
                // the version is not yet in the DB or we need to update it
                _this._saveVersionIntoDBAsync(url, versionLoaded);
            };
            this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
        };
        Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
            var _this = this;
            if (this.isSupported) {
                var version;
                try {
                    var transaction = this.db.transaction(["versions"]);
                    transaction.oncomplete = function (event) {
                        if (version) {
                            // If the version in the JSON file is > than the version in DB
                            if (_this.manifestVersionFound > version.data) {
                                _this.mustUpdateRessources = true;
                                updateInDBCallback();
                            }
                            else {
                                callback(version.data);
                            }
                        }
                        else {
                            _this.mustUpdateRessources = true;
                            updateInDBCallback();
                        }
                    };
                    transaction.onabort = function (event) {
                        callback(-1);
                    };
                    var getRequest = transaction.objectStore("versions").get(url);
                    getRequest.onsuccess = function (event) {
                        version = (event.target).result;
                    };
                    getRequest.onerror = function (event) {
                        BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
                        callback(-1);
                    };
                }
                catch (ex) {
                    BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
                    callback(-1);
                }
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                callback(-1);
            }
        };
        Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
            var _this = this;
            if (this.isSupported && !this.hasReachedQuota) {
                try {
                    // Open a transaction to the database
                    var transaction = this.db.transaction(["versions"], "readwrite");
                    // the transaction could abort because of a QuotaExceededError error
                    transaction.onabort = function (event) {
                        try {
                            if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
                                _this.hasReachedQuota = true;
                            }
                        }
                        catch (ex) { }
                        callback(-1);
                    };
                    transaction.oncomplete = function (event) {
                        callback(_this.manifestVersionFound);
                    };
                    var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
                    // Put the scene into the database
                    var addRequest = transaction.objectStore("versions").put(newVersion);
                    addRequest.onsuccess = function (event) {
                    };
                    addRequest.onerror = function (event) {
                        BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
                    };
                }
                catch (ex) {
                    BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
                    callback(-1);
                }
            }
            else {
                callback(-1);
            }
        };
        Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
            var _this = this;
            var completeUrl = Database.ReturnFullUrlLocation(url);
            var saveAndLoadFile = function (event) {
                // the scene is not yet in the DB, let's try to save it
                _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
            };
            this._checkVersionFromDB(completeUrl, function (version) {
                if (version !== -1) {
                    if (!_this.mustUpdateRessources) {
                        _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
                    }
                    else {
                        _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
                    }
                }
                else {
                    errorCallback();
                }
            });
        };
        Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
            if (this.isSupported) {
                var targetStore;
                if (url.indexOf(".babylon") !== -1) {
                    targetStore = "scenes";
                }
                else {
                    targetStore = "textures";
                }
                var file;
                var transaction = this.db.transaction([targetStore]);
                transaction.oncomplete = function (event) {
                    if (file) {
                        callback(file.data);
                    }
                    else {
                        notInDBCallback();
                    }
                };
                transaction.onabort = function (event) {
                    notInDBCallback();
                };
                var getRequest = transaction.objectStore(targetStore).get(url);
                getRequest.onsuccess = function (event) {
                    file = (event.target).result;
                };
                getRequest.onerror = function (event) {
                    BABYLON.Tools.Error("Error loading file " + url + " from DB.");
                    notInDBCallback();
                };
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                callback();
            }
        };
        Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
            var _this = this;
            if (this.isSupported) {
                var targetStore;
                if (url.indexOf(".babylon") !== -1) {
                    targetStore = "scenes";
                }
                else {
                    targetStore = "textures";
                }
                // Create XHR
                var xhr = new XMLHttpRequest(), fileData;
                xhr.open("GET", url, true);
                if (useArrayBuffer) {
                    xhr.responseType = "arraybuffer";
                }
                xhr.onprogress = progressCallback;
                xhr.addEventListener("load", function () {
                    if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
                        // Blob as response (XHR2)
                        //fileData = xhr.responseText;
                        fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
                        if (!_this.hasReachedQuota) {
                            // Open a transaction to the database
                            var transaction = _this.db.transaction([targetStore], "readwrite");
                            // the transaction could abort because of a QuotaExceededError error
                            transaction.onabort = function (event) {
                                try {
                                    //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
                                    if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
                                        _this.hasReachedQuota = true;
                                    }
                                }
                                catch (ex) { }
                                callback(fileData);
                            };
                            transaction.oncomplete = function (event) {
                                callback(fileData);
                            };
                            var newFile;
                            if (targetStore === "scenes") {
                                newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
                            }
                            else {
                                newFile = { textureUrl: url, data: fileData };
                            }
                            try {
                                // Put the scene into the database
                                var addRequest = transaction.objectStore(targetStore).put(newFile);
                                addRequest.onsuccess = function (event) {
                                };
                                addRequest.onerror = function (event) {
                                    BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
                                };
                            }
                            catch (ex) {
                                callback(fileData);
                            }
                        }
                        else {
                            callback(fileData);
                        }
                    }
                    else {
                        callback();
                    }
                }, false);
                xhr.addEventListener("error", function (event) {
                    BABYLON.Tools.Error("error on XHR request.");
                    callback();
                }, false);
                xhr.send();
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                callback();
            }
        };
        Database.IsUASupportingBlobStorage = true;
        Database.IDBStorageEnabled = true;
        Database.parseURL = function (url) {
            var a = document.createElement('a');
            a.href = url;
            var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
            var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
            var absLocation = url.substring(0, url.indexOf(fileName, 0));
            return absLocation;
        };
        Database.ReturnFullUrlLocation = function (url) {
            if (url.indexOf("http:/") === -1) {
                return (Database.parseURL(window.location.href) + url);
            }
            else {
                return url;
            }
        };
        return Database;
    }());
    BABYLON.Database = Database;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.database.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        /*
        * Based on jsTGALoader - Javascript loader for TGA file
        * By Vincent Thibault
        * @blog http://blog.robrowser.com/javascript-tga-loader.html
        */
        var TGATools = (function () {
            function TGATools() {
            }
            TGATools.GetTGAHeader = function (data) {
                var offset = 0;
                var header = {
                    id_length: data[offset++],
                    colormap_type: data[offset++],
                    image_type: data[offset++],
                    colormap_index: data[offset++] | data[offset++] << 8,
                    colormap_length: data[offset++] | data[offset++] << 8,
                    colormap_size: data[offset++],
                    origin: [
                        data[offset++] | data[offset++] << 8,
                        data[offset++] | data[offset++] << 8
                    ],
                    width: data[offset++] | data[offset++] << 8,
                    height: data[offset++] | data[offset++] << 8,
                    pixel_size: data[offset++],
                    flags: data[offset++]
                };
                return header;
            };
            TGATools.UploadContent = function (gl, data) {
                // Not enough data to contain header ?
                if (data.length < 19) {
                    BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
                    return;
                }
                // Read Header
                var offset = 18;
                var header = TGATools.GetTGAHeader(data);
                // Assume it's a valid Targa file.
                if (header.id_length + offset > data.length) {
                    BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
                    return;
                }
                // Skip not needed data
                offset += header.id_length;
                var use_rle = false;
                var use_pal = false;
                var use_rgb = false;
                var use_grey = false;
                // Get some informations.
                switch (header.image_type) {
                    case TGATools._TYPE_RLE_INDEXED:
                        use_rle = true;
                    case TGATools._TYPE_INDEXED:
                        use_pal = true;
                        break;
                    case TGATools._TYPE_RLE_RGB:
                        use_rle = true;
                    case TGATools._TYPE_RGB:
                        use_rgb = true;
                        break;
                    case TGATools._TYPE_RLE_GREY:
                        use_rle = true;
                    case TGATools._TYPE_GREY:
                        use_grey = true;
                        break;
                }
                var pixel_data;
                var numAlphaBits = header.flags & 0xf;
                var pixel_size = header.pixel_size >> 3;
                var pixel_total = header.width * header.height * pixel_size;
                // Read palettes
                var palettes;
                if (use_pal) {
                    palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
                }
                // Read LRE
                if (use_rle) {
                    pixel_data = new Uint8Array(pixel_total);
                    var c, count, i;
                    var localOffset = 0;
                    var pixels = new Uint8Array(pixel_size);
                    while (offset < pixel_total && localOffset < pixel_total) {
                        c = data[offset++];
                        count = (c & 0x7f) + 1;
                        // RLE pixels
                        if (c & 0x80) {
                            // Bind pixel tmp array
                            for (i = 0; i < pixel_size; ++i) {
                                pixels[i] = data[offset++];
                            }
                            // Copy pixel array
                            for (i = 0; i < count; ++i) {
                                pixel_data.set(pixels, localOffset + i * pixel_size);
                            }
                            localOffset += pixel_size * count;
                        }
                        else {
                            count *= pixel_size;
                            for (i = 0; i < count; ++i) {
                                pixel_data[localOffset + i] = data[offset++];
                            }
                            localOffset += count;
                        }
                    }
                }
                else {
                    pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
                }
                // Load to texture
                var x_start, y_start, x_step, y_step, y_end, x_end;
                switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
                    default:
                    case TGATools._ORIGIN_UL:
                        x_start = 0;
                        x_step = 1;
                        x_end = header.width;
                        y_start = 0;
                        y_step = 1;
                        y_end = header.height;
                        break;
                    case TGATools._ORIGIN_BL:
                        x_start = 0;
                        x_step = 1;
                        x_end = header.width;
                        y_start = header.height - 1;
                        y_step = -1;
                        y_end = -1;
                        break;
                    case TGATools._ORIGIN_UR:
                        x_start = header.width - 1;
                        x_step = -1;
                        x_end = -1;
                        y_start = 0;
                        y_step = 1;
                        y_end = header.height;
                        break;
                    case TGATools._ORIGIN_BR:
                        x_start = header.width - 1;
                        x_step = -1;
                        x_end = -1;
                        y_start = header.height - 1;
                        y_step = -1;
                        y_end = -1;
                        break;
                }
                // Load the specify method
                var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
                var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
            };
            TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
                var image = pixel_data, colormap = palettes;
                var width = header.width, height = header.height;
                var color, i = 0, x, y;
                var imageData = new Uint8Array(width * height * 4);
                for (y = y_start; y !== y_end; y += y_step) {
                    for (x = x_start; x !== x_end; x += x_step, i++) {
                        color = image[i];
                        imageData[(x + width * y) * 4 + 3] = 255;
                        imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
                        imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
                        imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
                    }
                }
                return imageData;
            };
            TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
                var image = pixel_data;
                var width = header.width, height = header.height;
                var color, i = 0, x, y;
                var imageData = new Uint8Array(width * height * 4);
                for (y = y_start; y !== y_end; y += y_step) {
                    for (x = x_start; x !== x_end; x += x_step, i += 2) {
                        color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
                        imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
                        imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
                        imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
                        imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
                    }
                }
                return imageData;
            };
            TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
                var image = pixel_data;
                var width = header.width, height = header.height;
                var i = 0, x, y;
                var imageData = new Uint8Array(width * height * 4);
                for (y = y_start; y !== y_end; y += y_step) {
                    for (x = x_start; x !== x_end; x += x_step, i += 3) {
                        imageData[(x + width * y) * 4 + 3] = 255;
                        imageData[(x + width * y) * 4 + 2] = image[i + 0];
                        imageData[(x + width * y) * 4 + 1] = image[i + 1];
                        imageData[(x + width * y) * 4 + 0] = image[i + 2];
                    }
                }
                return imageData;
            };
            TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
                var image = pixel_data;
                var width = header.width, height = header.height;
                var i = 0, x, y;
                var imageData = new Uint8Array(width * height * 4);
                for (y = y_start; y !== y_end; y += y_step) {
                    for (x = x_start; x !== x_end; x += x_step, i += 4) {
                        imageData[(x + width * y) * 4 + 2] = image[i + 0];
                        imageData[(x + width * y) * 4 + 1] = image[i + 1];
                        imageData[(x + width * y) * 4 + 0] = image[i + 2];
                        imageData[(x + width * y) * 4 + 3] = image[i + 3];
                    }
                }
                return imageData;
            };
            TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
                var image = pixel_data;
                var width = header.width, height = header.height;
                var color, i = 0, x, y;
                var imageData = new Uint8Array(width * height * 4);
                for (y = y_start; y !== y_end; y += y_step) {
                    for (x = x_start; x !== x_end; x += x_step, i++) {
                        color = image[i];
                        imageData[(x + width * y) * 4 + 0] = color;
                        imageData[(x + width * y) * 4 + 1] = color;
                        imageData[(x + width * y) * 4 + 2] = color;
                        imageData[(x + width * y) * 4 + 3] = 255;
                    }
                }
                return imageData;
            };
            TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
                var image = pixel_data;
                var width = header.width, height = header.height;
                var i = 0, x, y;
                var imageData = new Uint8Array(width * height * 4);
                for (y = y_start; y !== y_end; y += y_step) {
                    for (x = x_start; x !== x_end; x += x_step, i += 2) {
                        imageData[(x + width * y) * 4 + 0] = image[i + 0];
                        imageData[(x + width * y) * 4 + 1] = image[i + 0];
                        imageData[(x + width * y) * 4 + 2] = image[i + 0];
                        imageData[(x + width * y) * 4 + 3] = image[i + 1];
                    }
                }
                return imageData;
            };
            TGATools._TYPE_NO_DATA = 0;
            TGATools._TYPE_INDEXED = 1;
            TGATools._TYPE_RGB = 2;
            TGATools._TYPE_GREY = 3;
            TGATools._TYPE_RLE_INDEXED = 9;
            TGATools._TYPE_RLE_RGB = 10;
            TGATools._TYPE_RLE_GREY = 11;
            TGATools._ORIGIN_MASK = 0x30;
            TGATools._ORIGIN_SHIFT = 0x04;
            TGATools._ORIGIN_BL = 0x00;
            TGATools._ORIGIN_BR = 0x01;
            TGATools._ORIGIN_UL = 0x02;
            TGATools._ORIGIN_UR = 0x03;
            return TGATools;
        }());
        Internals.TGATools = TGATools;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.tga.js.map
 
var BABYLON;
(function (BABYLON) {
    var SmartArray = (function () {
        function SmartArray(capacity) {
            this.length = 0;
            this._duplicateId = 0;
            this.data = new Array(capacity);
            this._id = SmartArray._GlobalId++;
        }
        SmartArray.prototype.push = function (value) {
            this.data[this.length++] = value;
            if (this.length > this.data.length) {
                this.data.length *= 2;
            }
            if (!value.__smartArrayFlags) {
                value.__smartArrayFlags = {};
            }
            value.__smartArrayFlags[this._id] = this._duplicateId;
        };
        SmartArray.prototype.pushNoDuplicate = function (value) {
            if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
                return false;
            }
            this.push(value);
            return true;
        };
        SmartArray.prototype.sort = function (compareFn) {
            this.data.sort(compareFn);
        };
        SmartArray.prototype.reset = function () {
            this.length = 0;
            this._duplicateId++;
        };
        SmartArray.prototype.concat = function (array) {
            if (array.length === 0) {
                return;
            }
            if (this.length + array.length > this.data.length) {
                this.data.length = (this.length + array.length) * 2;
            }
            for (var index = 0; index < array.length; index++) {
                this.data[this.length++] = (array.data || array)[index];
            }
        };
        SmartArray.prototype.concatWithNoDuplicate = function (array) {
            if (array.length === 0) {
                return;
            }
            if (this.length + array.length > this.data.length) {
                this.data.length = (this.length + array.length) * 2;
            }
            for (var index = 0; index < array.length; index++) {
                var item = (array.data || array)[index];
                this.pushNoDuplicate(item);
            }
        };
        SmartArray.prototype.indexOf = function (value) {
            var position = this.data.indexOf(value);
            if (position >= this.length) {
                return -1;
            }
            return position;
        };
        // Statics
        SmartArray._GlobalId = 0;
        return SmartArray;
    }());
    BABYLON.SmartArray = SmartArray;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.smartArray.js.map
 
var BABYLON;
(function (BABYLON) {
    /**
     * This class implement a typical dictionary using a string as key and the generic type T as value.
     * The underlying implementation relies on an associative array to ensure the best performances.
     * The value can be anything including 'null' but except 'undefined'
     */
    var StringDictionary = (function () {
        function StringDictionary() {
            this._count = 0;
            this._data = {};
        }
        /**
         * This will clear this dictionary and copy the content from the 'source' one.
         * If the T value is a custom object, it won't be copied/cloned, the same object will be used
         * @param source the dictionary to take the content from and copy to this dictionary
         */
        StringDictionary.prototype.copyFrom = function (source) {
            var _this = this;
            this.clear();
            source.forEach(function (t, v) { return _this.add(t, v); });
        };
        /**
         * Get a value based from its key
         * @param key the given key to get the matching value from
         * @return the value if found, otherwise undefined is returned
         */
        StringDictionary.prototype.get = function (key) {
            var val = this._data[key];
            if (val !== undefined) {
                return val;
            }
            return undefined;
        };
        /**
         * Get a value from its key or add it if it doesn't exist.
         * This method will ensure you that a given key/data will be present in the dictionary.
         * @param key the given key to get the matching value from
         * @param factory the factory that will create the value if the key is not present in the dictionary.
         * The factory will only be invoked if there's no data for the given key.
         * @return the value corresponding to the key.
         */
        StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
            var val = this.get(key);
            if (val !== undefined) {
                return val;
            }
            val = factory(key);
            if (val) {
                this.add(key, val);
            }
            return val;
        };
        /**
         * Get a value from its key if present in the dictionary otherwise add it
         * @param key the key to get the value from
         * @param val if there's no such key/value pair in the dictionary add it with this value
         * @return the value corresponding to the key
         */
        StringDictionary.prototype.getOrAdd = function (key, val) {
            var curVal = this.get(key);
            if (curVal !== undefined) {
                return curVal;
            }
            this.add(key, val);
            return val;
        };
        /**
         * Check if there's a given key in the dictionary
         * @param key the key to check for
         * @return true if the key is present, false otherwise
         */
        StringDictionary.prototype.contains = function (key) {
            return this._data[key] !== undefined;
        };
        /**
         * Add a new key and its corresponding value
         * @param key the key to add
         * @param value the value corresponding to the key
         * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
         */
        StringDictionary.prototype.add = function (key, value) {
            if (this._data[key] !== undefined) {
                return false;
            }
            this._data[key] = value;
            ++this._count;
            return true;
        };
        StringDictionary.prototype.set = function (key, value) {
            if (this._data[key] === undefined) {
                return false;
            }
            this._data[key] = value;
            return true;
        };
        /**
         * Get the element of the given key and remove it from the dictionary
         * @param key
         */
        StringDictionary.prototype.getAndRemove = function (key) {
            var val = this.get(key);
            if (val !== undefined) {
                delete this._data[key];
                --this._count;
                return val;
            }
            return null;
        };
        /**
         * Remove a key/value from the dictionary.
         * @param key the key to remove
         * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
         */
        StringDictionary.prototype.remove = function (key) {
            if (this.contains(key)) {
                delete this._data[key];
                --this._count;
                return true;
            }
            return false;
        };
        /**
         * Clear the whole content of the dictionary
         */
        StringDictionary.prototype.clear = function () {
            this._data = {};
            this._count = 0;
        };
        Object.defineProperty(StringDictionary.prototype, "count", {
            get: function () {
                return this._count;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Execute a callback on each key/val of the dictionary.
         * Note that you can remove any element in this dictionary in the callback implementation
         * @param callback the callback to execute on a given key/value pair
         */
        StringDictionary.prototype.forEach = function (callback) {
            for (var cur in this._data) {
                var val = this._data[cur];
                callback(cur, val);
            }
        };
        /**
         * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
         * If the callback returns null or undefined the method will iterate to the next key/value pair
         * Note that you can remove any element in this dictionary in the callback implementation
         * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
         */
        StringDictionary.prototype.first = function (callback) {
            for (var cur in this._data) {
                var val = this._data[cur];
                var res = callback(cur, val);
                if (res) {
                    return res;
                }
            }
            return null;
        };
        return StringDictionary;
    }());
    BABYLON.StringDictionary = StringDictionary;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.stringDictionary.js.map
 
var BABYLON;
(function (BABYLON) {
    // Screenshots
    var screenshotCanvas;
    var cloneValue = function (source, destinationObject) {
        if (!source)
            return null;
        if (source instanceof BABYLON.Mesh) {
            return null;
        }
        if (source instanceof BABYLON.SubMesh) {
            return source.clone(destinationObject);
        }
        else if (source.clone) {
            return source.clone();
        }
        return null;
    };
    var Tools = (function () {
        function Tools() {
        }
        Tools.Instantiate = function (className) {
            var arr = className.split(".");
            var fn = (window || this);
            for (var i = 0, len = arr.length; i < len; i++) {
                fn = fn[arr[i]];
            }
            if (typeof fn !== "function") {
                return null;
            }
            return fn;
        };
        Tools.SetImmediate = function (action) {
            if (window.setImmediate) {
                window.setImmediate(action);
            }
            else {
                setTimeout(action, 1);
            }
        };
        Tools.IsExponentOfTwo = function (value) {
            var count = 1;
            do {
                count *= 2;
            } while (count < value);
            return count === value;
        };
        Tools.GetExponentOfTwo = function (value, max) {
            var count = 1;
            do {
                count *= 2;
            } while (count < value);
            if (count > max)
                count = max;
            return count;
        };
        Tools.GetFilename = function (path) {
            var index = path.lastIndexOf("/");
            if (index < 0)
                return path;
            return path.substring(index + 1);
        };
        Tools.GetDOMTextContent = function (element) {
            var result = "";
            var child = element.firstChild;
            while (child) {
                if (child.nodeType === 3) {
                    result += child.textContent;
                }
                child = child.nextSibling;
            }
            return result;
        };
        Tools.ToDegrees = function (angle) {
            return angle * 180 / Math.PI;
        };
        Tools.ToRadians = function (angle) {
            return angle * Math.PI / 180;
        };
        Tools.EncodeArrayBufferTobase64 = function (buffer) {
            var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            var bytes = new Uint8Array(buffer);
            while (i < bytes.length) {
                chr1 = bytes[i++];
                chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index 
                chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                }
                else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                    keyStr.charAt(enc3) + keyStr.charAt(enc4);
            }
            return "data:image/png;base64," + output;
        };
        Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
            if (bias === void 0) { bias = null; }
            var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            for (var index = indexStart; index < indexStart + indexCount; index++) {
                var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
                minimum = BABYLON.Vector3.Minimize(current, minimum);
                maximum = BABYLON.Vector3.Maximize(current, maximum);
            }
            if (bias) {
                minimum.x -= minimum.x * bias.x + bias.y;
                minimum.y -= minimum.y * bias.x + bias.y;
                minimum.z -= minimum.z * bias.x + bias.y;
                maximum.x += maximum.x * bias.x + bias.y;
                maximum.y += maximum.y * bias.x + bias.y;
                maximum.z += maximum.z * bias.x + bias.y;
            }
            return {
                minimum: minimum,
                maximum: maximum
            };
        };
        Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
            if (bias === void 0) { bias = null; }
            var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            if (!stride) {
                stride = 3;
            }
            for (var index = start; index < start + count; index++) {
                var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
                minimum = BABYLON.Vector3.Minimize(current, minimum);
                maximum = BABYLON.Vector3.Maximize(current, maximum);
            }
            if (bias) {
                minimum.x -= minimum.x * bias.x + bias.y;
                minimum.y -= minimum.y * bias.x + bias.y;
                minimum.z -= minimum.z * bias.x + bias.y;
                maximum.x += maximum.x * bias.x + bias.y;
                maximum.y += maximum.y * bias.x + bias.y;
                maximum.z += maximum.z * bias.x + bias.y;
            }
            return {
                minimum: minimum,
                maximum: maximum
            };
        };
        Tools.Vector2ArrayFeeder = function (array) {
            return function (index) {
                var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
                var length = isFloatArray ? array.length / 2 : array.length;
                if (index >= length) {
                    return null;
                }
                if (isFloatArray) {
                    var fa = array;
                    return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
                }
                var a = array;
                return a[index];
            };
        };
        Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
            if (bias === void 0) { bias = null; }
            var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
            var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
            var i = 0;
            var cur = feeder(i++);
            while (cur) {
                minimum = BABYLON.Vector2.Minimize(cur, minimum);
                maximum = BABYLON.Vector2.Maximize(cur, maximum);
                cur = feeder(i++);
            }
            if (bias) {
                minimum.x -= minimum.x * bias.x + bias.y;
                minimum.y -= minimum.y * bias.x + bias.y;
                maximum.x += maximum.x * bias.x + bias.y;
                maximum.y += maximum.y * bias.x + bias.y;
            }
            return {
                minimum: minimum,
                maximum: maximum
            };
        };
        Tools.MakeArray = function (obj, allowsNullUndefined) {
            if (allowsNullUndefined !== true && (obj === undefined || obj == null))
                return undefined;
            return Array.isArray(obj) ? obj : [obj];
        };
        // Misc.
        Tools.GetPointerPrefix = function () {
            var eventPrefix = "pointer";
            // Check if pointer events are supported
            if (!window.PointerEvent && !navigator.pointerEnabled) {
                eventPrefix = "mouse";
            }
            return eventPrefix;
        };
        /**
         * @param func - the function to be called
         * @param requester - the object that will request the next frame. Falls back to window.
         */
        Tools.QueueNewFrame = function (func, requester) {
            if (requester === void 0) { requester = window; }
            //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
            /*if(requester.isPresenting) {
                return;
            } else*/ if (requester.requestAnimationFrame)
                requester.requestAnimationFrame(func);
            else if (requester.msRequestAnimationFrame)
                requester.msRequestAnimationFrame(func);
            else if (requester.webkitRequestAnimationFrame)
                requester.webkitRequestAnimationFrame(func);
            else if (requester.mozRequestAnimationFrame)
                requester.mozRequestAnimationFrame(func);
            else if (requester.oRequestAnimationFrame)
                requester.oRequestAnimationFrame(func);
            else {
                window.setTimeout(func, 16);
            }
        };
        Tools.RequestFullscreen = function (element) {
            var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
            if (!requestFunction)
                return;
            requestFunction.call(element);
        };
        Tools.ExitFullscreen = function () {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
            else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            }
            else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
            else if (document.msCancelFullScreen) {
                document.msCancelFullScreen();
            }
        };
        Tools.SetCorsBehavior = function (url, img) {
            if (Tools.CorsBehavior) {
                switch (typeof (Tools.CorsBehavior)) {
                    case "function":
                        var result = Tools.CorsBehavior(url);
                        if (result) {
                            return result;
                        }
                        break;
                    case "string":
                    default:
                        img.crossOrigin = Tools.CorsBehavior;
                        break;
                }
            }
        };
        // External files
        Tools.CleanUrl = function (url) {
            url = url.replace(/#/mg, "%23");
            return url;
        };
        Tools.LoadImage = function (url, onload, onerror, database) {
            if (url instanceof ArrayBuffer) {
                url = Tools.EncodeArrayBufferTobase64(url);
            }
            url = Tools.CleanUrl(url);
            var img = new Image();
            if (url.substr(0, 5) !== "data:") {
                Tools.SetCorsBehavior(url, img);
            }
            img.onload = function () {
                onload(img);
            };
            img.onerror = function (err) {
                Tools.Error("Error while trying to load texture: " + url);
                if (Tools.UseFallbackTexture) {
                    img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
                    onload(img);
                }
                else {
                    onerror();
                }
            };
            var noIndexedDB = function () {
                img.src = url;
            };
            var loadFromIndexedDB = function () {
                database.loadImageFromDB(url, img);
            };
            //ANY database to do!
            if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
                database.openAsync(loadFromIndexedDB, noIndexedDB);
            }
            else {
                if (url.indexOf("file:") === -1) {
                    noIndexedDB();
                }
                else {
                    try {
                        var textureName = url.substring(5).toLowerCase();
                        var blobURL;
                        try {
                            blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
                        }
                        catch (ex) {
                            // Chrome doesn't support oneTimeOnly parameter
                            blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
                        }
                        img.src = blobURL;
                    }
                    catch (e) {
                        img.src = null;
                    }
                }
            }
            return img;
        };
        //ANY
        Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
            url = Tools.CleanUrl(url);
            var noIndexedDB = function () {
                var request = new XMLHttpRequest();
                var loadUrl = Tools.BaseUrl + url;
                request.open('GET', loadUrl, true);
                if (useArrayBuffer) {
                    request.responseType = "arraybuffer";
                }
                request.onprogress = progressCallBack;
                request.onreadystatechange = function () {
                    if (request.readyState === 4) {
                        request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
                        if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
                            callback(!useArrayBuffer ? request.responseText : request.response);
                        }
                        else {
                            if (onError) {
                                onError();
                            }
                            else {
                                throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
                            }
                        }
                    }
                };
                request.send(null);
            };
            var loadFromIndexedDB = function () {
                database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
            };
            if (url.indexOf("file:") !== -1) {
                var fileName = url.substring(5).toLowerCase();
                Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
            }
            else {
                // Caching all files
                if (database && database.enableSceneOffline) {
                    database.openAsync(loadFromIndexedDB, noIndexedDB);
                }
                else {
                    noIndexedDB();
                }
            }
        };
        Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
            var reader = new FileReader();
            reader.onload = function (e) {
                //target doesn't have result from ts 1.3
                callback(e.target['result']);
            };
            reader.onprogress = progressCallback;
            reader.readAsDataURL(fileToLoad);
        };
        Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
            var reader = new FileReader();
            reader.onerror = function (e) {
                Tools.Log("Error while reading file: " + fileToLoad.name);
                callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
            };
            reader.onload = function (e) {
                //target doesn't have result from ts 1.3
                callback(e.target['result']);
            };
            reader.onprogress = progressCallBack;
            if (!useArrayBuffer) {
                // Asynchronous read
                reader.readAsText(fileToLoad);
            }
            else {
                reader.readAsArrayBuffer(fileToLoad);
            }
        };
        //returns a downloadable url to a file content.
        Tools.FileAsURL = function (content) {
            var fileBlob = new Blob([content]);
            var url = window.URL || window.webkitURL;
            var link = url.createObjectURL(fileBlob);
            return link;
        };
        // Misc.
        Tools.Format = function (value, decimals) {
            if (decimals === void 0) { decimals = 2; }
            return value.toFixed(decimals);
        };
        Tools.CheckExtends = function (v, min, max) {
            if (v.x < min.x)
                min.x = v.x;
            if (v.y < min.y)
                min.y = v.y;
            if (v.z < min.z)
                min.z = v.z;
            if (v.x > max.x)
                max.x = v.x;
            if (v.y > max.y)
                max.y = v.y;
            if (v.z > max.z)
                max.z = v.z;
        };
        Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
            for (var prop in source) {
                if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
                    continue;
                }
                if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
                    continue;
                }
                var sourceValue = source[prop];
                var typeOfSourceValue = typeof sourceValue;
                if (typeOfSourceValue === "function") {
                    continue;
                }
                if (typeOfSourceValue === "object") {
                    if (sourceValue instanceof Array) {
                        destination[prop] = [];
                        if (sourceValue.length > 0) {
                            if (typeof sourceValue[0] == "object") {
                                for (var index = 0; index < sourceValue.length; index++) {
                                    var clonedValue = cloneValue(sourceValue[index], destination);
                                    if (destination[prop].indexOf(clonedValue) === -1) {
                                        destination[prop].push(clonedValue);
                                    }
                                }
                            }
                            else {
                                destination[prop] = sourceValue.slice(0);
                            }
                        }
                    }
                    else {
                        destination[prop] = cloneValue(sourceValue, destination);
                    }
                }
                else {
                    destination[prop] = sourceValue;
                }
            }
        };
        Tools.IsEmpty = function (obj) {
            for (var i in obj) {
                return false;
            }
            return true;
        };
        Tools.RegisterTopRootEvents = function (events) {
            for (var index = 0; index < events.length; index++) {
                var event = events[index];
                window.addEventListener(event.name, event.handler, false);
                try {
                    if (window.parent) {
                        window.parent.addEventListener(event.name, event.handler, false);
                    }
                }
                catch (e) {
                }
            }
        };
        Tools.UnregisterTopRootEvents = function (events) {
            for (var index = 0; index < events.length; index++) {
                var event = events[index];
                window.removeEventListener(event.name, event.handler);
                try {
                    if (window.parent) {
                        window.parent.removeEventListener(event.name, event.handler);
                    }
                }
                catch (e) {
                }
            }
        };
        Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            // Read the contents of the framebuffer
            var numberOfChannelsByLine = width * 4;
            var halfHeight = height / 2;
            //Reading datas from WebGL
            var data = engine.readPixels(0, 0, width, height);
            //To flip image on Y axis.
            for (var i = 0; i < halfHeight; i++) {
                for (var j = 0; j < numberOfChannelsByLine; j++) {
                    var currentCell = j + i * numberOfChannelsByLine;
                    var targetLine = height - i - 1;
                    var targetCell = j + targetLine * numberOfChannelsByLine;
                    var temp = data[currentCell];
                    data[currentCell] = data[targetCell];
                    data[targetCell] = temp;
                }
            }
            // Create a 2D canvas to store the result
            if (!screenshotCanvas) {
                screenshotCanvas = document.createElement('canvas');
            }
            screenshotCanvas.width = width;
            screenshotCanvas.height = height;
            var context = screenshotCanvas.getContext('2d');
            // Copy the pixels to a 2D canvas
            var imageData = context.createImageData(width, height);
            var castData = (imageData.data);
            castData.set(data);
            context.putImageData(imageData, 0, 0);
            Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
        };
        Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            var base64Image = screenshotCanvas.toDataURL(mimeType);
            if (successCallback) {
                successCallback(base64Image);
            }
            else {
                //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
                if (("download" in document.createElement("a"))) {
                    var a = window.document.createElement("a");
                    a.href = base64Image;
                    var date = new Date();
                    var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
                    a.setAttribute("download", "screenshot_" + stringDate + ".png");
                    window.document.body.appendChild(a);
                    a.addEventListener("click", function () {
                        a.parentElement.removeChild(a);
                    });
                    a.click();
                }
                else {
                    var newWindow = window.open("");
                    var img = newWindow.document.createElement("img");
                    img.src = base64Image;
                    newWindow.document.body.appendChild(img);
                }
            }
        };
        Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            var width;
            var height;
            // If a precision value is specified
            if (size.precision) {
                width = Math.round(engine.getRenderWidth() * size.precision);
                height = Math.round(width / engine.getAspectRatio(camera));
            }
            else if (size.width && size.height) {
                width = size.width;
                height = size.height;
            }
            else if (size.width && !size.height) {
                width = size.width;
                height = Math.round(width / engine.getAspectRatio(camera));
            }
            else if (size.height && !size.width) {
                height = size.height;
                width = Math.round(height * engine.getAspectRatio(camera));
            }
            else if (!isNaN(size)) {
                height = size;
                width = size;
            }
            else {
                Tools.Error("Invalid 'size' parameter !");
                return;
            }
            if (!screenshotCanvas) {
                screenshotCanvas = document.createElement('canvas');
            }
            screenshotCanvas.width = width;
            screenshotCanvas.height = height;
            var renderContext = screenshotCanvas.getContext("2d");
            renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
            Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
        };
        Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            var width;
            var height;
            //If a precision value is specified
            if (size.precision) {
                width = Math.round(engine.getRenderWidth() * size.precision);
                height = Math.round(width / engine.getAspectRatio(camera));
                size = { width: width, height: height };
            }
            else if (size.width && size.height) {
                width = size.width;
                height = size.height;
            }
            else if (size.width && !size.height) {
                width = size.width;
                height = Math.round(width / engine.getAspectRatio(camera));
                size = { width: width, height: height };
            }
            else if (size.height && !size.width) {
                height = size.height;
                width = Math.round(height * engine.getAspectRatio(camera));
                size = { width: width, height: height };
            }
            else if (!isNaN(size)) {
                height = size;
                width = size;
            }
            else {
                Tools.Error("Invalid 'size' parameter !");
                return;
            }
            var scene = camera.getScene();
            var previousCamera = null;
            if (scene.activeCamera !== camera) {
                previousCamera = scene.activeCamera;
                scene.activeCamera = camera;
            }
            //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
            var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
            texture.renderList = scene.meshes;
            texture.onAfterRenderObservable.add(function () {
                Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
            });
            scene.incrementRenderId();
            scene.resetCachedMaterial();
            texture.render(true);
            texture.dispose();
            if (previousCamera) {
                scene.activeCamera = previousCamera;
            }
            camera.getProjectionMatrix(true); // Force cache refresh;
        };
        // XHR response validator for local file scenario
        Tools.ValidateXHRData = function (xhr, dataType) {
            // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
            if (dataType === void 0) { dataType = 7; }
            try {
                if (dataType & 1) {
                    if (xhr.responseText && xhr.responseText.length > 0) {
                        return true;
                    }
                    else if (dataType === 1) {
                        return false;
                    }
                }
                if (dataType & 2) {
                    // Check header width and height since there is no "TGA" magic number
                    var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
                    if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
                        return true;
                    }
                    else if (dataType === 2) {
                        return false;
                    }
                }
                if (dataType & 4) {
                    // Check for the "DDS" magic number
                    var ddsHeader = new Uint8Array(xhr.response, 0, 3);
                    if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
            catch (e) {
            }
            return false;
        };
        /**
         * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
         * Be aware Math.random() could cause collisions, but:
         * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
         */
        Tools.RandomId = function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        };
        Object.defineProperty(Tools, "NoneLogLevel", {
            get: function () {
                return Tools._NoneLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "MessageLogLevel", {
            get: function () {
                return Tools._MessageLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "WarningLogLevel", {
            get: function () {
                return Tools._WarningLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "ErrorLogLevel", {
            get: function () {
                return Tools._ErrorLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "AllLogLevel", {
            get: function () {
                return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Tools._AddLogEntry = function (entry) {
            Tools._LogCache = entry + Tools._LogCache;
            if (Tools.OnNewCacheEntry) {
                Tools.OnNewCacheEntry(entry);
            }
        };
        Tools._FormatMessage = function (message) {
            var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
            var date = new Date();
            return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
        };
        Tools._LogDisabled = function (message) {
            // nothing to do
        };
        Tools._LogEnabled = function (message) {
            var formattedMessage = Tools._FormatMessage(message);
            console.log("BJS - " + formattedMessage);
            var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
            Tools._AddLogEntry(entry);
        };
        Tools._WarnDisabled = function (message) {
            // nothing to do
        };
        Tools._WarnEnabled = function (message) {
            var formattedMessage = Tools._FormatMessage(message);
            console.warn("BJS - " + formattedMessage);
            var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
            Tools._AddLogEntry(entry);
        };
        Tools._ErrorDisabled = function (message) {
            // nothing to do
        };
        Tools._ErrorEnabled = function (message) {
            Tools.errorsCount++;
            var formattedMessage = Tools._FormatMessage(message);
            console.error("BJS - " + formattedMessage);
            var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
            Tools._AddLogEntry(entry);
        };
        Object.defineProperty(Tools, "LogCache", {
            get: function () {
                return Tools._LogCache;
            },
            enumerable: true,
            configurable: true
        });
        Tools.ClearLogCache = function () {
            Tools._LogCache = "";
            Tools.errorsCount = 0;
        };
        Object.defineProperty(Tools, "LogLevels", {
            set: function (level) {
                if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
                    Tools.Log = Tools._LogEnabled;
                }
                else {
                    Tools.Log = Tools._LogDisabled;
                }
                if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
                    Tools.Warn = Tools._WarnEnabled;
                }
                else {
                    Tools.Warn = Tools._WarnDisabled;
                }
                if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
                    Tools.Error = Tools._ErrorEnabled;
                }
                else {
                    Tools.Error = Tools._ErrorDisabled;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
            get: function () {
                return Tools._PerformanceNoneLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
            get: function () {
                return Tools._PerformanceUserMarkLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
            get: function () {
                return Tools._PerformanceConsoleLogLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Tools, "PerformanceLogLevel", {
            set: function (level) {
                if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
                    Tools.StartPerformanceCounter = Tools._StartUserMark;
                    Tools.EndPerformanceCounter = Tools._EndUserMark;
                    return;
                }
                if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
                    Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
                    Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
                    return;
                }
                Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
                Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
            },
            enumerable: true,
            configurable: true
        });
        Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
        };
        Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
        };
        Tools._StartUserMark = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition || !Tools._performance.mark) {
                return;
            }
            Tools._performance.mark(counterName + "-Begin");
        };
        Tools._EndUserMark = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition || !Tools._performance.mark) {
                return;
            }
            Tools._performance.mark(counterName + "-End");
            Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
        };
        Tools._StartPerformanceConsole = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition) {
                return;
            }
            Tools._StartUserMark(counterName, condition);
            if (console.time) {
                console.time(counterName);
            }
        };
        Tools._EndPerformanceConsole = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition) {
                return;
            }
            Tools._EndUserMark(counterName, condition);
            if (console.time) {
                console.timeEnd(counterName);
            }
        };
        Object.defineProperty(Tools, "Now", {
            get: function () {
                if (window.performance && window.performance.now) {
                    return window.performance.now();
                }
                return new Date().getTime();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * This method will return the name of the class used to create the instance of the given object.
         * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
         * @param object the object to get the class name from
         * @return the name of the class, will be "object" for a custom data type not using the @className decorator
         */
        Tools.getClassName = function (object, isType) {
            if (isType === void 0) { isType = false; }
            var name = null;
            if (!isType && object.getClassName) {
                name = object.getClassName();
            }
            else {
                if (object instanceof Object) {
                    var classObj = isType ? object : Object.getPrototypeOf(object);
                    name = classObj.constructor["__bjsclassName__"];
                }
                if (!name) {
                    name = typeof object;
                }
            }
            return name;
        };
        Tools.first = function (array, predicate) {
            for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
                var el = array_1[_i];
                if (predicate(el)) {
                    return el;
                }
            }
        };
        /**
         * This method will return the name of the full name of the class, including its owning module (if any).
         * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
         * @param object the object to get the class name from
         * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
         */
        Tools.getFullClassName = function (object, isType) {
            if (isType === void 0) { isType = false; }
            var className = null;
            var moduleName = null;
            if (!isType && object.getClassName) {
                className = object.getClassName();
            }
            else {
                if (object instanceof Object) {
                    var classObj = isType ? object : Object.getPrototypeOf(object);
                    className = classObj.constructor["__bjsclassName__"];
                    moduleName = classObj.constructor["__bjsmoduleName__"];
                }
                if (!className) {
                    className = typeof object;
                }
            }
            if (!className) {
                return null;
            }
            return ((moduleName != null) ? (moduleName + ".") : "") + className;
        };
        /**
         * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
         * @param array
         */
        Tools.arrayOrStringFeeder = function (array) {
            return function (index) {
                if (index >= array.length) {
                    return null;
                }
                var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
                if (val && val.getHashCode) {
                    val = val.getHashCode();
                }
                if (typeof val === "string") {
                    return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
                }
                return val;
            };
        };
        /**
         * Compute the hashCode of a stream of number
         * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
         * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
         * @return the hash code computed
         */
        Tools.hashCodeFromStream = function (feeder) {
            // Based from here: http://stackoverflow.com/a/7616484/802124
            var hash = 0;
            var index = 0;
            var chr = feeder(index++);
            while (chr != null) {
                hash = ((hash << 5) - hash) + chr;
                hash |= 0; // Convert to 32bit integer
                chr = feeder(index++);
            }
            return hash;
        };
        Tools.BaseUrl = "";
        Tools.CorsBehavior = "anonymous";
        Tools.UseFallbackTexture = true;
        // Logs
        Tools._NoneLogLevel = 0;
        Tools._MessageLogLevel = 1;
        Tools._WarningLogLevel = 2;
        Tools._ErrorLogLevel = 4;
        Tools._LogCache = "";
        Tools.errorsCount = 0;
        Tools.Log = Tools._LogEnabled;
        Tools.Warn = Tools._WarnEnabled;
        Tools.Error = Tools._ErrorEnabled;
        // Performances
        Tools._PerformanceNoneLogLevel = 0;
        Tools._PerformanceUserMarkLogLevel = 1;
        Tools._PerformanceConsoleLogLevel = 2;
        Tools._performance = window.performance;
        Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
        Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
        return Tools;
    }());
    BABYLON.Tools = Tools;
    /**
     * This class is used to track a performance counter which is number based.
     * The user has access to many properties which give statistics of different nature
     *
     * The implementer can track two kinds of Performance Counter: time and count
     * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
     * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
     */
    var PerfCounter = (function () {
        function PerfCounter() {
            this._startMonitoringTime = 0;
            this._min = 0;
            this._max = 0;
            this._average = 0;
            this._lastSecAverage = 0;
            this._current = 0;
            this._totalValueCount = 0;
            this._totalAccumulated = 0;
            this._lastSecAccumulated = 0;
            this._lastSecTime = 0;
            this._lastSecValueCount = 0;
        }
        Object.defineProperty(PerfCounter.prototype, "min", {
            /**
             * Returns the smallest value ever
             */
            get: function () {
                return this._min;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "max", {
            /**
             * Returns the biggest value ever
             */
            get: function () {
                return this._max;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "average", {
            /**
             * Returns the average value since the performance counter is running
             */
            get: function () {
                return this._average;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
            /**
             * Returns the average value of the last second the counter was monitored
             */
            get: function () {
                return this._lastSecAverage;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "current", {
            /**
             * Returns the current value
             */
            get: function () {
                return this._current;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "total", {
            get: function () {
                return this._totalAccumulated;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Call this method to start monitoring a new frame.
         * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
         */
        PerfCounter.prototype.fetchNewFrame = function () {
            this._totalValueCount++;
            this._current = 0;
            this._lastSecValueCount++;
        };
        /**
         * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
         * @param newCount the count value to add to the monitored count
         * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
         */
        PerfCounter.prototype.addCount = function (newCount, fetchResult) {
            this._current += newCount;
            if (fetchResult) {
                this._fetchResult();
            }
        };
        /**
         * Start monitoring this performance counter
         */
        PerfCounter.prototype.beginMonitoring = function () {
            this._startMonitoringTime = Tools.Now;
        };
        /**
         * Compute the time lapsed since the previous beginMonitoring() call.
         * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
         */
        PerfCounter.prototype.endMonitoring = function (newFrame) {
            if (newFrame === void 0) { newFrame = true; }
            if (newFrame) {
                this.fetchNewFrame();
            }
            var currentTime = Tools.Now;
            this._current = currentTime - this._startMonitoringTime;
            if (newFrame) {
                this._fetchResult();
            }
        };
        PerfCounter.prototype._fetchResult = function () {
            this._totalAccumulated += this._current;
            this._lastSecAccumulated += this._current;
            // Min/Max update
            this._min = Math.min(this._min, this._current);
            this._max = Math.max(this._max, this._current);
            this._average = this._totalAccumulated / this._totalValueCount;
            // Reset last sec?
            var now = Tools.Now;
            if ((now - this._lastSecTime) > 1000) {
                this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
                this._lastSecTime = now;
                this._lastSecAccumulated = 0;
                this._lastSecValueCount = 0;
            }
        };
        return PerfCounter;
    }());
    BABYLON.PerfCounter = PerfCounter;
    /**
     * Use this className as a decorator on a given class definition to add it a name and optionally its module.
     * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
     * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
     * @param name The name of the class, case should be preserved
     * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
     */
    function className(name, module) {
        return function (target) {
            target["__bjsclassName__"] = name;
            target["__bjsmoduleName__"] = (module != null) ? module : null;
        };
    }
    BABYLON.className = className;
    /**
    * An implementation of a loop for asynchronous functions.
    */
    var AsyncLoop = (function () {
        /**
         * Constroctor.
         * @param iterations the number of iterations.
         * @param _fn the function to run each iteration
         * @param _successCallback the callback that will be called upon succesful execution
         * @param offset starting offset.
         */
        function AsyncLoop(iterations, _fn, _successCallback, offset) {
            if (offset === void 0) { offset = 0; }
            this.iterations = iterations;
            this._fn = _fn;
            this._successCallback = _successCallback;
            this.index = offset - 1;
            this._done = false;
        }
        /**
         * Execute the next iteration. Must be called after the last iteration was finished.
         */
        AsyncLoop.prototype.executeNext = function () {
            if (!this._done) {
                if (this.index + 1 < this.iterations) {
                    ++this.index;
                    this._fn(this);
                }
                else {
                    this.breakLoop();
                }
            }
        };
        /**
         * Break the loop and run the success callback.
         */
        AsyncLoop.prototype.breakLoop = function () {
            this._done = true;
            this._successCallback();
        };
        /**
         * Helper function
         */
        AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
            if (offset === void 0) { offset = 0; }
            var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
            loop.executeNext();
            return loop;
        };
        /**
         * A for-loop that will run a given number of iterations synchronous and the rest async.
         * @param iterations total number of iterations
         * @param syncedIterations number of synchronous iterations in each async iteration.
         * @param fn the function to call each iteration.
         * @param callback a success call back that will be called when iterating stops.
         * @param breakFunction a break condition (optional)
         * @param timeout timeout settings for the setTimeout function. default - 0.
         * @constructor
         */
        AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
            if (timeout === void 0) { timeout = 0; }
            AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
                if (breakFunction && breakFunction())
                    loop.breakLoop();
                else {
                    setTimeout(function () {
                        for (var i = 0; i < syncedIterations; ++i) {
                            var iteration = (loop.index * syncedIterations) + i;
                            if (iteration >= iterations)
                                break;
                            fn(iteration);
                            if (breakFunction && breakFunction()) {
                                loop.breakLoop();
                                break;
                            }
                        }
                        loop.executeNext();
                    }, timeout);
                }
            }, callback);
        };
        return AsyncLoop;
    }());
    BABYLON.AsyncLoop = AsyncLoop;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var _AlphaState = (function () {
            /**
             * Initializes the state.
             */
            function _AlphaState() {
                this._isAlphaBlendDirty = false;
                this._isBlendFunctionParametersDirty = false;
                this._alphaBlend = false;
                this._blendFunctionParameters = new Array(4);
                this.reset();
            }
            Object.defineProperty(_AlphaState.prototype, "isDirty", {
                get: function () {
                    return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
                get: function () {
                    return this._alphaBlend;
                },
                set: function (value) {
                    if (this._alphaBlend === value) {
                        return;
                    }
                    this._alphaBlend = value;
                    this._isAlphaBlendDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
                if (this._blendFunctionParameters[0] === value0 &&
                    this._blendFunctionParameters[1] === value1 &&
                    this._blendFunctionParameters[2] === value2 &&
                    this._blendFunctionParameters[3] === value3) {
                    return;
                }
                this._blendFunctionParameters[0] = value0;
                this._blendFunctionParameters[1] = value1;
                this._blendFunctionParameters[2] = value2;
                this._blendFunctionParameters[3] = value3;
                this._isBlendFunctionParametersDirty = true;
            };
            _AlphaState.prototype.reset = function () {
                this._alphaBlend = false;
                this._blendFunctionParameters[0] = null;
                this._blendFunctionParameters[1] = null;
                this._blendFunctionParameters[2] = null;
                this._blendFunctionParameters[3] = null;
                this._isAlphaBlendDirty = true;
                this._isBlendFunctionParametersDirty = false;
            };
            _AlphaState.prototype.apply = function (gl) {
                if (!this.isDirty) {
                    return;
                }
                // Alpha blend
                if (this._isAlphaBlendDirty) {
                    if (this._alphaBlend) {
                        gl.enable(gl.BLEND);
                    }
                    else {
                        gl.disable(gl.BLEND);
                    }
                    this._isAlphaBlendDirty = false;
                }
                // Alpha function
                if (this._isBlendFunctionParametersDirty) {
                    gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
                    this._isBlendFunctionParametersDirty = false;
                }
            };
            return _AlphaState;
        }());
        Internals._AlphaState = _AlphaState;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.alphaCullingState.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var _DepthCullingState = (function () {
            /**
             * Initializes the state.
             */
            function _DepthCullingState() {
                this._isDepthTestDirty = false;
                this._isDepthMaskDirty = false;
                this._isDepthFuncDirty = false;
                this._isCullFaceDirty = false;
                this._isCullDirty = false;
                this._isZOffsetDirty = false;
                this.reset();
            }
            Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
                get: function () {
                    return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
                get: function () {
                    return this._zOffset;
                },
                set: function (value) {
                    if (this._zOffset === value) {
                        return;
                    }
                    this._zOffset = value;
                    this._isZOffsetDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
                get: function () {
                    return this._cullFace;
                },
                set: function (value) {
                    if (this._cullFace === value) {
                        return;
                    }
                    this._cullFace = value;
                    this._isCullFaceDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_DepthCullingState.prototype, "cull", {
                get: function () {
                    return this._cull;
                },
                set: function (value) {
                    if (this._cull === value) {
                        return;
                    }
                    this._cull = value;
                    this._isCullDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
                get: function () {
                    return this._depthFunc;
                },
                set: function (value) {
                    if (this._depthFunc === value) {
                        return;
                    }
                    this._depthFunc = value;
                    this._isDepthFuncDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
                get: function () {
                    return this._depthMask;
                },
                set: function (value) {
                    if (this._depthMask === value) {
                        return;
                    }
                    this._depthMask = value;
                    this._isDepthMaskDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
                get: function () {
                    return this._depthTest;
                },
                set: function (value) {
                    if (this._depthTest === value) {
                        return;
                    }
                    this._depthTest = value;
                    this._isDepthTestDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            _DepthCullingState.prototype.reset = function () {
                this._depthMask = true;
                this._depthTest = true;
                this._depthFunc = null;
                this._cullFace = null;
                this._cull = null;
                this._zOffset = 0;
                this._isDepthTestDirty = true;
                this._isDepthMaskDirty = true;
                this._isDepthFuncDirty = false;
                this._isCullFaceDirty = false;
                this._isCullDirty = false;
                this._isZOffsetDirty = false;
            };
            _DepthCullingState.prototype.apply = function (gl) {
                if (!this.isDirty) {
                    return;
                }
                // Cull
                if (this._isCullDirty) {
                    if (this.cull) {
                        gl.enable(gl.CULL_FACE);
                    }
                    else {
                        gl.disable(gl.CULL_FACE);
                    }
                    this._isCullDirty = false;
                }
                // Cull face
                if (this._isCullFaceDirty) {
                    gl.cullFace(this.cullFace);
                    this._isCullFaceDirty = false;
                }
                // Depth mask
                if (this._isDepthMaskDirty) {
                    gl.depthMask(this.depthMask);
                    this._isDepthMaskDirty = false;
                }
                // Depth test
                if (this._isDepthTestDirty) {
                    if (this.depthTest) {
                        gl.enable(gl.DEPTH_TEST);
                    }
                    else {
                        gl.disable(gl.DEPTH_TEST);
                    }
                    this._isDepthTestDirty = false;
                }
                // Depth func
                if (this._isDepthFuncDirty) {
                    gl.depthFunc(this.depthFunc);
                    this._isDepthFuncDirty = false;
                }
                // zOffset
                if (this._isZOffsetDirty) {
                    if (this.zOffset) {
                        gl.enable(gl.POLYGON_OFFSET_FILL);
                        gl.polygonOffset(this.zOffset, 0);
                    }
                    else {
                        gl.disable(gl.POLYGON_OFFSET_FILL);
                    }
                    this._isZOffsetDirty = false;
                }
            };
            return _DepthCullingState;
        }());
        Internals._DepthCullingState = _DepthCullingState;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.depthCullingState.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var _StencilState = (function () {
            function _StencilState() {
                this._isStencilTestDirty = false;
                this._isStencilMaskDirty = false;
                this._isStencilFuncDirty = false;
                this._isStencilOpDirty = false;
                this.reset();
            }
            Object.defineProperty(_StencilState.prototype, "isDirty", {
                get: function () {
                    return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilFunc", {
                get: function () {
                    return this._stencilFunc;
                },
                set: function (value) {
                    if (this._stencilFunc === value) {
                        return;
                    }
                    this._stencilFunc = value;
                    this._isStencilFuncDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
                get: function () {
                    return this._stencilFuncRef;
                },
                set: function (value) {
                    if (this._stencilFuncRef === value) {
                        return;
                    }
                    this._stencilFuncRef = value;
                    this._isStencilFuncDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
                get: function () {
                    return this._stencilFuncMask;
                },
                set: function (value) {
                    if (this._stencilFuncMask === value) {
                        return;
                    }
                    this._stencilFuncMask = value;
                    this._isStencilFuncDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
                get: function () {
                    return this._stencilOpStencilFail;
                },
                set: function (value) {
                    if (this._stencilOpStencilFail === value) {
                        return;
                    }
                    this._stencilOpStencilFail = value;
                    this._isStencilOpDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
                get: function () {
                    return this._stencilOpDepthFail;
                },
                set: function (value) {
                    if (this._stencilOpDepthFail === value) {
                        return;
                    }
                    this._stencilOpDepthFail = value;
                    this._isStencilOpDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
                get: function () {
                    return this._stencilOpStencilDepthPass;
                },
                set: function (value) {
                    if (this._stencilOpStencilDepthPass === value) {
                        return;
                    }
                    this._stencilOpStencilDepthPass = value;
                    this._isStencilOpDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilMask", {
                get: function () {
                    return this._stencilMask;
                },
                set: function (value) {
                    if (this._stencilMask === value) {
                        return;
                    }
                    this._stencilMask = value;
                    this._isStencilMaskDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(_StencilState.prototype, "stencilTest", {
                get: function () {
                    return this._stencilTest;
                },
                set: function (value) {
                    if (this._stencilTest === value) {
                        return;
                    }
                    this._stencilTest = value;
                    this._isStencilTestDirty = true;
                },
                enumerable: true,
                configurable: true
            });
            _StencilState.prototype.reset = function () {
                this._stencilTest = false;
                this._stencilMask = 0xFF;
                this._stencilFunc = BABYLON.Engine.ALWAYS;
                this._stencilFuncRef = 1;
                this._stencilFuncMask = 0xFF;
                this._stencilOpStencilFail = BABYLON.Engine.KEEP;
                this._stencilOpDepthFail = BABYLON.Engine.KEEP;
                this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
                this._isStencilTestDirty = true;
                this._isStencilMaskDirty = true;
                this._isStencilFuncDirty = true;
                this._isStencilOpDirty = true;
            };
            _StencilState.prototype.apply = function (gl) {
                if (!this.isDirty) {
                    return;
                }
                // Stencil test
                if (this._isStencilTestDirty) {
                    if (this.stencilTest) {
                        gl.enable(gl.STENCIL_TEST);
                    }
                    else {
                        gl.disable(gl.STENCIL_TEST);
                    }
                    this._isStencilTestDirty = false;
                }
                // Stencil mask
                if (this._isStencilMaskDirty) {
                    gl.stencilMask(this.stencilMask);
                    this._isStencilMaskDirty = false;
                }
                // Stencil func
                if (this._isStencilFuncDirty) {
                    gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
                    this._isStencilFuncDirty = false;
                }
                // Stencil op
                if (this._isStencilOpDirty) {
                    gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
                    this._isStencilOpDirty = false;
                }
            };
            return _StencilState;
        }());
        Internals._StencilState = _StencilState;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.stencilState.js.map
 
var BABYLON;
(function (BABYLON) {
    var compileShader = function (gl, source, type, defines) {
        var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
        gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            throw new Error(gl.getShaderInfoLog(shader));
        }
        return shader;
    };
    var HALF_FLOAT_OES = 0x8D61;
    var getWebGLTextureType = function (gl, type) {
        if (type === Engine.TEXTURETYPE_FLOAT) {
            return gl.FLOAT;
        }
        else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
            // Add Half Float Constant.
            return HALF_FLOAT_OES;
        }
        return gl.UNSIGNED_BYTE;
    };
    var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
        var magFilter = gl.NEAREST;
        var minFilter = gl.NEAREST;
        if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
            magFilter = gl.LINEAR;
            if (generateMipMaps) {
                minFilter = gl.LINEAR_MIPMAP_NEAREST;
            }
            else {
                minFilter = gl.LINEAR;
            }
        }
        else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
            magFilter = gl.LINEAR;
            if (generateMipMaps) {
                minFilter = gl.LINEAR_MIPMAP_LINEAR;
            }
            else {
                minFilter = gl.LINEAR;
            }
        }
        else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
            magFilter = gl.NEAREST;
            if (generateMipMaps) {
                minFilter = gl.NEAREST_MIPMAP_LINEAR;
            }
            else {
                minFilter = gl.NEAREST;
            }
        }
        return {
            min: minFilter,
            mag: magFilter
        };
    };
    var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
        if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
        var engine = scene.getEngine();
        var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
        var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
        engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
        texture._baseWidth = width;
        texture._baseHeight = height;
        texture._width = potWidth;
        texture._height = potHeight;
        texture.isReady = true;
        processFunction(potWidth, potHeight);
        var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
        if (!noMipmap && !isCompressed) {
            gl.generateMipmap(gl.TEXTURE_2D);
        }
        engine._bindTextureDirectly(gl.TEXTURE_2D, null);
        engine.resetTextureCache();
        scene._removePendingData(texture);
        texture.onLoadedCallbacks.forEach(function (callback) {
            callback();
        });
        texture.onLoadedCallbacks = [];
    };
    var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
        if (onErrorCallBack === void 0) { onErrorCallBack = null; }
        var img;
        var onload = function () {
            loadedImages[index] = img;
            loadedImages._internalCount++;
            scene._removePendingData(img);
            if (loadedImages._internalCount === 6) {
                onfinish(loadedImages);
            }
        };
        var onerror = function () {
            scene._removePendingData(img);
            if (onErrorCallBack) {
                onErrorCallBack();
            }
        };
        img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
        scene._addPendingData(img);
    };
    var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
        if (onError === void 0) { onError = null; }
        var loadedImages = [];
        loadedImages._internalCount = 0;
        for (var index = 0; index < 6; index++) {
            partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
        }
    };
    var InstancingAttributeInfo = (function () {
        function InstancingAttributeInfo() {
        }
        return InstancingAttributeInfo;
    }());
    BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
    var EngineCapabilities = (function () {
        function EngineCapabilities() {
        }
        return EngineCapabilities;
    }());
    BABYLON.EngineCapabilities = EngineCapabilities;
    /**
     * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
     */
    var Engine = (function () {
        /**
         * @constructor
         * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
         * @param {boolean} [antialias] - enable antialias
         * @param options - further options to be sent to the getContext function
         */
        function Engine(canvas, antialias, options, adaptToDeviceRatio) {
            var _this = this;
            if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
            // Public members
            this.isFullscreen = false;
            this.isPointerLock = false;
            this.cullBackFaces = true;
            this.renderEvenInBackground = true;
            // To enable/disable IDB support and avoid XHR on .manifest
            this.enableOfflineSupport = true;
            this.scenes = new Array();
            this._windowIsBackground = false;
            this._webGLVersion = "1.0";
            this._badOS = false;
            this._drawCalls = new BABYLON.PerfCounter();
            this._renderingQueueLaunched = false;
            this._activeRenderLoops = [];
            // FPS
            this.fpsRange = 60;
            this.previousFramesDuration = [];
            this.fps = 60;
            this.deltaTime = 0;
            // States
            this._depthCullingState = new BABYLON.Internals._DepthCullingState();
            this._stencilState = new BABYLON.Internals._StencilState();
            this._alphaState = new BABYLON.Internals._AlphaState();
            this._alphaMode = Engine.ALPHA_DISABLE;
            // Cache
            this._loadedTexturesCache = new Array();
            this._maxTextureChannels = 16;
            this._activeTexturesCache = new Array(this._maxTextureChannels);
            this._compiledEffects = {};
            this._vertexAttribArraysEnabled = [];
            this._uintIndicesCurrentlySet = false;
            this._currentBoundBuffer = new Array();
            this._currentBufferPointers = [];
            this._currentInstanceLocations = new Array();
            this._currentInstanceBuffers = new Array();
            // Hardware supported Compressed Textures
            this._texturesSupported = new Array();
            this._onVRFullScreenTriggered = function () {
                if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
                    //get the old size before we change
                    _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
                    _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
                    //according to the WebVR specs, requestAnimationFrame should be triggered only once.
                    //But actually, no browser follow the specs...
                    //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
                    //get the width and height, change the render size
                    var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
                    var width, height;
                    _this.setHardwareScalingLevel(1);
                    _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
                }
                else {
                    //When the specs are implemented, need to uncomment this.
                    //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
                    _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
                    _this.setSize(_this._oldSize.width, _this._oldSize.height);
                    _this._vrDisplayEnabled = undefined;
                }
            };
            this._renderingCanvas = canvas;
            this._externalData = new BABYLON.StringDictionary();
            options = options || {};
            if (antialias != null) {
                options.antialias = antialias;
            }
            if (options.preserveDrawingBuffer === undefined) {
                options.preserveDrawingBuffer = false;
            }
            // Checks if some of the format renders first to allow the use of webgl inspector.
            var renderToFullFloat = this._canRenderToFloatTexture();
            var renderToHalfFloat = this._canRenderToHalfFloatTexture();
            // GL
            //try {
            //    this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
            //    if (this._gl) {
            //        this._webGLVersion = "2.0";
            //    }
            //} catch (e) {
            //    // Do nothing
            //}
            if (!this._gl) {
                if (!canvas) {
                    throw new Error("The provided canvas is null or undefined.");
                }
                try {
                    this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
                }
                catch (e) {
                    throw new Error("WebGL not supported");
                }
            }
            if (!this._gl) {
                throw new Error("WebGL not supported");
            }
            this._onBlur = function () {
                _this._windowIsBackground = true;
            };
            this._onFocus = function () {
                _this._windowIsBackground = false;
            };
            window.addEventListener("blur", this._onBlur);
            window.addEventListener("focus", this._onFocus);
            // Viewport
            var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
            this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
            this.resize();
            // Caps
            this._isStencilEnable = options.stencil;
            this._caps = new EngineCapabilities();
            this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
            this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
            this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
            this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
            this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
            // Infos
            this._glVersion = this._gl.getParameter(this._gl.VERSION);
            var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
            if (rendererInfo != null) {
                this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
                this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
            }
            if (!this._glVendor) {
                this._glVendor = "Unknown vendor";
            }
            if (!this._glRenderer) {
                this._glRenderer = "Unknown renderer";
            }
            // Extensions
            this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
            this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc');
            this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
            this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); // 2nd is what iOS reports
            this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1');
            this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // first is the final name, found hardware using 2nd
            this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
            this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
            this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
            this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
            this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
            this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
            this._caps.highPrecisionShaderSupported = true;
            this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
            this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
            this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
            this._caps.textureFloatRender = renderToFullFloat;
            this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
            this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
            this._caps.textureHalfFloatRender = renderToHalfFloat;
            // Intelligently add supported commpressed formats in order to check for.
            // Check for ASTC support first as it is most powerful and to be very cross platform.
            // Next PVR & S3, which are probably superior to ETC1/2.  
            // Likely no hardware which supports both PVR & S3, so order matters little.
            // ETC2 is newer and handles ETC1, so check for first.
            if (this._caps.astc)
                this.texturesSupported.push('.astc');
            if (this._caps.s3tc)
                this.texturesSupported.push('.dds');
            if (this._caps.pvrtc)
                this.texturesSupported.push('.pvr');
            if (this._caps.etc2)
                this.texturesSupported.push('.etc2');
            if (this._caps.etc1)
                this.texturesSupported.push('.etc1');
            if (this._gl.getShaderPrecisionFormat) {
                var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
                this._caps.highPrecisionShaderSupported = highp.precision !== 0;
            }
            // Depth buffer
            this.setDepthBuffer(true);
            this.setDepthFunctionToLessOrEqual();
            this.setDepthWrite(true);
            // Fullscreen
            this._onFullscreenChange = function () {
                if (document.fullscreen !== undefined) {
                    _this.isFullscreen = document.fullscreen;
                }
                else if (document.mozFullScreen !== undefined) {
                    _this.isFullscreen = document.mozFullScreen;
                }
                else if (document.webkitIsFullScreen !== undefined) {
                    _this.isFullscreen = document.webkitIsFullScreen;
                }
                else if (document.msIsFullScreen !== undefined) {
                    _this.isFullscreen = document.msIsFullScreen;
                }
                // Pointer lock
                if (_this.isFullscreen && _this._pointerLockRequested) {
                    canvas.requestPointerLock = canvas.requestPointerLock ||
                        canvas.msRequestPointerLock ||
                        canvas.mozRequestPointerLock ||
                        canvas.webkitRequestPointerLock;
                    if (canvas.requestPointerLock) {
                        canvas.requestPointerLock();
                    }
                }
            };
            document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
            document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
            document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
            document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
            // Pointer lock
            this._onPointerLockChange = function () {
                _this.isPointerLock = (document.mozPointerLockElement === canvas ||
                    document.webkitPointerLockElement === canvas ||
                    document.msPointerLockElement === canvas ||
                    document.pointerLockElement === canvas);
            };
            document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
            document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
            document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
            document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
            if (BABYLON.AudioEngine && !Engine.audioEngine) {
                Engine.audioEngine = new BABYLON.AudioEngine();
            }
            //default loading screen
            this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
            //Load WebVR Devices
            if (options.autoEnableWebVR) {
                this.initWebVR();
            }
            //Detect if we are running on a faulty buggy OS.
            var regexp = /AppleWebKit.*10.[\d] Mobile/;
            //ua sniffing is the tool of the devil.
            this._badOS = regexp.test(navigator.userAgent);
            BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
        }
        Object.defineProperty(Engine, "NEVER", {
            get: function () {
                return Engine._NEVER;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALWAYS", {
            get: function () {
                return Engine._ALWAYS;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "LESS", {
            get: function () {
                return Engine._LESS;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "EQUAL", {
            get: function () {
                return Engine._EQUAL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "LEQUAL", {
            get: function () {
                return Engine._LEQUAL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "GREATER", {
            get: function () {
                return Engine._GREATER;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "GEQUAL", {
            get: function () {
                return Engine._GEQUAL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "NOTEQUAL", {
            get: function () {
                return Engine._NOTEQUAL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "KEEP", {
            get: function () {
                return Engine._KEEP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "REPLACE", {
            get: function () {
                return Engine._REPLACE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "INCR", {
            get: function () {
                return Engine._INCR;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "DECR", {
            get: function () {
                return Engine._DECR;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "INVERT", {
            get: function () {
                return Engine._INVERT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "INCR_WRAP", {
            get: function () {
                return Engine._INCR_WRAP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "DECR_WRAP", {
            get: function () {
                return Engine._DECR_WRAP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_DISABLE", {
            get: function () {
                return Engine._ALPHA_DISABLE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_ONEONE", {
            get: function () {
                return Engine._ALPHA_ONEONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_ADD", {
            get: function () {
                return Engine._ALPHA_ADD;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_COMBINE", {
            get: function () {
                return Engine._ALPHA_COMBINE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
            get: function () {
                return Engine._ALPHA_SUBTRACT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
            get: function () {
                return Engine._ALPHA_MULTIPLY;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
            get: function () {
                return Engine._ALPHA_MAXIMIZED;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
            get: function () {
                return Engine._DELAYLOADSTATE_NONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
            get: function () {
                return Engine._DELAYLOADSTATE_LOADED;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
            get: function () {
                return Engine._DELAYLOADSTATE_LOADING;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
            get: function () {
                return Engine._DELAYLOADSTATE_NOTLOADED;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
            get: function () {
                return Engine._TEXTUREFORMAT_ALPHA;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
            get: function () {
                return Engine._TEXTUREFORMAT_LUMINANCE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
            get: function () {
                return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
            get: function () {
                return Engine._TEXTUREFORMAT_RGB;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
            get: function () {
                return Engine._TEXTUREFORMAT_RGBA;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
            get: function () {
                return Engine._TEXTURETYPE_UNSIGNED_INT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
            get: function () {
                return Engine._TEXTURETYPE_FLOAT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
            get: function () {
                return Engine._TEXTURETYPE_HALF_FLOAT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "Version", {
            get: function () {
                return "2.5";
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "texturesSupported", {
            get: function () {
                return this._texturesSupported;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "textureFormatInUse", {
            get: function () {
                return this._textureFormatInUse;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "webGLVersion", {
            get: function () {
                return this._webGLVersion;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "isStencilEnable", {
            /**
             * Returns true if the stencil buffer has been enabled through the creation option of the context.
             */
            get: function () {
                return this._isStencilEnable;
            },
            enumerable: true,
            configurable: true
        });
        Engine.prototype._prepareWorkingCanvas = function () {
            if (this._workingCanvas) {
                return;
            }
            this._workingCanvas = document.createElement("canvas");
            this._workingContext = this._workingCanvas.getContext("2d");
        };
        Engine.prototype.resetTextureCache = function () {
            for (var index = 0; index < this._maxTextureChannels; index++) {
                this._activeTexturesCache[index] = null;
            }
        };
        Engine.prototype.getGlInfo = function () {
            return {
                vendor: this._glVendor,
                renderer: this._glRenderer,
                version: this._glVersion
            };
        };
        Engine.prototype.getAspectRatio = function (camera, useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            var viewport = camera.viewport;
            return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
        };
        Engine.prototype.getRenderWidth = function (useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            if (!useScreen && this._currentRenderTarget) {
                return this._currentRenderTarget._width;
            }
            return this._renderingCanvas.width;
        };
        Engine.prototype.getRenderHeight = function (useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            if (!useScreen && this._currentRenderTarget) {
                return this._currentRenderTarget._height;
            }
            return this._renderingCanvas.height;
        };
        Engine.prototype.getRenderingCanvas = function () {
            return this._renderingCanvas;
        };
        Engine.prototype.getRenderingCanvasClientRect = function () {
            return this._renderingCanvas.getBoundingClientRect();
        };
        Engine.prototype.setHardwareScalingLevel = function (level) {
            this._hardwareScalingLevel = level;
            this.resize();
        };
        Engine.prototype.getHardwareScalingLevel = function () {
            return this._hardwareScalingLevel;
        };
        Engine.prototype.getLoadedTexturesCache = function () {
            return this._loadedTexturesCache;
        };
        Engine.prototype.getCaps = function () {
            return this._caps;
        };
        Object.defineProperty(Engine.prototype, "drawCalls", {
            get: function () {
                return this._drawCalls.current;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
            get: function () {
                return this._drawCalls;
            },
            enumerable: true,
            configurable: true
        });
        Engine.prototype.getDepthFunction = function () {
            return this._depthCullingState.depthFunc;
        };
        Engine.prototype.setDepthFunction = function (depthFunc) {
            this._depthCullingState.depthFunc = depthFunc;
        };
        Engine.prototype.setDepthFunctionToGreater = function () {
            this._depthCullingState.depthFunc = this._gl.GREATER;
        };
        Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
            this._depthCullingState.depthFunc = this._gl.GEQUAL;
        };
        Engine.prototype.setDepthFunctionToLess = function () {
            this._depthCullingState.depthFunc = this._gl.LESS;
        };
        Engine.prototype.setDepthFunctionToLessOrEqual = function () {
            this._depthCullingState.depthFunc = this._gl.LEQUAL;
        };
        Engine.prototype.getStencilBuffer = function () {
            return this._stencilState.stencilTest;
        };
        Engine.prototype.setStencilBuffer = function (enable) {
            this._stencilState.stencilTest = enable;
        };
        Engine.prototype.getStencilMask = function () {
            return this._stencilState.stencilMask;
        };
        Engine.prototype.setStencilMask = function (mask) {
            this._stencilState.stencilMask = mask;
        };
        Engine.prototype.getStencilFunction = function () {
            return this._stencilState.stencilFunc;
        };
        Engine.prototype.getStencilFunctionReference = function () {
            return this._stencilState.stencilFuncRef;
        };
        Engine.prototype.getStencilFunctionMask = function () {
            return this._stencilState.stencilFuncMask;
        };
        Engine.prototype.setStencilFunction = function (stencilFunc) {
            this._stencilState.stencilFunc = stencilFunc;
        };
        Engine.prototype.setStencilFunctionReference = function (reference) {
            this._stencilState.stencilFuncRef = reference;
        };
        Engine.prototype.setStencilFunctionMask = function (mask) {
            this._stencilState.stencilFuncMask = mask;
        };
        Engine.prototype.getStencilOperationFail = function () {
            return this._stencilState.stencilOpStencilFail;
        };
        Engine.prototype.getStencilOperationDepthFail = function () {
            return this._stencilState.stencilOpDepthFail;
        };
        Engine.prototype.getStencilOperationPass = function () {
            return this._stencilState.stencilOpStencilDepthPass;
        };
        Engine.prototype.setStencilOperationFail = function (operation) {
            this._stencilState.stencilOpStencilFail = operation;
        };
        Engine.prototype.setStencilOperationDepthFail = function (operation) {
            this._stencilState.stencilOpDepthFail = operation;
        };
        Engine.prototype.setStencilOperationPass = function (operation) {
            this._stencilState.stencilOpStencilDepthPass = operation;
        };
        /**
         * stop executing a render loop function and remove it from the execution array
         * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
         */
        Engine.prototype.stopRenderLoop = function (renderFunction) {
            if (!renderFunction) {
                this._activeRenderLoops = [];
                return;
            }
            var index = this._activeRenderLoops.indexOf(renderFunction);
            if (index >= 0) {
                this._activeRenderLoops.splice(index, 1);
            }
        };
        Engine.prototype._renderLoop = function () {
            var shouldRender = true;
            if (!this.renderEvenInBackground && this._windowIsBackground) {
                shouldRender = false;
            }
            if (shouldRender) {
                // Start new frame
                this.beginFrame();
                for (var index = 0; index < this._activeRenderLoops.length; index++) {
                    var renderFunction = this._activeRenderLoops[index];
                    renderFunction();
                }
                // Present
                this.endFrame();
            }
            if (this._activeRenderLoops.length > 0) {
                // Register new frame
                BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
            }
            else {
                this._renderingQueueLaunched = false;
            }
        };
        /**
         * Register and execute a render loop. The engine can have more than one render function.
         * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
         * @example
         * engine.runRenderLoop(function () {
         *      scene.render()
         * })
         */
        Engine.prototype.runRenderLoop = function (renderFunction) {
            if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
                return;
            }
            this._activeRenderLoops.push(renderFunction);
            if (!this._renderingQueueLaunched) {
                this._renderingQueueLaunched = true;
                this._bindedRenderFunction = this._renderLoop.bind(this);
                BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
            }
        };
        /**
         * Toggle full screen mode.
         * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
         * @param {any} options - an options object to be sent to the requestFullscreen function
         */
        Engine.prototype.switchFullscreen = function (requestPointerLock) {
            if (this.isFullscreen) {
                BABYLON.Tools.ExitFullscreen();
            }
            else {
                this._pointerLockRequested = requestPointerLock;
                BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
            }
        };
        Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
            if (stencil === void 0) { stencil = false; }
            this.applyStates();
            var mode = 0;
            if (backBuffer) {
                this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
                mode |= this._gl.COLOR_BUFFER_BIT;
            }
            if (depth) {
                this._gl.clearDepth(1.0);
                mode |= this._gl.DEPTH_BUFFER_BIT;
            }
            if (stencil) {
                this._gl.clearStencil(0);
                mode |= this._gl.STENCIL_BUFFER_BIT;
            }
            this._gl.clear(mode);
        };
        Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
            var gl = this._gl;
            // Save state
            var curScissor = gl.getParameter(gl.SCISSOR_TEST);
            var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
            // Change state
            gl.enable(gl.SCISSOR_TEST);
            gl.scissor(x, y, width, height);
            // Clear
            this.clear(clearColor, true, true, true);
            // Restore state
            gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
            if (curScissor === true) {
                gl.enable(gl.SCISSOR_TEST);
            }
            else {
                gl.disable(gl.SCISSOR_TEST);
            }
        };
        /**
         * Set the WebGL's viewport
         * @param {BABYLON.Viewport} viewport - the viewport element to be used.
         * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
         * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
         */
        Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
            var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
            var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
            var x = viewport.x || 0;
            var y = viewport.y || 0;
            this._cachedViewport = viewport;
            this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
        };
        /**
         * Directly set the WebGL Viewport
         * The x, y, width & height are directly passed to the WebGL call
         * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
         */
        Engine.prototype.setDirectViewport = function (x, y, width, height) {
            var currentViewport = this._cachedViewport;
            this._cachedViewport = null;
            this._gl.viewport(x, y, width, height);
            return currentViewport;
        };
        Engine.prototype.beginFrame = function () {
            this._measureFps();
        };
        Engine.prototype.endFrame = function () {
            //force a flush in case we are using a bad OS.
            if (this._badOS) {
                this.flushFramebuffer();
            }
            //submit frame to the vr device, if enabled
            if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
                this._vrDisplayEnabled.submitFrame();
            }
        };
        /**
         * resize the view according to the canvas' size.
         * @example
         *   window.addEventListener("resize", function () {
         *      engine.resize();
         *   });
         */
        Engine.prototype.resize = function () {
            var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
            var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
            this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
            for (var index = 0; index < this.scenes.length; index++) {
                var scene = this.scenes[index];
                if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
                    scene.debugLayer._syncPositions();
                }
            }
        };
        /**
         * force a specific size of the canvas
         * @param {number} width - the new canvas' width
         * @param {number} height - the new canvas' height
         */
        Engine.prototype.setSize = function (width, height) {
            this._renderingCanvas.width = width;
            this._renderingCanvas.height = height;
            for (var index = 0; index < this.scenes.length; index++) {
                var scene = this.scenes[index];
                for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
                    var cam = scene.cameras[camIndex];
                    cam._currentRenderId = 0;
                }
            }
        };
        //WebVR functions
        Engine.prototype.initWebVR = function () {
            if (!this.vrDisplaysPromise) {
                this._getVRDisplays();
            }
        };
        Engine.prototype.enableVR = function (vrDevice) {
            this._vrDisplayEnabled = vrDevice;
            this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
        };
        Engine.prototype.disableVR = function () {
            if (this._vrDisplayEnabled) {
                this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
            }
        };
        Engine.prototype._getVRDisplays = function () {
            var _this = this;
            var getWebVRDevices = function (devices) {
                var size = devices.length;
                var i = 0;
                _this._vrDisplays = devices.filter(function (device) {
                    return devices[i] instanceof VRDisplay;
                });
                return _this._vrDisplays;
            };
            //using a key due to typescript
            if (navigator.getVRDisplays) {
                this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
            }
        };
        Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
            this._currentRenderTarget = texture;
            this.bindUnboundFramebuffer(texture._framebuffer);
            var gl = this._gl;
            if (texture.isCube) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
            }
            gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
            this.wipeCaches();
        };
        Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
            if (this._currentFramebuffer !== framebuffer) {
                this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
                this._currentFramebuffer = framebuffer;
            }
        };
        Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
            if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
            this._currentRenderTarget = null;
            if (texture.generateMipMaps && !disableGenerateMipMaps) {
                var gl = this._gl;
                this._bindTextureDirectly(gl.TEXTURE_2D, texture);
                gl.generateMipmap(gl.TEXTURE_2D);
                this._bindTextureDirectly(gl.TEXTURE_2D, null);
            }
            this.bindUnboundFramebuffer(null);
        };
        Engine.prototype.generateMipMapsForCubemap = function (texture) {
            if (texture.generateMipMaps) {
                var gl = this._gl;
                this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
                gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            }
        };
        Engine.prototype.flushFramebuffer = function () {
            this._gl.flush();
        };
        Engine.prototype.restoreDefaultFramebuffer = function () {
            this._currentRenderTarget = null;
            this.bindUnboundFramebuffer(null);
            this.setViewport(this._cachedViewport);
            this.wipeCaches();
        };
        // VBOs
        Engine.prototype._resetVertexBufferBinding = function () {
            this.bindArrayBuffer(null);
            this._cachedVertexBuffers = null;
        };
        Engine.prototype.createVertexBuffer = function (vertices) {
            var vbo = this._gl.createBuffer();
            this.bindArrayBuffer(vbo);
            if (vertices instanceof Float32Array) {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
            }
            else {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
            }
            this._resetVertexBufferBinding();
            vbo.references = 1;
            return vbo;
        };
        Engine.prototype.createDynamicVertexBuffer = function (vertices) {
            var vbo = this._gl.createBuffer();
            this.bindArrayBuffer(vbo);
            if (vertices instanceof Float32Array) {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
            }
            else {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
            }
            this._resetVertexBufferBinding();
            vbo.references = 1;
            return vbo;
        };
        Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
            this.bindArrayBuffer(vertexBuffer);
            if (offset === undefined) {
                offset = 0;
            }
            if (count === undefined) {
                if (vertices instanceof Float32Array) {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
                }
                else {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
                }
            }
            else {
                if (vertices instanceof Float32Array) {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
                }
                else {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
                }
            }
            this._resetVertexBufferBinding();
        };
        Engine.prototype._resetIndexBufferBinding = function () {
            this.bindIndexBuffer(null);
            this._cachedIndexBuffer = null;
        };
        Engine.prototype.createIndexBuffer = function (indices) {
            var vbo = this._gl.createBuffer();
            this.bindIndexBuffer(vbo);
            // Check for 32 bits indices
            var arrayBuffer;
            var need32Bits = false;
            if (this._caps.uintIndices) {
                for (var index = 0; index < indices.length; index++) {
                    if (indices[index] > 65535) {
                        need32Bits = true;
                        break;
                    }
                }
                arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
            }
            else {
                arrayBuffer = new Uint16Array(indices);
            }
            this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
            this._resetIndexBufferBinding();
            vbo.references = 1;
            vbo.is32Bits = need32Bits;
            return vbo;
        };
        Engine.prototype.bindArrayBuffer = function (buffer) {
            this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
        };
        Engine.prototype.bindIndexBuffer = function (buffer) {
            this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
        };
        Engine.prototype.bindBuffer = function (buffer, target) {
            if (this._currentBoundBuffer[target] !== buffer) {
                this._gl.bindBuffer(target, buffer);
                this._currentBoundBuffer[target] = buffer;
            }
        };
        Engine.prototype.updateArrayBuffer = function (data) {
            this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
        };
        Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
            var pointer = this._currentBufferPointers[indx];
            var changed = false;
            if (!pointer) {
                changed = true;
                this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
            }
            else {
                if (pointer.buffer !== buffer) {
                    pointer.buffer = buffer;
                    changed = true;
                }
                if (pointer.size !== size) {
                    pointer.size = size;
                    changed = true;
                }
                if (pointer.type !== type) {
                    pointer.type = type;
                    changed = true;
                }
                if (pointer.normalized !== normalized) {
                    pointer.normalized = normalized;
                    changed = true;
                }
                if (pointer.stride !== stride) {
                    pointer.stride = stride;
                    changed = true;
                }
                if (pointer.offset !== offset) {
                    pointer.offset = offset;
                    changed = true;
                }
            }
            if (changed) {
                this.bindArrayBuffer(buffer);
                this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
            }
        };
        Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
            if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
                this._cachedVertexBuffers = vertexBuffer;
                this._cachedEffectForVertexBuffers = effect;
                var attributesCount = effect.getAttributesCount();
                var offset = 0;
                for (var index = 0; index < attributesCount; index++) {
                    if (index < vertexDeclaration.length) {
                        var order = effect.getAttributeLocation(index);
                        if (order >= 0) {
                            if (!this._vertexAttribArraysEnabled[order]) {
                                this._gl.enableVertexAttribArray(order);
                                this._vertexAttribArraysEnabled[order] = true;
                            }
                            this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
                        }
                        offset += vertexDeclaration[index] * 4;
                    }
                    else {
                        //disable effect attributes that have no data
                        var order = effect.getAttributeLocation(index);
                        if (this._vertexAttribArraysEnabled[order]) {
                            this._gl.disableVertexAttribArray(order);
                            this._vertexAttribArraysEnabled[order] = false;
                        }
                    }
                }
            }
            if (this._cachedIndexBuffer !== indexBuffer) {
                this._cachedIndexBuffer = indexBuffer;
                this.bindIndexBuffer(indexBuffer);
                this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
            }
        };
        Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
            if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
                this._cachedVertexBuffers = vertexBuffers;
                this._cachedEffectForVertexBuffers = effect;
                var attributes = effect.getAttributesNames();
                for (var index = 0; index < attributes.length; index++) {
                    var order = effect.getAttributeLocation(index);
                    if (order >= 0) {
                        var vertexBuffer = vertexBuffers[attributes[index]];
                        if (!vertexBuffer) {
                            if (this._vertexAttribArraysEnabled[order]) {
                                this._gl.disableVertexAttribArray(order);
                                this._vertexAttribArraysEnabled[order] = false;
                            }
                            continue;
                        }
                        if (!this._vertexAttribArraysEnabled[order]) {
                            this._gl.enableVertexAttribArray(order);
                            this._vertexAttribArraysEnabled[order] = true;
                        }
                        var buffer = vertexBuffer.getBuffer();
                        this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
                        if (vertexBuffer.getIsInstanced()) {
                            this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
                            this._currentInstanceLocations.push(order);
                            this._currentInstanceBuffers.push(buffer);
                        }
                    }
                }
            }
            if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
                this._cachedIndexBuffer = indexBuffer;
                this.bindIndexBuffer(indexBuffer);
                this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
            }
        };
        Engine.prototype.unbindInstanceAttributes = function () {
            var boundBuffer;
            for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
                var instancesBuffer = this._currentInstanceBuffers[i];
                if (boundBuffer != instancesBuffer) {
                    boundBuffer = instancesBuffer;
                    this.bindArrayBuffer(instancesBuffer);
                }
                var offsetLocation = this._currentInstanceLocations[i];
                this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
            }
            this._currentInstanceBuffers.length = 0;
            this._currentInstanceLocations.length = 0;
        };
        Engine.prototype._releaseBuffer = function (buffer) {
            buffer.references--;
            if (buffer.references === 0) {
                this._gl.deleteBuffer(buffer);
                return true;
            }
            return false;
        };
        Engine.prototype.createInstancesBuffer = function (capacity) {
            var buffer = this._gl.createBuffer();
            buffer.capacity = capacity;
            this.bindArrayBuffer(buffer);
            this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
            return buffer;
        };
        Engine.prototype.deleteInstancesBuffer = function (buffer) {
            this._gl.deleteBuffer(buffer);
        };
        Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
            this.bindArrayBuffer(instancesBuffer);
            if (data) {
                this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
            }
            if (offsetLocations[0].index !== undefined) {
                var stride = 0;
                for (var i = 0; i < offsetLocations.length; i++) {
                    var ai = offsetLocations[i];
                    stride += ai.attributeSize * 4;
                }
                for (var i = 0; i < offsetLocations.length; i++) {
                    var ai = offsetLocations[i];
                    if (!this._vertexAttribArraysEnabled[ai.index]) {
                        this._gl.enableVertexAttribArray(ai.index);
                        this._vertexAttribArraysEnabled[ai.index] = true;
                    }
                    this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
                    this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
                    this._currentInstanceLocations.push(ai.index);
                    this._currentInstanceBuffers.push(instancesBuffer);
                }
            }
            else {
                for (var index = 0; index < 4; index++) {
                    var offsetLocation = offsetLocations[index];
                    if (!this._vertexAttribArraysEnabled[offsetLocation]) {
                        this._gl.enableVertexAttribArray(offsetLocation);
                        this._vertexAttribArraysEnabled[offsetLocation] = true;
                    }
                    this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
                    this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
                    this._currentInstanceLocations.push(offsetLocation);
                    this._currentInstanceBuffers.push(instancesBuffer);
                }
            }
        };
        Engine.prototype.applyStates = function () {
            this._depthCullingState.apply(this._gl);
            this._stencilState.apply(this._gl);
            this._alphaState.apply(this._gl);
        };
        Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
            // Apply states
            this.applyStates();
            this._drawCalls.addCount(1, false);
            // Render
            var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
            var mult = this._uintIndicesCurrentlySet ? 4 : 2;
            if (instancesCount) {
                this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
                return;
            }
            this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
        };
        Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
            // Apply states
            this.applyStates();
            this._drawCalls.addCount(1, false);
            if (instancesCount) {
                this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
                return;
            }
            this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
        };
        Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
            // Apply states
            this.applyStates();
            this._drawCalls.addCount(1, false);
            if (instancesCount) {
                this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
                return;
            }
            this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
        };
        // Shaders
        Engine.prototype._releaseEffect = function (effect) {
            if (this._compiledEffects[effect._key]) {
                delete this._compiledEffects[effect._key];
                if (effect.getProgram()) {
                    this._gl.deleteProgram(effect.getProgram());
                }
            }
        };
        Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
            var vertex = baseName.vertexElement || baseName.vertex || baseName;
            var fragment = baseName.fragmentElement || baseName.fragment || baseName;
            var name = vertex + "+" + fragment + "@" + defines;
            if (this._compiledEffects[name]) {
                return this._compiledEffects[name];
            }
            var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
            effect._key = name;
            this._compiledEffects[name] = effect;
            return effect;
        };
        Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
            if (uniformsNames === void 0) { uniformsNames = []; }
            if (samplers === void 0) { samplers = []; }
            if (defines === void 0) { defines = ""; }
            return this.createEffect({
                vertex: "particles",
                fragmentElement: fragmentName
            }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
        };
        Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
            context = context || this._gl;
            var vertexShader = compileShader(context, vertexCode, "vertex", defines);
            var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
            var shaderProgram = context.createProgram();
            context.attachShader(shaderProgram, vertexShader);
            context.attachShader(shaderProgram, fragmentShader);
            context.linkProgram(shaderProgram);
            var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
            if (!linked) {
                var error = context.getProgramInfoLog(shaderProgram);
                if (error) {
                    throw new Error(error);
                }
            }
            context.deleteShader(vertexShader);
            context.deleteShader(fragmentShader);
            return shaderProgram;
        };
        Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
            var results = [];
            for (var index = 0; index < uniformsNames.length; index++) {
                results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
            }
            return results;
        };
        Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
            var results = [];
            for (var index = 0; index < attributesNames.length; index++) {
                try {
                    results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
                }
                catch (e) {
                    results.push(-1);
                }
            }
            return results;
        };
        Engine.prototype.enableEffect = function (effect) {
            //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
            //    if (effect && effect.onBind) {
            //        effect.onBind(effect);
            //    }
            //    return;
            //}
            // Use program
            this.setProgram(effect.getProgram());
            this._currentEffect = effect;
            if (effect.onBind) {
                effect.onBind(effect);
            }
        };
        Engine.prototype.setIntArray = function (uniform, array) {
            if (!uniform)
                return;
            this._gl.uniform1iv(uniform, array);
        };
        Engine.prototype.setIntArray2 = function (uniform, array) {
            if (!uniform || array.length % 2 !== 0)
                return;
            this._gl.uniform2iv(uniform, array);
        };
        Engine.prototype.setIntArray3 = function (uniform, array) {
            if (!uniform || array.length % 3 !== 0)
                return;
            this._gl.uniform3iv(uniform, array);
        };
        Engine.prototype.setIntArray4 = function (uniform, array) {
            if (!uniform || array.length % 4 !== 0)
                return;
            this._gl.uniform4iv(uniform, array);
        };
        Engine.prototype.setFloatArray = function (uniform, array) {
            if (!uniform)
                return;
            this._gl.uniform1fv(uniform, array);
        };
        Engine.prototype.setFloatArray2 = function (uniform, array) {
            if (!uniform || array.length % 2 !== 0)
                return;
            this._gl.uniform2fv(uniform, array);
        };
        Engine.prototype.setFloatArray3 = function (uniform, array) {
            if (!uniform || array.length % 3 !== 0)
                return;
            this._gl.uniform3fv(uniform, array);
        };
        Engine.prototype.setFloatArray4 = function (uniform, array) {
            if (!uniform || array.length % 4 !== 0)
                return;
            this._gl.uniform4fv(uniform, array);
        };
        Engine.prototype.setArray = function (uniform, array) {
            if (!uniform)
                return;
            this._gl.uniform1fv(uniform, array);
        };
        Engine.prototype.setArray2 = function (uniform, array) {
            if (!uniform || array.length % 2 !== 0)
                return;
            this._gl.uniform2fv(uniform, array);
        };
        Engine.prototype.setArray3 = function (uniform, array) {
            if (!uniform || array.length % 3 !== 0)
                return;
            this._gl.uniform3fv(uniform, array);
        };
        Engine.prototype.setArray4 = function (uniform, array) {
            if (!uniform || array.length % 4 !== 0)
                return;
            this._gl.uniform4fv(uniform, array);
        };
        Engine.prototype.setMatrices = function (uniform, matrices) {
            if (!uniform)
                return;
            this._gl.uniformMatrix4fv(uniform, false, matrices);
        };
        Engine.prototype.setMatrix = function (uniform, matrix) {
            if (!uniform)
                return;
            this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
        };
        Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
            if (!uniform)
                return;
            this._gl.uniformMatrix3fv(uniform, false, matrix);
        };
        Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
            if (!uniform)
                return;
            this._gl.uniformMatrix2fv(uniform, false, matrix);
        };
        Engine.prototype.setFloat = function (uniform, value) {
            if (!uniform)
                return;
            this._gl.uniform1f(uniform, value);
        };
        Engine.prototype.setFloat2 = function (uniform, x, y) {
            if (!uniform)
                return;
            this._gl.uniform2f(uniform, x, y);
        };
        Engine.prototype.setFloat3 = function (uniform, x, y, z) {
            if (!uniform)
                return;
            this._gl.uniform3f(uniform, x, y, z);
        };
        Engine.prototype.setBool = function (uniform, bool) {
            if (!uniform)
                return;
            this._gl.uniform1i(uniform, bool);
        };
        Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
            if (!uniform)
                return;
            this._gl.uniform4f(uniform, x, y, z, w);
        };
        Engine.prototype.setColor3 = function (uniform, color3) {
            if (!uniform)
                return;
            this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
        };
        Engine.prototype.setColor4 = function (uniform, color3, alpha) {
            if (!uniform)
                return;
            this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
        };
        // States
        Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
            if (zOffset === void 0) { zOffset = 0; }
            if (reverseSide === void 0) { reverseSide = false; }
            // Culling        
            var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
            var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
            var cullFace = this.cullBackFaces ? showSide : hideSide;
            if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
                if (culling) {
                    this._depthCullingState.cullFace = cullFace;
                    this._depthCullingState.cull = true;
                }
                else {
                    this._depthCullingState.cull = false;
                }
            }
            // Z offset
            this._depthCullingState.zOffset = zOffset;
        };
        Engine.prototype.setDepthBuffer = function (enable) {
            this._depthCullingState.depthTest = enable;
        };
        Engine.prototype.getDepthWrite = function () {
            return this._depthCullingState.depthMask;
        };
        Engine.prototype.setDepthWrite = function (enable) {
            this._depthCullingState.depthMask = enable;
        };
        Engine.prototype.setColorWrite = function (enable) {
            this._gl.colorMask(enable, enable, enable, enable);
        };
        Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
            if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
            if (this._alphaMode === mode) {
                return;
            }
            switch (mode) {
                case Engine.ALPHA_DISABLE:
                    this._alphaState.alphaBlend = false;
                    break;
                case Engine.ALPHA_COMBINE:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_ONEONE:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_ADD:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_SUBTRACT:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_MULTIPLY:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_MAXIMIZED:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
            }
            if (!noDepthWriteChange) {
                this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
            }
            this._alphaMode = mode;
        };
        Engine.prototype.getAlphaMode = function () {
            return this._alphaMode;
        };
        Engine.prototype.setAlphaTesting = function (enable) {
            this._alphaTest = enable;
        };
        Engine.prototype.getAlphaTesting = function () {
            return this._alphaTest;
        };
        // Textures
        Engine.prototype.wipeCaches = function () {
            this.resetTextureCache();
            this._currentEffect = null;
            this._stencilState.reset();
            this._depthCullingState.reset();
            this.setDepthFunctionToLessOrEqual();
            this._alphaState.reset();
            this._cachedVertexBuffers = null;
            this._cachedIndexBuffer = null;
            this._cachedEffectForVertexBuffers = null;
        };
        Engine.prototype.setSamplingMode = function (texture, samplingMode) {
            var gl = this._gl;
            this._bindTextureDirectly(gl.TEXTURE_2D, texture);
            var magFilter = gl.NEAREST;
            var minFilter = gl.NEAREST;
            if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
                magFilter = gl.LINEAR;
                minFilter = gl.LINEAR;
            }
            else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
                magFilter = gl.LINEAR;
                minFilter = gl.LINEAR_MIPMAP_LINEAR;
            }
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
            this._bindTextureDirectly(gl.TEXTURE_2D, null);
            texture.samplingMode = samplingMode;
        };
        /**
         * Set the compressed texture format to use, based on the formats you have,
         * the formats supported by the hardware / browser, and those currently implemented
         * in BJS.
         *
         * Note: The result of this call is not taken into account texture is base64 or when
         * using a database / manifest.
         *
         * @param {Array<string>} formatsAvailable - Extension names including dot.  Case
         * and order do not matter.
         * @returns The extension selected.
         */
        Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
            for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
                // code to allow the formats to be added as they can be developed / hw tested
                if (this._texturesSupported[i] === '.astc')
                    continue;
                if (this._texturesSupported[i] === '.pvr')
                    continue;
                if (this._texturesSupported[i] === '.etc1')
                    continue;
                if (this._texturesSupported[i] === '.etc2')
                    continue;
                for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
                    if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
                        return this._textureFormatInUse = this._texturesSupported[i];
                    }
                }
            }
            // actively set format to nothing, to allow this to be called more than once
            // and possibly fail the 2nd time
            return this._textureFormatInUse = null;
        };
        Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
            var _this = this;
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (buffer === void 0) { buffer = null; }
            var texture = this._gl.createTexture();
            var extension;
            var fromData = false;
            if (url.substr(0, 5) === "data:") {
                fromData = true;
            }
            if (!fromData) {
                var lastDot = url.lastIndexOf('.');
                extension = url.substring(lastDot).toLowerCase();
                if (this._textureFormatInUse && !fromData && !scene.database) {
                    extension = this._textureFormatInUse;
                    url = url.substring(0, lastDot) + this._textureFormatInUse;
                }
            }
            else {
                var oldUrl = url;
                fromData = oldUrl.split(':');
                url = oldUrl;
                extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
            }
            var isDDS = (extension === ".dds");
            var isTGA = (extension === ".tga");
            scene._addPendingData(texture);
            texture.url = url;
            texture.noMipmap = noMipmap;
            texture.references = 1;
            texture.samplingMode = samplingMode;
            texture.onLoadedCallbacks = [onLoad];
            this._loadedTexturesCache.push(texture);
            var onerror = function () {
                scene._removePendingData(texture);
                if (onError) {
                    onError();
                }
            };
            var callback;
            if (isTGA) {
                callback = function (arrayBuffer) {
                    var data = new Uint8Array(arrayBuffer);
                    var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
                    prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
                        BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
                    }, samplingMode);
                };
                if (!(fromData instanceof Array))
                    BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
                        callback(arrayBuffer);
                    }, null, scene.database, true, onerror);
                else
                    callback(buffer);
            }
            else if (isDDS) {
                callback = function (data) {
                    var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
                    var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
                    prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
                        BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
                    }, samplingMode);
                };
                if (!(fromData instanceof Array))
                    BABYLON.Tools.LoadFile(url, function (data) {
                        callback(data);
                    }, null, scene.database, true, onerror);
                else
                    callback(buffer);
            }
            else {
                var onload = function (img) {
                    prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
                        var isPot = (img.width === potWidth && img.height === potHeight);
                        if (!isPot) {
                            _this._prepareWorkingCanvas();
                            _this._workingCanvas.width = potWidth;
                            _this._workingCanvas.height = potHeight;
                            if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
                                _this._workingContext.imageSmoothingEnabled = false;
                                _this._workingContext.mozImageSmoothingEnabled = false;
                                _this._workingContext.oImageSmoothingEnabled = false;
                                _this._workingContext.webkitImageSmoothingEnabled = false;
                                _this._workingContext.msImageSmoothingEnabled = false;
                            }
                            _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
                            if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
                                _this._workingContext.imageSmoothingEnabled = true;
                                _this._workingContext.mozImageSmoothingEnabled = true;
                                _this._workingContext.oImageSmoothingEnabled = true;
                                _this._workingContext.webkitImageSmoothingEnabled = true;
                                _this._workingContext.msImageSmoothingEnabled = true;
                            }
                        }
                        _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
                    }, samplingMode);
                };
                if (!(fromData instanceof Array))
                    BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
                else
                    BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
            }
            return texture;
        };
        Engine.prototype._getInternalFormat = function (format) {
            var internalFormat = this._gl.RGBA;
            switch (format) {
                case Engine.TEXTUREFORMAT_ALPHA:
                    internalFormat = this._gl.ALPHA;
                    break;
                case Engine.TEXTUREFORMAT_LUMINANCE:
                    internalFormat = this._gl.LUMINANCE;
                    break;
                case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
                    internalFormat = this._gl.LUMINANCE_ALPHA;
                    break;
                case Engine.TEXTUREFORMAT_RGB:
                    internalFormat = this._gl.RGB;
                    break;
                case Engine.TEXTUREFORMAT_RGBA:
                    internalFormat = this._gl.RGBA;
                    break;
            }
            return internalFormat;
        };
        Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
            if (compression === void 0) { compression = null; }
            var internalFormat = this._getInternalFormat(format);
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
            this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
            if (texture._width % 4 !== 0) {
                this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
            }
            if (compression) {
                this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
            }
            else {
                this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
            }
            if (texture.generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            this.resetTextureCache();
            texture.isReady = true;
        };
        Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
            if (compression === void 0) { compression = null; }
            var texture = this._gl.createTexture();
            texture._baseWidth = width;
            texture._baseHeight = height;
            texture._width = width;
            texture._height = height;
            texture.references = 1;
            this.updateRawTexture(texture, data, format, invertY, compression);
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
            // Filters
            var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            texture.samplingMode = samplingMode;
            this._loadedTexturesCache.push(texture);
            return texture;
        };
        Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
            var texture = this._gl.createTexture();
            texture._baseWidth = width;
            texture._baseHeight = height;
            if (generateMipMaps) {
                width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
                height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
            }
            this.resetTextureCache();
            texture._width = width;
            texture._height = height;
            texture.isReady = false;
            texture.generateMipMaps = generateMipMaps;
            texture.references = 1;
            texture.samplingMode = samplingMode;
            this.updateTextureSamplingMode(samplingMode, texture);
            this._loadedTexturesCache.push(texture);
            return texture;
        };
        Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
            var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
            if (texture.isCube) {
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
                this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
                this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
            }
            else {
                this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
                this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
                this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
                this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            }
        };
        Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
            if (premulAlpha === void 0) { premulAlpha = false; }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
            this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
            if (premulAlpha) {
                this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
            }
            this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
            if (texture.generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            if (premulAlpha) {
                this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
            }
            this.resetTextureCache();
            texture.isReady = true;
        };
        Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
            if (texture._isDisabled) {
                return;
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
            this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
            try {
                // Testing video texture support
                if (this._videoTextureSupported === undefined) {
                    this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
                    if (this._gl.getError() !== 0) {
                        this._videoTextureSupported = false;
                    }
                    else {
                        this._videoTextureSupported = true;
                    }
                }
                // Copy video through the current working canvas if video texture is not supported
                if (!this._videoTextureSupported) {
                    if (!texture._workingCanvas) {
                        texture._workingCanvas = document.createElement("canvas");
                        texture._workingContext = texture._workingCanvas.getContext("2d");
                        texture._workingCanvas.width = texture._width;
                        texture._workingCanvas.height = texture._height;
                    }
                    texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
                    this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
                }
                else {
                    this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
                }
                if (texture.generateMipMaps) {
                    this._gl.generateMipmap(this._gl.TEXTURE_2D);
                }
                this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
                this.resetTextureCache();
                texture.isReady = true;
            }
            catch (ex) {
                // Something unexpected
                // Let's disable the texture
                texture._isDisabled = true;
            }
        };
        Engine.prototype.createRenderTargetTexture = function (size, options) {
            // old version had a "generateMipMaps" arg instead of options.
            // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
            // in the same way, generateDepthBuffer is defaulted to true
            var generateMipMaps = false;
            var generateDepthBuffer = true;
            var generateStencilBuffer = false;
            var type = Engine.TEXTURETYPE_UNSIGNED_INT;
            var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
            if (options !== undefined) {
                generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
                generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
                generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
                type = options.type === undefined ? type : options.type;
                if (options.samplingMode !== undefined) {
                    samplingMode = options.samplingMode;
                }
                if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
                    // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
                    samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
                }
                else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
                    // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
                    samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
                }
            }
            var gl = this._gl;
            var texture = gl.createTexture();
            this._bindTextureDirectly(gl.TEXTURE_2D, texture);
            var width = size.width || size;
            var height = size.height || size;
            var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
            if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
                type = Engine.TEXTURETYPE_UNSIGNED_INT;
                BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
            }
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
            var depthStencilBuffer;
            // Create the depth/stencil buffer
            if (generateStencilBuffer) {
                depthStencilBuffer = gl.createRenderbuffer();
                gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
            }
            else if (generateDepthBuffer) {
                depthStencilBuffer = gl.createRenderbuffer();
                gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
            }
            // Create the framebuffer
            var framebuffer = gl.createFramebuffer();
            this.bindUnboundFramebuffer(framebuffer);
            // Manage attachments
            if (generateStencilBuffer) {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
            }
            else if (generateDepthBuffer) {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
            }
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
            if (generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            // Unbind
            this._bindTextureDirectly(gl.TEXTURE_2D, null);
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            this.bindUnboundFramebuffer(null);
            texture._framebuffer = framebuffer;
            if (generateDepthBuffer) {
                texture._depthBuffer = depthStencilBuffer;
            }
            texture._baseWidth = width;
            texture._baseHeight = height;
            texture._width = width;
            texture._height = height;
            texture.isReady = true;
            texture.generateMipMaps = generateMipMaps;
            texture.references = 1;
            texture.samplingMode = samplingMode;
            texture.type = type;
            this.resetTextureCache();
            this._loadedTexturesCache.push(texture);
            return texture;
        };
        Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
            var gl = this._gl;
            var texture = gl.createTexture();
            var generateMipMaps = true;
            var generateDepthBuffer = true;
            var generateStencilBuffer = false;
            var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
            if (options !== undefined) {
                generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
                generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
                generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
                if (options.samplingMode !== undefined) {
                    samplingMode = options.samplingMode;
                }
            }
            texture.isCube = true;
            texture.references = 1;
            texture.generateMipMaps = generateMipMaps;
            texture.references = 1;
            texture.samplingMode = samplingMode;
            var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
            for (var face = 0; face < 6; face++) {
                gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
            }
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            // Create the depth buffer
            var depthStencilBuffer;
            // Create the depth/stencil buffer
            if (generateStencilBuffer) {
                depthStencilBuffer = gl.createRenderbuffer();
                gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
            }
            else if (generateDepthBuffer) {
                depthStencilBuffer = gl.createRenderbuffer();
                gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
            }
            // Create the framebuffer
            var framebuffer = gl.createFramebuffer();
            this.bindUnboundFramebuffer(framebuffer);
            // Manage attachments
            if (generateStencilBuffer) {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
            }
            else if (generateDepthBuffer) {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
            }
            // Mipmaps
            if (texture.generateMipMaps) {
                this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
                gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
            }
            // Unbind
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            this.bindUnboundFramebuffer(null);
            texture._framebuffer = framebuffer;
            if (generateDepthBuffer) {
                texture._depthBuffer = depthStencilBuffer;
            }
            texture._width = size;
            texture._height = size;
            texture.isReady = true;
            this.resetTextureCache();
            this._loadedTexturesCache.push(texture);
            return texture;
        };
        Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
            var _this = this;
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            var gl = this._gl;
            var texture = gl.createTexture();
            texture.isCube = true;
            texture.url = rootUrl;
            texture.references = 1;
            texture.onLoadedCallbacks = [];
            var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
            var isDDS = this.getCaps().s3tc && (extension === ".dds");
            if (isDDS) {
                BABYLON.Tools.LoadFile(rootUrl, function (data) {
                    var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
                    var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
                    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
                    BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
                    if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
                        gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                    }
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
                    _this.resetTextureCache();
                    texture._width = info.width;
                    texture._height = info.height;
                    texture.isReady = true;
                }, null, null, true, onError);
            }
            else {
                cascadeLoad(rootUrl, scene, function (imgs) {
                    var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
                    var height = width;
                    _this._prepareWorkingCanvas();
                    _this._workingCanvas.width = width;
                    _this._workingCanvas.height = height;
                    var faces = [
                        gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                        gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
                    ];
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
                    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                    for (var index = 0; index < faces.length; index++) {
                        _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
                        gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
                    }
                    if (!noMipmap) {
                        gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                    }
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
                    _this.resetTextureCache();
                    texture._width = width;
                    texture._height = height;
                    texture.isReady = true;
                    texture.onLoadedCallbacks.forEach(function (callback) {
                        callback();
                    });
                    if (onLoad) {
                        onLoad();
                    }
                }, files, onError);
            }
            this._loadedTexturesCache.push(texture);
            return texture;
        };
        Engine.prototype.updateTextureSize = function (texture, width, height) {
            texture._width = width;
            texture._height = height;
            texture._size = width * height;
            texture._baseWidth = width;
            texture._baseHeight = height;
        };
        Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
            var _this = this;
            var gl = this._gl;
            var texture = gl.createTexture();
            scene._addPendingData(texture);
            texture.isCube = true;
            texture.references = 1;
            texture.url = url;
            var internalFormat = this._getInternalFormat(format);
            var textureType = gl.UNSIGNED_BYTE;
            if (type === Engine.TEXTURETYPE_FLOAT) {
                textureType = gl.FLOAT;
            }
            var width = size;
            var height = width;
            var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
            texture._width = width;
            texture._height = height;
            var onerror = function () {
                scene._removePendingData(texture);
            };
            var internalCallback = function (data) {
                var rgbeDataArrays = callback(data);
                var facesIndex = [
                    gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                    gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
                ];
                width = texture._width;
                height = texture._height;
                isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
                _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
                gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
                if (!noMipmap && isPot) {
                    if (mipmmapGenerator) {
                        var arrayTemp = [];
                        // Data are known to be in +X +Y +Z -X -Y -Z
                        // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
                        arrayTemp.push(rgbeDataArrays[0]); // +X
                        arrayTemp.push(rgbeDataArrays[3]); // -X
                        arrayTemp.push(rgbeDataArrays[1]); // +Y
                        arrayTemp.push(rgbeDataArrays[4]); // -Y
                        arrayTemp.push(rgbeDataArrays[2]); // +Z
                        arrayTemp.push(rgbeDataArrays[5]); // -Z
                        var mipData = mipmmapGenerator(arrayTemp);
                        for (var level = 0; level < mipData.length; level++) {
                            var mipSize = width >> level;
                            // mipData is order in +X -X +Y -Y +Z -Z
                            gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
                            gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
                            gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
                            gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
                            gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
                            gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
                        }
                    }
                    else {
                        // Data are known to be in +X +Y +Z -X -Y -Z
                        for (var index = 0; index < facesIndex.length; index++) {
                            var faceData = rgbeDataArrays[index];
                            gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
                        }
                        gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                        // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
                        // By following the webgl standard changes from Revision 7, 2014/11/24
                        // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
                        if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
                            BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
                            // Data are known to be in +X +Y +Z -X -Y -Z
                            for (var index = 0; index < facesIndex.length; index++) {
                                var faceData = rgbeDataArrays[index];
                                // Create a new RGBA Face.
                                var newFaceData = new Float32Array(width * height * 4);
                                for (var x = 0; x < width; x++) {
                                    for (var y = 0; y < height; y++) {
                                        var index_1 = (y * width + x) * 3;
                                        var newIndex = (y * width + x) * 4;
                                        // Map Old Value to new value.
                                        newFaceData[newIndex + 0] = faceData[index_1 + 0];
                                        newFaceData[newIndex + 1] = faceData[index_1 + 1];
                                        newFaceData[newIndex + 2] = faceData[index_1 + 2];
                                        // Add fully opaque alpha channel.
                                        newFaceData[newIndex + 3] = 1;
                                    }
                                }
                                // Reupload the face.
                                gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
                            }
                            // Try to generate mipmap again.
                            gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                        }
                    }
                }
                else {
                    noMipmap = true;
                }
                if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                }
                else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                }
                else {
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
                }
                gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
                texture.isReady = true;
                _this.resetTextureCache();
                scene._removePendingData(texture);
            };
            BABYLON.Tools.LoadFile(url, function (data) {
                internalCallback(data);
            }, onerror, scene.database, true);
            return texture;
        };
        ;
        Engine.prototype._releaseTexture = function (texture) {
            var gl = this._gl;
            if (texture._framebuffer) {
                gl.deleteFramebuffer(texture._framebuffer);
            }
            if (texture._depthBuffer) {
                gl.deleteRenderbuffer(texture._depthBuffer);
            }
            gl.deleteTexture(texture);
            // Unbind channels
            this.unbindAllTextures();
            var index = this._loadedTexturesCache.indexOf(texture);
            if (index !== -1) {
                this._loadedTexturesCache.splice(index, 1);
            }
        };
        Engine.prototype.setProgram = function (program) {
            if (this._currentProgram !== program) {
                this._gl.useProgram(program);
                this._currentProgram = program;
            }
        };
        Engine.prototype.bindSamplers = function (effect) {
            this.setProgram(effect.getProgram());
            var samplers = effect.getSamplers();
            for (var index = 0; index < samplers.length; index++) {
                var uniform = effect.getUniform(samplers[index]);
                this._gl.uniform1i(uniform, index);
            }
            this._currentEffect = null;
        };
        Engine.prototype.activateTexture = function (texture) {
            if (this._activeTexture !== texture) {
                this._gl.activeTexture(texture);
                this._activeTexture = texture;
            }
        };
        Engine.prototype._bindTextureDirectly = function (target, texture) {
            if (this._activeTexturesCache[this._activeTexture] !== texture) {
                this._gl.bindTexture(target, texture);
                this._activeTexturesCache[this._activeTexture] = texture;
            }
        };
        Engine.prototype._bindTexture = function (channel, texture) {
            if (channel < 0) {
                return;
            }
            this.activateTexture(this._gl["TEXTURE" + channel]);
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
        };
        Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
            this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
        };
        Engine.prototype.unbindAllTextures = function () {
            for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
                this.activateTexture(this._gl["TEXTURE" + channel]);
                this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
            }
        };
        Engine.prototype.setTexture = function (channel, uniform, texture) {
            if (channel < 0) {
                return;
            }
            this._gl.uniform1i(uniform, channel);
            this._setTexture(channel, texture);
        };
        Engine.prototype._setTexture = function (channel, texture) {
            // Not ready?
            if (!texture || !texture.isReady()) {
                if (this._activeTexturesCache[channel] != null) {
                    this.activateTexture(this._gl["TEXTURE" + channel]);
                    this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
                    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
                }
                return;
            }
            // Video
            var alreadyActivated = false;
            if (texture instanceof BABYLON.VideoTexture) {
                this.activateTexture(this._gl["TEXTURE" + channel]);
                alreadyActivated = true;
                texture.update();
            }
            else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
                texture.delayLoad();
                return;
            }
            var internalTexture = texture.getInternalTexture();
            if (this._activeTexturesCache[channel] === internalTexture) {
                return;
            }
            if (!alreadyActivated) {
                this.activateTexture(this._gl["TEXTURE" + channel]);
            }
            if (internalTexture.isCube) {
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
                if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
                    internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
                    // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE.  All other modes use REPEAT.
                    var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
                    this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
                }
                this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
            }
            else {
                this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
                if (internalTexture._cachedWrapU !== texture.wrapU) {
                    internalTexture._cachedWrapU = texture.wrapU;
                    switch (texture.wrapU) {
                        case BABYLON.Texture.WRAP_ADDRESSMODE:
                            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
                            break;
                        case BABYLON.Texture.CLAMP_ADDRESSMODE:
                            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
                            break;
                        case BABYLON.Texture.MIRROR_ADDRESSMODE:
                            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
                            break;
                    }
                }
                if (internalTexture._cachedWrapV !== texture.wrapV) {
                    internalTexture._cachedWrapV = texture.wrapV;
                    switch (texture.wrapV) {
                        case BABYLON.Texture.WRAP_ADDRESSMODE:
                            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
                            break;
                        case BABYLON.Texture.CLAMP_ADDRESSMODE:
                            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
                            break;
                        case BABYLON.Texture.MIRROR_ADDRESSMODE:
                            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
                            break;
                    }
                }
                this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
            }
        };
        Engine.prototype.setTextureArray = function (channel, uniform, textures) {
            if (channel < 0) {
                return;
            }
            if (!this._textureUnits || this._textureUnits.length !== textures.length) {
                this._textureUnits = new Int32Array(textures.length);
            }
            for (var i = 0; i < textures.length; i++) {
                this._textureUnits[i] = channel + i;
            }
            this._gl.uniform1iv(uniform, this._textureUnits);
            for (var index = 0; index < textures.length; index++) {
                this._setTexture(channel + index, textures[index]);
            }
        };
        Engine.prototype._setAnisotropicLevel = function (key, texture) {
            var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
            var value = texture.anisotropicFilteringLevel;
            if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
                value = 1;
            }
            if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
                this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
                texture._cachedAnisotropicFilteringLevel = value;
            }
        };
        Engine.prototype.readPixels = function (x, y, width, height) {
            var data = new Uint8Array(height * width * 4);
            this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
            return data;
        };
        /**
         * Add an externaly attached data from its key.
         * This method call will fail and return false, if such key already exists.
         * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
         * @param key the unique key that identifies the data
         * @param data the data object to associate to the key for this Engine instance
         * @return true if no such key were already present and the data was added successfully, false otherwise
         */
        Engine.prototype.addExternalData = function (key, data) {
            return this._externalData.add(key, data);
        };
        /**
         * Get an externaly attached data from its key
         * @param key the unique key that identifies the data
         * @return the associated data, if present (can be null), or undefined if not present
         */
        Engine.prototype.getExternalData = function (key) {
            return this._externalData.get(key);
        };
        /**
         * Get an externaly attached data from its key, create it using a factory if it's not already present
         * @param key the unique key that identifies the data
         * @param factory the factory that will be called to create the instance if and only if it doesn't exists
         * @return the associated data, can be null if the factory returned null.
         */
        Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
            return this._externalData.getOrAddWithFactory(key, factory);
        };
        /**
         * Remove an externaly attached data from the Engine instance
         * @param key the unique key that identifies the data
         * @return true if the data was successfully removed, false if it doesn't exist
         */
        Engine.prototype.removeExternalData = function (key) {
            return this._externalData.remove(key);
        };
        Engine.prototype.releaseInternalTexture = function (texture) {
            if (!texture) {
                return;
            }
            texture.references--;
            // Final reference ?
            if (texture.references === 0) {
                var texturesCache = this.getLoadedTexturesCache();
                var index = texturesCache.indexOf(texture);
                if (index > -1) {
                    texturesCache.splice(index, 1);
                }
                this._releaseTexture(texture);
            }
        };
        Engine.prototype.unbindAllAttributes = function () {
            for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
                if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
                    continue;
                }
                this._gl.disableVertexAttribArray(i);
                this._vertexAttribArraysEnabled[i] = false;
            }
        };
        // Dispose
        Engine.prototype.dispose = function () {
            this.hideLoadingUI();
            this.stopRenderLoop();
            // Release scenes
            while (this.scenes.length) {
                this.scenes[0].dispose();
            }
            // Release audio engine
            Engine.audioEngine.dispose();
            // Release effects
            for (var name in this._compiledEffects) {
                this._gl.deleteProgram(this._compiledEffects[name]._program);
            }
            // Unbind
            this.unbindAllAttributes();
            this._gl = null;
            //WebVR
            this.disableVR();
            // Events
            window.removeEventListener("blur", this._onBlur);
            window.removeEventListener("focus", this._onFocus);
            document.removeEventListener("fullscreenchange", this._onFullscreenChange);
            document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
            document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
            document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
            document.removeEventListener("pointerlockchange", this._onPointerLockChange);
            document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
            document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
            document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
        };
        // Loading screen
        Engine.prototype.displayLoadingUI = function () {
            this._loadingScreen.displayLoadingUI();
        };
        Engine.prototype.hideLoadingUI = function () {
            this._loadingScreen.hideLoadingUI();
        };
        Object.defineProperty(Engine.prototype, "loadingScreen", {
            get: function () {
                return this._loadingScreen;
            },
            set: function (loadingScreen) {
                this._loadingScreen = loadingScreen;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "loadingUIText", {
            set: function (text) {
                this._loadingScreen.loadingUIText = text;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
            set: function (color) {
                this._loadingScreen.loadingUIBackgroundColor = color;
            },
            enumerable: true,
            configurable: true
        });
        Engine.prototype.attachContextLostEvent = function (callback) {
            this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
        };
        Engine.prototype.attachContextRestoredEvent = function (callback) {
            this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
        };
        Engine.prototype.getVertexShaderSource = function (program) {
            var shaders = this._gl.getAttachedShaders(program);
            return this._gl.getShaderSource(shaders[0]);
        };
        Engine.prototype.getFragmentShaderSource = function (program) {
            var shaders = this._gl.getAttachedShaders(program);
            return this._gl.getShaderSource(shaders[1]);
        };
        // FPS
        Engine.prototype.getFps = function () {
            return this.fps;
        };
        Engine.prototype.getDeltaTime = function () {
            return this.deltaTime;
        };
        Engine.prototype._measureFps = function () {
            this.previousFramesDuration.push(BABYLON.Tools.Now);
            var length = this.previousFramesDuration.length;
            if (length >= 2) {
                this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
            }
            if (length >= this.fpsRange) {
                if (length > this.fpsRange) {
                    this.previousFramesDuration.splice(0, 1);
                    length = this.previousFramesDuration.length;
                }
                var sum = 0;
                for (var id = 0; id < length - 1; id++) {
                    sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
                }
                this.fps = 1000.0 / (sum / (length - 1));
            }
        };
        Engine.prototype._canRenderToFloatTexture = function () {
            return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
        };
        Engine.prototype._canRenderToHalfFloatTexture = function () {
            return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
        };
        // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
        Engine.prototype._canRenderToTextureOfType = function (format, extension) {
            var tempcanvas = document.createElement("canvas");
            tempcanvas.height = 16;
            tempcanvas.width = 16;
            var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
            // extension.
            var ext = gl.getExtension(extension);
            if (!ext) {
                return false;
            }
            // setup GLSL program
            var vertexCode = "attribute vec4 a_position;\n                void main() {\n                    gl_Position = a_position;\n                }";
            var fragmentCode = "precision mediump float;\n                uniform vec4 u_color;\n                uniform sampler2D u_texture;\n\n                void main() {\n                    gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n                }";
            var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
            gl.useProgram(program);
            // look up where the vertex data needs to go.
            var positionLocation = gl.getAttribLocation(program, "a_position");
            var colorLoc = gl.getUniformLocation(program, "u_color");
            // provide texture coordinates for the rectangle.
            var positionBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
                -1.0, -1.0,
                1.0, -1.0,
                -1.0, 1.0,
                -1.0, 1.0,
                1.0, -1.0,
                1.0, 1.0]), gl.STATIC_DRAW);
            gl.enableVertexAttribArray(positionLocation);
            gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
            var whiteTex = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, whiteTex);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
            var tex = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, tex);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
            var fb = gl.createFramebuffer();
            gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
            var cleanup = function () {
                gl.deleteProgram(program);
                gl.disableVertexAttribArray(positionLocation);
                gl.deleteBuffer(positionBuffer);
                gl.deleteFramebuffer(fb);
                gl.deleteTexture(whiteTex);
                gl.deleteTexture(tex);
            };
            var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
            if (status !== gl.FRAMEBUFFER_COMPLETE) {
                BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
                cleanup();
                return false;
            }
            // Draw the rectangle.
            gl.bindTexture(gl.TEXTURE_2D, whiteTex);
            gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
            gl.bindTexture(gl.TEXTURE_2D, tex);
            gl.bindFramebuffer(gl.FRAMEBUFFER, null);
            gl.clearColor(1, 0, 0, 1);
            gl.clear(gl.COLOR_BUFFER_BIT);
            gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
            var pixel = new Uint8Array(4);
            gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
            if (pixel[0] !== 0 ||
                pixel[1] < 248 ||
                pixel[2] < 248 ||
                pixel[3] < 254) {
                BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
                cleanup();
                return false;
            }
            // Succesfully rendered to "format" texture.
            cleanup();
            return true;
        };
        // Statics
        Engine.isSupported = function () {
            try {
                // Avoid creating an unsized context for CocoonJS, since size determined on first creation.  Is not resizable
                if (navigator.isCocoonJS) {
                    return true;
                }
                var tempcanvas = document.createElement("canvas");
                var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
                return gl != null && !!window.WebGLRenderingContext;
            }
            catch (e) {
                return false;
            }
        };
        // Const statics
        Engine._ALPHA_DISABLE = 0;
        Engine._ALPHA_ADD = 1;
        Engine._ALPHA_COMBINE = 2;
        Engine._ALPHA_SUBTRACT = 3;
        Engine._ALPHA_MULTIPLY = 4;
        Engine._ALPHA_MAXIMIZED = 5;
        Engine._ALPHA_ONEONE = 6;
        Engine._DELAYLOADSTATE_NONE = 0;
        Engine._DELAYLOADSTATE_LOADED = 1;
        Engine._DELAYLOADSTATE_LOADING = 2;
        Engine._DELAYLOADSTATE_NOTLOADED = 4;
        Engine._TEXTUREFORMAT_ALPHA = 0;
        Engine._TEXTUREFORMAT_LUMINANCE = 1;
        Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
        Engine._TEXTUREFORMAT_RGB = 4;
        Engine._TEXTUREFORMAT_RGBA = 5;
        Engine._TEXTURETYPE_UNSIGNED_INT = 0;
        Engine._TEXTURETYPE_FLOAT = 1;
        Engine._TEXTURETYPE_HALF_FLOAT = 2;
        // Depht or Stencil test Constants.
        Engine._NEVER = 0x0200; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
        Engine._ALWAYS = 0x0207; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
        Engine._LESS = 0x0201; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
        Engine._EQUAL = 0x0202; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
        Engine._LEQUAL = 0x0203; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
        Engine._GREATER = 0x0204; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
        Engine._GEQUAL = 0x0206; //	Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
        Engine._NOTEQUAL = 0x0205; //  Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
        // Stencil Actions Constants.
        Engine._KEEP = 0x1E00;
        Engine._REPLACE = 0x1E01;
        Engine._INCR = 0x1E02;
        Engine._DECR = 0x1E03;
        Engine._INVERT = 0x150A;
        Engine._INCR_WRAP = 0x8507;
        Engine._DECR_WRAP = 0x8508;
        // Updatable statics so stick with vars here
        Engine.CollisionsEpsilon = 0.001;
        Engine.CodeRepository = "src/";
        Engine.ShadersRepository = "src/Shaders/";
        return Engine;
    }());
    BABYLON.Engine = Engine;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.engine.js.map
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * Node is the basic class for all scene objects (Mesh, Light Camera).
     */
    var Node = (function () {
        /**
         * @constructor
         * @param {string} name - the name and id to be given to this node
         * @param {BABYLON.Scene} the scene this node will be added to
         */
        function Node(name, scene) {
            this.state = "";
            this.metadata = null;
            this.doNotSerialize = false;
            this.animations = new Array();
            this._ranges = {};
            this._childrenFlag = -1;
            this._isEnabled = true;
            this._isReady = true;
            this._currentRenderId = -1;
            this._parentRenderId = -1;
            /**
            * An event triggered when the mesh is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            this.name = name;
            this.id = name;
            this._scene = scene;
            this._initCache();
        }
        Object.defineProperty(Node.prototype, "parent", {
            get: function () {
                return this._parentNode;
            },
            set: function (parent) {
                if (this._parentNode === parent) {
                    return;
                }
                if (this._parentNode) {
                    var index = this._parentNode._children.indexOf(this);
                    if (index !== -1) {
                        this._parentNode._children.splice(index, 1);
                    }
                }
                this._parentNode = parent;
                if (this._parentNode) {
                    if (!this._parentNode._children) {
                        this._parentNode._children = new Array();
                    }
                    this._parentNode._children.push(this);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Node.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Node.prototype.getScene = function () {
            return this._scene;
        };
        Node.prototype.getEngine = function () {
            return this._scene.getEngine();
        };
        // override it in derived class
        Node.prototype.getWorldMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        // override it in derived class if you add new variables to the cache
        // and call the parent class method
        Node.prototype._initCache = function () {
            this._cache = {};
            this._cache.parent = undefined;
        };
        Node.prototype.updateCache = function (force) {
            if (!force && this.isSynchronized())
                return;
            this._cache.parent = this.parent;
            this._updateCache();
        };
        // override it in derived class if you add new variables to the cache
        // and call the parent class method if !ignoreParentClass
        Node.prototype._updateCache = function (ignoreParentClass) {
        };
        // override it in derived class if you add new variables to the cache
        Node.prototype._isSynchronized = function () {
            return true;
        };
        Node.prototype._markSyncedWithParent = function () {
            this._parentRenderId = this.parent._currentRenderId;
        };
        Node.prototype.isSynchronizedWithParent = function () {
            if (!this.parent) {
                return true;
            }
            if (this._parentRenderId !== this.parent._currentRenderId) {
                return false;
            }
            return this.parent.isSynchronized();
        };
        Node.prototype.isSynchronized = function (updateCache) {
            var check = this.hasNewParent();
            check = check || !this.isSynchronizedWithParent();
            check = check || !this._isSynchronized();
            if (updateCache)
                this.updateCache(true);
            return !check;
        };
        Node.prototype.hasNewParent = function (update) {
            if (this._cache.parent === this.parent)
                return false;
            if (update)
                this._cache.parent = this.parent;
            return true;
        };
        /**
         * Is this node ready to be used/rendered
         * @return {boolean} is it ready
         */
        Node.prototype.isReady = function () {
            return this._isReady;
        };
        /**
         * Is this node enabled.
         * If the node has a parent and is enabled, the parent will be inspected as well.
         * @return {boolean} whether this node (and its parent) is enabled.
         * @see setEnabled
         */
        Node.prototype.isEnabled = function () {
            if (!this._isEnabled) {
                return false;
            }
            if (this.parent) {
                return this.parent.isEnabled();
            }
            return true;
        };
        /**
         * Set the enabled state of this node.
         * @param {boolean} value - the new enabled state
         * @see isEnabled
         */
        Node.prototype.setEnabled = function (value) {
            this._isEnabled = value;
        };
        /**
         * Is this node a descendant of the given node.
         * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
         * @param {BABYLON.Node} ancestor - The parent node to inspect
         * @see parent
         */
        Node.prototype.isDescendantOf = function (ancestor) {
            if (this.parent) {
                if (this.parent === ancestor) {
                    return true;
                }
                return this.parent.isDescendantOf(ancestor);
            }
            return false;
        };
        /**
         * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
         * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
         * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
         * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
         */
        Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
            if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
            if (!this._children) {
                return;
            }
            for (var index = 0; index < this._children.length; index++) {
                var item = this._children[index];
                if (!predicate || predicate(item)) {
                    results.push(item);
                }
                if (!directDescendantsOnly) {
                    item._getDescendants(results, false, predicate);
                }
            }
        };
        /**
         * Will return all nodes that have this node as ascendant.
         * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
         * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
         * @return {BABYLON.Node[]} all children nodes of all types.
         */
        Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
            var results = [];
            this._getDescendants(results, directDescendantsOnly, predicate);
            return results;
        };
        /**
         * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
         * @Deprecated, legacy support.
         * use getDecendants instead.
         */
        Node.prototype.getChildren = function (predicate) {
            return this.getDescendants(true, predicate);
        };
        /**
         * Get all child-meshes of this node.
         */
        Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
            var results = [];
            this._getDescendants(results, directDecendantsOnly, function (node) {
                return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
            });
            return results;
        };
        Node.prototype._setReady = function (state) {
            if (state === this._isReady) {
                return;
            }
            if (!state) {
                this._isReady = false;
                return;
            }
            this._isReady = true;
            if (this.onReady) {
                this.onReady(this);
            }
        };
        Node.prototype.getAnimationByName = function (name) {
            for (var i = 0; i < this.animations.length; i++) {
                var animation = this.animations[i];
                if (animation.name === name) {
                    return animation;
                }
            }
            return null;
        };
        Node.prototype.createAnimationRange = function (name, from, to) {
            // check name not already in use
            if (!this._ranges[name]) {
                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
                for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
                    if (this.animations[i]) {
                        this.animations[i].createRange(name, from, to);
                    }
                }
            }
        };
        Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
            if (deleteFrames === void 0) { deleteFrames = true; }
            for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
                if (this.animations[i]) {
                    this.animations[i].deleteRange(name, deleteFrames);
                }
            }
            this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
        };
        Node.prototype.getAnimationRange = function (name) {
            return this._ranges[name];
        };
        Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
            var range = this.getAnimationRange(name);
            if (!range) {
                return null;
            }
            this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
        };
        Node.prototype.serializeAnimationRanges = function () {
            var serializationRanges = [];
            for (var name in this._ranges) {
                var range = {};
                range.name = name;
                range.from = this._ranges[name].from;
                range.to = this._ranges[name].to;
                serializationRanges.push(range);
            }
            return serializationRanges;
        };
        Node.prototype.dispose = function () {
            this.parent = null;
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        Node.ParseAnimationRanges = function (node, parsedNode, scene) {
            if (parsedNode.ranges) {
                for (var index = 0; index < parsedNode.ranges.length; index++) {
                    var data = parsedNode.ranges[index];
                    node.createAnimationRange(data.name, data.from, data.to);
                }
            }
        };
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "name", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "id", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "uniqueId", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "state", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "metadata", void 0);
        return Node;
    }());
    BABYLON.Node = Node;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.node.js.map
 
var BABYLON;
(function (BABYLON) {
    var FilesInput = (function () {
        /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
        /// loading progress callback and optionnal addionnal logic to call in the rendering loop
        function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
            this._engine = p_engine;
            this._canvas = p_canvas;
            this._currentScene = p_scene;
            this._sceneLoadedCallback = p_sceneLoadedCallback;
            this._progressCallback = p_progressCallback;
            this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
            this._textureLoadingCallback = p_textureLoadingCallback;
            this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
        }
        FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
            var _this = this;
            if (p_elementToMonitor) {
                this._elementToMonitor = p_elementToMonitor;
                this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
                this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
                this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
            }
        };
        FilesInput.prototype.renderFunction = function () {
            if (this._additionnalRenderLoopLogicCallback) {
                this._additionnalRenderLoopLogicCallback();
            }
            if (this._currentScene) {
                if (this._textureLoadingCallback) {
                    var remaining = this._currentScene.getWaitingItemsCount();
                    if (remaining > 0) {
                        this._textureLoadingCallback(remaining);
                    }
                }
                this._currentScene.render();
            }
        };
        FilesInput.prototype.drag = function (e) {
            e.stopPropagation();
            e.preventDefault();
        };
        FilesInput.prototype.drop = function (eventDrop) {
            eventDrop.stopPropagation();
            eventDrop.preventDefault();
            this.loadFiles(eventDrop);
        };
        FilesInput.prototype.loadFiles = function (event) {
            if (this._startingProcessingFilesCallback)
                this._startingProcessingFilesCallback();
            // Handling data transfer via drag'n'drop
            if (event && event.dataTransfer && event.dataTransfer.files) {
                this._filesToLoad = event.dataTransfer.files;
            }
            // Handling files from input files
            if (event && event.target && event.target.files) {
                this._filesToLoad = event.target.files;
            }
            if (this._filesToLoad && this._filesToLoad.length > 0) {
                for (var i = 0; i < this._filesToLoad.length; i++) {
                    switch (this._filesToLoad[i].type) {
                        case "image/jpeg":
                        case "image/png":
                        case "image/bmp":
                            FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
                            break;
                        case "image/targa":
                        case "image/vnd.ms-dds":
                        case "audio/wav":
                        case "audio/x-wav":
                        case "audio/mp3":
                        case "audio/mpeg":
                        case "audio/mpeg3":
                        case "audio/x-mpeg-3":
                        case "audio/ogg":
                            FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
                            break;
                        default:
                            if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
                                FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
                            }
                            else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
                                this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
                                this._filesToLoad[i].name.indexOf(".obj") !== -1)
                                && this._filesToLoad[i].name.indexOf(".manifest") === -1
                                && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
                                && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
                                this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
                                this._sceneFileToLoad = this._filesToLoad[i];
                            }
                            break;
                    }
                }
                this.reload();
            }
        };
        FilesInput.prototype.reload = function () {
            var _this = this;
            var that = this;
            // If a ".babylon" file has been provided
            if (this._sceneFileToLoad) {
                if (this._currentScene) {
                    if (BABYLON.Tools.errorsCount > 0) {
                        BABYLON.Tools.ClearLogCache();
                        BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
                    }
                    this._engine.stopRenderLoop();
                    this._currentScene.dispose();
                }
                BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
                    that._currentScene = newScene;
                    // Wait for textures and shaders to be ready
                    that._currentScene.executeWhenReady(function () {
                        // Attach camera to canvas inputs
                        if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
                            that._currentScene.createDefaultCameraOrLight();
                        }
                        that._currentScene.activeCamera.attachControl(that._canvas);
                        if (that._sceneLoadedCallback) {
                            that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
                        }
                        that._engine.runRenderLoop(function () { that.renderFunction(); });
                    });
                }, function (progress) {
                    if (_this._progressCallback) {
                        _this._progressCallback(progress);
                    }
                });
            }
            else {
                BABYLON.Tools.Error("Please provide a valid .babylon file.");
            }
        };
        FilesInput.FilesTextures = new Array();
        FilesInput.FilesToLoad = new Array();
        return FilesInput;
    }());
    BABYLON.FilesInput = FilesInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.filesInput.js.map
 
var BABYLON;
(function (BABYLON) {
    var IntersectionInfo = (function () {
        function IntersectionInfo(bu, bv, distance) {
            this.bu = bu;
            this.bv = bv;
            this.distance = distance;
            this.faceId = 0;
            this.subMeshId = 0;
        }
        return IntersectionInfo;
    }());
    BABYLON.IntersectionInfo = IntersectionInfo;
    var PickingInfo = (function () {
        function PickingInfo() {
            this.hit = false;
            this.distance = 0;
            this.pickedPoint = null;
            this.pickedMesh = null;
            this.bu = 0;
            this.bv = 0;
            this.faceId = -1;
            this.subMeshId = 0;
            this.pickedSprite = null;
        }
        // Methods
        PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
            if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
            if (useVerticesNormals === void 0) { useVerticesNormals = true; }
            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                return null;
            }
            var indices = this.pickedMesh.getIndices();
            var result;
            if (useVerticesNormals) {
                var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
                var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
                var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
                normal0 = normal0.scale(this.bu);
                normal1 = normal1.scale(this.bv);
                normal2 = normal2.scale(1.0 - this.bu - this.bv);
                result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
            }
            else {
                var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
                var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
                var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
                var p1p2 = vertex1.subtract(vertex2);
                var p3p2 = vertex3.subtract(vertex2);
                result = BABYLON.Vector3.Cross(p1p2, p3p2);
            }
            if (useWorldCoordinates) {
                result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
            }
            return BABYLON.Vector3.Normalize(result);
        };
        PickingInfo.prototype.getTextureCoordinates = function () {
            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                return null;
            }
            var indices = this.pickedMesh.getIndices();
            var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
            var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
            var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
            uv0 = uv0.scale(1.0 - this.bu - this.bv);
            uv1 = uv1.scale(this.bu);
            uv2 = uv2.scale(this.bv);
            return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
        };
        return PickingInfo;
    }());
    BABYLON.PickingInfo = PickingInfo;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.pickingInfo.js.map
 
var BABYLON;
(function (BABYLON) {
    var BoundingSphere = (function () {
        function BoundingSphere(minimum, maximum) {
            this.minimum = minimum;
            this.maximum = maximum;
            this._tempRadiusVector = BABYLON.Vector3.Zero();
            var distance = BABYLON.Vector3.Distance(minimum, maximum);
            this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
            this.radius = distance * 0.5;
            this.centerWorld = BABYLON.Vector3.Zero();
            this._update(BABYLON.Matrix.Identity());
        }
        // Methods
        BoundingSphere.prototype._update = function (world) {
            BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
            this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
        };
        BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
            for (var i = 0; i < 6; i++) {
                if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
                    return false;
            }
            return true;
        };
        BoundingSphere.prototype.intersectsPoint = function (point) {
            var x = this.centerWorld.x - point.x;
            var y = this.centerWorld.y - point.y;
            var z = this.centerWorld.z - point.z;
            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
            if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
                return false;
            return true;
        };
        // Statics
        BoundingSphere.Intersects = function (sphere0, sphere1) {
            var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
            var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
            var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
            if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
                return false;
            return true;
        };
        return BoundingSphere;
    }());
    BABYLON.BoundingSphere = BoundingSphere;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boundingSphere.js.map
 
var BABYLON;
(function (BABYLON) {
    var BoundingBox = (function () {
        function BoundingBox(minimum, maximum) {
            this.minimum = minimum;
            this.maximum = maximum;
            this.vectors = new Array();
            this.vectorsWorld = new Array();
            // Bounding vectors
            this.vectors.push(this.minimum.clone());
            this.vectors.push(this.maximum.clone());
            this.vectors.push(this.minimum.clone());
            this.vectors[2].x = this.maximum.x;
            this.vectors.push(this.minimum.clone());
            this.vectors[3].y = this.maximum.y;
            this.vectors.push(this.minimum.clone());
            this.vectors[4].z = this.maximum.z;
            this.vectors.push(this.maximum.clone());
            this.vectors[5].z = this.minimum.z;
            this.vectors.push(this.maximum.clone());
            this.vectors[6].x = this.minimum.x;
            this.vectors.push(this.maximum.clone());
            this.vectors[7].y = this.minimum.y;
            // OBB
            this.center = this.maximum.add(this.minimum).scale(0.5);
            this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
            this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
            // World
            for (var index = 0; index < this.vectors.length; index++) {
                this.vectorsWorld[index] = BABYLON.Vector3.Zero();
            }
            this.minimumWorld = BABYLON.Vector3.Zero();
            this.maximumWorld = BABYLON.Vector3.Zero();
            this._update(BABYLON.Matrix.Identity());
        }
        // Methods
        BoundingBox.prototype.getWorldMatrix = function () {
            return this._worldMatrix;
        };
        BoundingBox.prototype.setWorldMatrix = function (matrix) {
            this._worldMatrix.copyFrom(matrix);
            return this;
        };
        BoundingBox.prototype._update = function (world) {
            BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
            BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
            for (var index = 0; index < this.vectors.length; index++) {
                var v = this.vectorsWorld[index];
                BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
                if (v.x < this.minimumWorld.x)
                    this.minimumWorld.x = v.x;
                if (v.y < this.minimumWorld.y)
                    this.minimumWorld.y = v.y;
                if (v.z < this.minimumWorld.z)
                    this.minimumWorld.z = v.z;
                if (v.x > this.maximumWorld.x)
                    this.maximumWorld.x = v.x;
                if (v.y > this.maximumWorld.y)
                    this.maximumWorld.y = v.y;
                if (v.z > this.maximumWorld.z)
                    this.maximumWorld.z = v.z;
            }
            // OBB
            this.maximumWorld.addToRef(this.minimumWorld, this.center);
            this.center.scaleInPlace(0.5);
            BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
            BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
            BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
            this._worldMatrix = world;
        };
        BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
            return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
        };
        BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
        };
        BoundingBox.prototype.intersectsPoint = function (point) {
            var delta = -BABYLON.Epsilon;
            if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
                return false;
            if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
                return false;
            if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
                return false;
            return true;
        };
        BoundingBox.prototype.intersectsSphere = function (sphere) {
            return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
        };
        BoundingBox.prototype.intersectsMinMax = function (min, max) {
            if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
                return false;
            if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
                return false;
            if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
                return false;
            return true;
        };
        // Statics
        BoundingBox.Intersects = function (box0, box1) {
            if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
                return false;
            if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
                return false;
            if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
                return false;
            return true;
        };
        BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
            var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
            var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
            return (num <= (sphereRadius * sphereRadius));
        };
        BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
            for (var p = 0; p < 6; p++) {
                for (var i = 0; i < 8; i++) {
                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
                        return false;
                    }
                }
            }
            return true;
        };
        BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
            for (var p = 0; p < 6; p++) {
                var inCount = 8;
                for (var i = 0; i < 8; i++) {
                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
                        --inCount;
                    }
                    else {
                        break;
                    }
                }
                if (inCount === 0)
                    return false;
            }
            return true;
        };
        return BoundingBox;
    }());
    BABYLON.BoundingBox = BoundingBox;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boundingBox.js.map
 
var BABYLON;
(function (BABYLON) {
    var computeBoxExtents = function (axis, box) {
        var p = BABYLON.Vector3.Dot(box.center, axis);
        var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
        var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
        var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
        var r = r0 + r1 + r2;
        return {
            min: p - r,
            max: p + r
        };
    };
    var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
    var axisOverlap = function (axis, box0, box1) {
        var result0 = computeBoxExtents(axis, box0);
        var result1 = computeBoxExtents(axis, box1);
        return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
    };
    var BoundingInfo = (function () {
        function BoundingInfo(minimum, maximum) {
            this.minimum = minimum;
            this.maximum = maximum;
            this._isLocked = false;
            this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
            this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
        }
        Object.defineProperty(BoundingInfo.prototype, "isLocked", {
            get: function () {
                return this._isLocked;
            },
            set: function (value) {
                this._isLocked = value;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        BoundingInfo.prototype.update = function (world) {
            if (this._isLocked) {
                return;
            }
            this.boundingBox._update(world);
            this.boundingSphere._update(world);
        };
        BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
            if (!this.boundingSphere.isInFrustum(frustumPlanes))
                return false;
            return this.boundingBox.isInFrustum(frustumPlanes);
        };
        BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
        };
        BoundingInfo.prototype._checkCollision = function (collider) {
            return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
        };
        BoundingInfo.prototype.intersectsPoint = function (point) {
            if (!this.boundingSphere.centerWorld) {
                return false;
            }
            if (!this.boundingSphere.intersectsPoint(point)) {
                return false;
            }
            if (!this.boundingBox.intersectsPoint(point)) {
                return false;
            }
            return true;
        };
        BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
            if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
                return false;
            }
            if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
                return false;
            }
            if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
                return false;
            }
            if (!precise) {
                return true;
            }
            var box0 = this.boundingBox;
            var box1 = boundingInfo.boundingBox;
            if (!axisOverlap(box0.directions[0], box0, box1))
                return false;
            if (!axisOverlap(box0.directions[1], box0, box1))
                return false;
            if (!axisOverlap(box0.directions[2], box0, box1))
                return false;
            if (!axisOverlap(box1.directions[0], box0, box1))
                return false;
            if (!axisOverlap(box1.directions[1], box0, box1))
                return false;
            if (!axisOverlap(box1.directions[2], box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
                return false;
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
                return false;
            return true;
        };
        return BoundingInfo;
    }());
    BABYLON.BoundingInfo = BoundingInfo;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boundingInfo.js.map
 
var BABYLON;
(function (BABYLON) {
    var Ray = (function () {
        function Ray(origin, direction, length) {
            if (length === void 0) { length = Number.MAX_VALUE; }
            this.origin = origin;
            this.direction = direction;
            this.length = length;
            this._show = false;
        }
        // Methods
        Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
            var d = 0.0;
            var maxValue = Number.MAX_VALUE;
            var inv;
            var min;
            var max;
            var temp;
            if (Math.abs(this.direction.x) < 0.0000001) {
                if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
                    return false;
                }
            }
            else {
                inv = 1.0 / this.direction.x;
                min = (minimum.x - this.origin.x) * inv;
                max = (maximum.x - this.origin.x) * inv;
                if (max === -Infinity) {
                    max = Infinity;
                }
                if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                d = Math.max(min, d);
                maxValue = Math.min(max, maxValue);
                if (d > maxValue) {
                    return false;
                }
            }
            if (Math.abs(this.direction.y) < 0.0000001) {
                if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
                    return false;
                }
            }
            else {
                inv = 1.0 / this.direction.y;
                min = (minimum.y - this.origin.y) * inv;
                max = (maximum.y - this.origin.y) * inv;
                if (max === -Infinity) {
                    max = Infinity;
                }
                if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                d = Math.max(min, d);
                maxValue = Math.min(max, maxValue);
                if (d > maxValue) {
                    return false;
                }
            }
            if (Math.abs(this.direction.z) < 0.0000001) {
                if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
                    return false;
                }
            }
            else {
                inv = 1.0 / this.direction.z;
                min = (minimum.z - this.origin.z) * inv;
                max = (maximum.z - this.origin.z) * inv;
                if (max === -Infinity) {
                    max = Infinity;
                }
                if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                d = Math.max(min, d);
                maxValue = Math.min(max, maxValue);
                if (d > maxValue) {
                    return false;
                }
            }
            return true;
        };
        Ray.prototype.intersectsBox = function (box) {
            return this.intersectsBoxMinMax(box.minimum, box.maximum);
        };
        Ray.prototype.intersectsSphere = function (sphere) {
            var x = sphere.center.x - this.origin.x;
            var y = sphere.center.y - this.origin.y;
            var z = sphere.center.z - this.origin.z;
            var pyth = (x * x) + (y * y) + (z * z);
            var rr = sphere.radius * sphere.radius;
            if (pyth <= rr) {
                return true;
            }
            var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
            if (dot < 0.0) {
                return false;
            }
            var temp = pyth - (dot * dot);
            return temp <= rr;
        };
        Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
            if (!this._edge1) {
                this._edge1 = BABYLON.Vector3.Zero();
                this._edge2 = BABYLON.Vector3.Zero();
                this._pvec = BABYLON.Vector3.Zero();
                this._tvec = BABYLON.Vector3.Zero();
                this._qvec = BABYLON.Vector3.Zero();
            }
            vertex1.subtractToRef(vertex0, this._edge1);
            vertex2.subtractToRef(vertex0, this._edge2);
            BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
            var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
            if (det === 0) {
                return null;
            }
            var invdet = 1 / det;
            this.origin.subtractToRef(vertex0, this._tvec);
            var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
            if (bu < 0 || bu > 1.0) {
                return null;
            }
            BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
            var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
            if (bv < 0 || bu + bv > 1.0) {
                return null;
            }
            //check if the distance is longer than the predefined length.
            var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
            if (distance > this.length) {
                return null;
            }
            return new BABYLON.IntersectionInfo(bu, bv, distance);
        };
        Ray.prototype.intersectsPlane = function (plane) {
            var distance;
            var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
            if (Math.abs(result1) < 9.99999997475243E-07) {
                return null;
            }
            else {
                var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
                distance = (-plane.d - result2) / result1;
                if (distance < 0.0) {
                    if (distance < -9.99999997475243E-07) {
                        return null;
                    }
                    else {
                        return 0;
                    }
                }
                return distance;
            }
        };
        Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
            var tm = BABYLON.Tmp.Matrix[0];
            mesh.getWorldMatrix().invertToRef(tm);
            if (this._tmpRay) {
                Ray.TransformToRef(this, tm, this._tmpRay);
            }
            else {
                this._tmpRay = Ray.Transform(this, tm);
            }
            return mesh.intersects(this._tmpRay, fastCheck);
        };
        Ray.prototype.show = function (scene, color) {
            if (!this._show) {
                this._renderFunction = this._render.bind(this);
                this._show = true;
                this._scene = scene;
                this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
                this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
                this._scene.registerBeforeRender(this._renderFunction);
            }
            if (color) {
                this._renderLine.color.copyFrom(color);
            }
        };
        Ray.prototype.hide = function () {
            if (this._show) {
                this._show = false;
                this._scene.unregisterBeforeRender(this._renderFunction);
            }
            if (this._renderLine) {
                this._renderLine.dispose();
                this._renderLine = null;
                this._renderPoints = null;
            }
        };
        Ray.prototype._render = function () {
            var point = this._renderPoints[1];
            point.copyFrom(this.direction);
            point.scaleInPlace(this.length);
            point.addInPlace(this.origin);
            BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
        };
        /**
         * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
         * @param sega the first point of the segment to test the intersection against
         * @param segb the second point of the segment to test the intersection against
         * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
         * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
         */
        Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
            var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
            var u = segb.subtract(sega);
            var v = rsegb.subtract(this.origin);
            var w = sega.subtract(this.origin);
            var a = BABYLON.Vector3.Dot(u, u); // always >= 0
            var b = BABYLON.Vector3.Dot(u, v);
            var c = BABYLON.Vector3.Dot(v, v); // always >= 0
            var d = BABYLON.Vector3.Dot(u, w);
            var e = BABYLON.Vector3.Dot(v, w);
            var D = a * c - b * b; // always >= 0
            var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
            var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
            // compute the line parameters of the two closest points
            if (D < Ray.smallnum) {
                sN = 0.0; // force using point P0 on segment S1
                sD = 1.0; // to prevent possible division by 0.0 later
                tN = e;
                tD = c;
            }
            else {
                sN = (b * e - c * d);
                tN = (a * e - b * d);
                if (sN < 0.0) {
                    sN = 0.0;
                    tN = e;
                    tD = c;
                }
                else if (sN > sD) {
                    sN = sD;
                    tN = e + b;
                    tD = c;
                }
            }
            if (tN < 0.0) {
                tN = 0.0;
                // recompute sc for this edge
                if (-d < 0.0) {
                    sN = 0.0;
                }
                else if (-d > a)
                    sN = sD;
                else {
                    sN = -d;
                    sD = a;
                }
            }
            else if (tN > tD) {
                tN = tD;
                // recompute sc for this edge
                if ((-d + b) < 0.0) {
                    sN = 0;
                }
                else if ((-d + b) > a) {
                    sN = sD;
                }
                else {
                    sN = (-d + b);
                    sD = a;
                }
            }
            // finally do the division to get sc and tc
            sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
            tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
            // get the difference of the two closest points
            var qtc = v.multiplyByFloats(tc, tc, tc);
            var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
            var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
            if (isIntersected) {
                return qtc.length();
            }
            return -1;
        };
        // Statics
        Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
            var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
            var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
            var direction = end.subtract(start);
            direction.normalize();
            return new Ray(start, direction);
        };
        /**
        * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
        * transformed to the given world matrix.
        * @param origin The origin point
        * @param end The end point
        * @param world a matrix to transform the ray to. Default is the identity matrix.
        */
        Ray.CreateNewFromTo = function (origin, end, world) {
            if (world === void 0) { world = BABYLON.Matrix.Identity(); }
            var direction = end.subtract(origin);
            var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
            direction.normalize();
            return Ray.Transform(new Ray(origin, direction, length), world);
        };
        Ray.Transform = function (ray, matrix) {
            var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
            var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
            newDirection.normalize();
            return new Ray(newOrigin, newDirection, ray.length);
        };
        Ray.TransformToRef = function (ray, matrix, result) {
            BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
            BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
            ray.direction.normalize();
        };
        Ray.smallnum = 0.00000001;
        Ray.rayl = 10e8;
        return Ray;
    }());
    BABYLON.Ray = Ray;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.ray.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var AbstractMesh = (function (_super) {
        __extends(AbstractMesh, _super);
        // Constructor
        function AbstractMesh(name, scene) {
            var _this = this;
            _super.call(this, name, scene);
            // Events
            /**
            * An event triggered when this mesh collides with another one
            * @type {BABYLON.Observable}
            */
            this.onCollideObservable = new BABYLON.Observable();
            /**
            * An event triggered when the collision's position changes
            * @type {BABYLON.Observable}
            */
            this.onCollisionPositionChangeObservable = new BABYLON.Observable();
            /**
            * An event triggered after the world matrix is updated
            * @type {BABYLON.Observable}
            */
            this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
            // Properties
            this.definedFacingForward = true; // orientation for POV movement & rotation
            this.position = new BABYLON.Vector3(0, 0, 0);
            this._rotation = new BABYLON.Vector3(0, 0, 0);
            this._scaling = new BABYLON.Vector3(1, 1, 1);
            this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
            this.visibility = 1.0;
            this.alphaIndex = Number.MAX_VALUE;
            this.infiniteDistance = false;
            this.isVisible = true;
            this.isPickable = true;
            this.showBoundingBox = false;
            this.showSubMeshesBoundingBox = false;
            this.isBlocker = false;
            this.renderingGroupId = 0;
            this.receiveShadows = false;
            this.renderOutline = false;
            this.outlineColor = BABYLON.Color3.Red();
            this.outlineWidth = 0.02;
            this.renderOverlay = false;
            this.overlayColor = BABYLON.Color3.Red();
            this.overlayAlpha = 0.5;
            this.hasVertexAlpha = false;
            this.useVertexColors = true;
            this.applyFog = true;
            this.computeBonesUsingShaders = true;
            this.scalingDeterminant = 1;
            this.numBoneInfluencers = 4;
            this.useOctreeForRenderingSelection = true;
            this.useOctreeForPicking = true;
            this.useOctreeForCollisions = true;
            this.layerMask = 0x0FFFFFFF;
            this.alwaysSelectAsActiveMesh = false;
            // Collisions
            this._checkCollisions = false;
            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
            this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
            this._collider = new BABYLON.Collider();
            this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
            this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
            this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
            // Edges
            this.edgesWidth = 1;
            this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
            // Cache
            this._localWorld = BABYLON.Matrix.Zero();
            this._worldMatrix = BABYLON.Matrix.Zero();
            this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
            this._absolutePosition = BABYLON.Vector3.Zero();
            this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
            this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
            this._isDirty = false;
            this._pivotMatrix = BABYLON.Matrix.Identity();
            this._isDisposed = false;
            this._renderId = 0;
            this._intersectionsInProgress = new Array();
            this._isWorldMatrixFrozen = false;
            this._unIndexed = false;
            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
                if (collidedMesh === void 0) { collidedMesh = null; }
                //TODO move this to the collision coordinator!
                if (_this.getScene().workerCollisions)
                    newPosition.multiplyInPlace(_this._collider.radius);
                newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
                if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
                    _this.position.addInPlace(_this._diffPositionForCollisions);
                }
                if (collidedMesh) {
                    _this.onCollideObservable.notifyObservers(collidedMesh);
                }
                _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
            };
            scene.addMesh(this);
        }
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
            get: function () {
                return AbstractMesh._BILLBOARDMODE_NONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
            get: function () {
                return AbstractMesh._BILLBOARDMODE_X;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
            get: function () {
                return AbstractMesh._BILLBOARDMODE_Y;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
            get: function () {
                return AbstractMesh._BILLBOARDMODE_Z;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
            get: function () {
                return AbstractMesh._BILLBOARDMODE_ALL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "onCollide", {
            set: function (callback) {
                if (this._onCollideObserver) {
                    this.onCollideObservable.remove(this._onCollideObserver);
                }
                this._onCollideObserver = this.onCollideObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
            set: function (callback) {
                if (this._onCollisionPositionChangeObserver) {
                    this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
                }
                this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "skeleton", {
            get: function () {
                return this._skeleton;
            },
            set: function (value) {
                if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
                    this._skeleton._unregisterMeshWithPoseMatrix(this);
                }
                if (value && value.needInitialSkinMatrix) {
                    value._registerMeshWithPoseMatrix(this);
                }
                this._skeleton = value;
                if (!this._skeleton) {
                    this._bonesTransformMatrices = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         */
        AbstractMesh.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
            ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
            if (this._skeleton) {
                ret += ", skeleton: " + this._skeleton.name;
            }
            if (fullDetails) {
                ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
                ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
            }
            return ret;
        };
        Object.defineProperty(AbstractMesh.prototype, "rotation", {
            /**
             * Getting the rotation object.
             * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
             */
            get: function () {
                return this._rotation;
            },
            set: function (newRotation) {
                this._rotation = newRotation;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "scaling", {
            get: function () {
                return this._scaling;
            },
            set: function (newScaling) {
                this._scaling = newScaling;
                if (this.physicsImpostor) {
                    this.physicsImpostor.forceUpdate();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
            get: function () {
                return this._rotationQuaternion;
            },
            set: function (quaternion) {
                this._rotationQuaternion = quaternion;
                //reset the rotation vector. 
                if (quaternion && this.rotation.length()) {
                    this.rotation.copyFromFloats(0, 0, 0);
                }
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
            this._poseMatrix.copyFrom(matrix);
        };
        AbstractMesh.prototype.getPoseMatrix = function () {
            return this._poseMatrix;
        };
        AbstractMesh.prototype.disableEdgesRendering = function () {
            if (this._edgesRenderer !== undefined) {
                this._edgesRenderer.dispose();
                this._edgesRenderer = undefined;
            }
        };
        AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
            if (epsilon === void 0) { epsilon = 0.95; }
            if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
            this.disableEdgesRendering();
            this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
        };
        Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        AbstractMesh.prototype.getLOD = function (camera) {
            return this;
        };
        AbstractMesh.prototype.getTotalVertices = function () {
            return 0;
        };
        AbstractMesh.prototype.getIndices = function () {
            return null;
        };
        AbstractMesh.prototype.getVerticesData = function (kind) {
            return null;
        };
        AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
            return false;
        };
        AbstractMesh.prototype.getBoundingInfo = function () {
            if (this._masterMesh) {
                return this._masterMesh.getBoundingInfo();
            }
            if (!this._boundingInfo) {
                this._updateBoundingInfo();
            }
            return this._boundingInfo;
        };
        AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
            this._boundingInfo = boundingInfo;
        };
        Object.defineProperty(AbstractMesh.prototype, "useBones", {
            get: function () {
                return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
            },
            enumerable: true,
            configurable: true
        });
        AbstractMesh.prototype._preActivate = function () {
        };
        AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
        };
        AbstractMesh.prototype._activate = function (renderId) {
            this._renderId = renderId;
        };
        AbstractMesh.prototype.getWorldMatrix = function () {
            if (this._masterMesh) {
                return this._masterMesh.getWorldMatrix();
            }
            if (this._currentRenderId !== this.getScene().getRenderId()) {
                this.computeWorldMatrix();
            }
            return this._worldMatrix;
        };
        Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
            get: function () {
                return this._worldMatrix;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
            get: function () {
                return this._absolutePosition;
            },
            enumerable: true,
            configurable: true
        });
        AbstractMesh.prototype.freezeWorldMatrix = function () {
            this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
            this.computeWorldMatrix(true);
            this._isWorldMatrixFrozen = true;
        };
        AbstractMesh.prototype.unfreezeWorldMatrix = function () {
            this._isWorldMatrixFrozen = false;
            this.computeWorldMatrix(true);
        };
        Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
            get: function () {
                return this._isWorldMatrixFrozen;
            },
            enumerable: true,
            configurable: true
        });
        AbstractMesh.prototype.rotate = function (axis, amount, space) {
            axis.normalize();
            if (!this.rotationQuaternion) {
                this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
                this.rotation = BABYLON.Vector3.Zero();
            }
            var rotationQuaternion;
            if (!space || space === BABYLON.Space.LOCAL) {
                rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
                this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
            }
            else {
                if (this.parent) {
                    var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
                    invertParentWorldMatrix.invert();
                    axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
                }
                rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
                rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
            }
        };
        AbstractMesh.prototype.translate = function (axis, distance, space) {
            var displacementVector = axis.scale(distance);
            if (!space || space === BABYLON.Space.LOCAL) {
                var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
                this.setPositionWithLocalVector(tempV3);
            }
            else {
                this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
            }
        };
        AbstractMesh.prototype.getAbsolutePosition = function () {
            this.computeWorldMatrix();
            return this._absolutePosition;
        };
        AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
            if (!absolutePosition) {
                return;
            }
            var absolutePositionX;
            var absolutePositionY;
            var absolutePositionZ;
            if (absolutePosition.x === undefined) {
                if (arguments.length < 3) {
                    return;
                }
                absolutePositionX = arguments[0];
                absolutePositionY = arguments[1];
                absolutePositionZ = arguments[2];
            }
            else {
                absolutePositionX = absolutePosition.x;
                absolutePositionY = absolutePosition.y;
                absolutePositionZ = absolutePosition.z;
            }
            if (this.parent) {
                var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
                invertParentWorldMatrix.invert();
                var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
                this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
            }
            else {
                this.position.x = absolutePositionX;
                this.position.y = absolutePositionY;
                this.position.z = absolutePositionZ;
            }
        };
        // ================================== Point of View Movement =================================
        /**
         * Perform relative position change from the point of view of behind the front of the mesh.
         * This is performed taking into account the meshes current rotation, so you do not have to care.
         * Supports definition of mesh facing forward or backward.
         * @param {number} amountRight
         * @param {number} amountUp
         * @param {number} amountForward
         */
        AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
            this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
        };
        /**
         * Calculate relative position change from the point of view of behind the front of the mesh.
         * This is performed taking into account the meshes current rotation, so you do not have to care.
         * Supports definition of mesh facing forward or backward.
         * @param {number} amountRight
         * @param {number} amountUp
         * @param {number} amountForward
         */
        AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
            var rotMatrix = new BABYLON.Matrix();
            var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
            rotQuaternion.toRotationMatrix(rotMatrix);
            var translationDelta = BABYLON.Vector3.Zero();
            var defForwardMult = this.definedFacingForward ? -1 : 1;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
            return translationDelta;
        };
        // ================================== Point of View Rotation =================================
        /**
         * Perform relative rotation change from the point of view of behind the front of the mesh.
         * Supports definition of mesh facing forward or backward.
         * @param {number} flipBack
         * @param {number} twirlClockwise
         * @param {number} tiltRight
         */
        AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
            this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
        };
        /**
         * Calculate relative rotation change from the point of view of behind the front of the mesh.
         * Supports definition of mesh facing forward or backward.
         * @param {number} flipBack
         * @param {number} twirlClockwise
         * @param {number} tiltRight
         */
        AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
            var defForwardMult = this.definedFacingForward ? 1 : -1;
            return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
        };
        AbstractMesh.prototype.setPivotMatrix = function (matrix) {
            this._pivotMatrix = matrix;
            this._cache.pivotMatrixUpdated = true;
        };
        AbstractMesh.prototype.getPivotMatrix = function () {
            return this._pivotMatrix;
        };
        AbstractMesh.prototype._isSynchronized = function () {
            if (this._isDirty) {
                return false;
            }
            if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
                return false;
            if (this._cache.pivotMatrixUpdated) {
                return false;
            }
            if (this.infiniteDistance) {
                return false;
            }
            if (!this._cache.position.equals(this.position))
                return false;
            if (this.rotationQuaternion) {
                if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
                    return false;
            }
            if (!this._cache.rotation.equals(this.rotation))
                return false;
            if (!this._cache.scaling.equals(this.scaling))
                return false;
            return true;
        };
        AbstractMesh.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.localMatrixUpdated = false;
            this._cache.position = BABYLON.Vector3.Zero();
            this._cache.scaling = BABYLON.Vector3.Zero();
            this._cache.rotation = BABYLON.Vector3.Zero();
            this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
            this._cache.billboardMode = -1;
        };
        AbstractMesh.prototype.markAsDirty = function (property) {
            if (property === "rotation") {
                this.rotationQuaternion = null;
            }
            this._currentRenderId = Number.MAX_VALUE;
            this._isDirty = true;
        };
        AbstractMesh.prototype._updateBoundingInfo = function () {
            this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
            this._boundingInfo.update(this.worldMatrixFromCache);
            this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
        };
        AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
            if (!this.subMeshes) {
                return;
            }
            for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
                var subMesh = this.subMeshes[subIndex];
                if (!subMesh.IsGlobal) {
                    subMesh.updateBoundingInfo(matrix);
                }
            }
        };
        AbstractMesh.prototype.computeWorldMatrix = function (force) {
            if (this._isWorldMatrixFrozen) {
                return this._worldMatrix;
            }
            if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
                this._currentRenderId = this.getScene().getRenderId();
                return this._worldMatrix;
            }
            this._cache.position.copyFrom(this.position);
            this._cache.scaling.copyFrom(this.scaling);
            this._cache.pivotMatrixUpdated = false;
            this._cache.billboardMode = this.billboardMode;
            this._currentRenderId = this.getScene().getRenderId();
            this._isDirty = false;
            // Scaling
            BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
            // Rotation
            //rotate, if quaternion is set and rotation was used
            if (this.rotationQuaternion) {
                var len = this.rotation.length();
                if (len) {
                    this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
                    this.rotation.copyFromFloats(0, 0, 0);
                }
            }
            if (this.rotationQuaternion) {
                this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
                this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
            }
            else {
                BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
                this._cache.rotation.copyFrom(this.rotation);
            }
            // Translation
            if (this.infiniteDistance && !this.parent) {
                var camera = this.getScene().activeCamera;
                if (camera) {
                    var cameraWorldMatrix = camera.getWorldMatrix();
                    var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
                    BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
                }
            }
            else {
                BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
            }
            // Composing transformations
            this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
            BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
            // Billboarding
            if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
                BABYLON.Tmp.Vector3[0].copyFrom(this.position);
                var localPosition = BABYLON.Tmp.Vector3[0];
                if (this.parent && this.parent.getWorldMatrix) {
                    this._markSyncedWithParent();
                    var parentMatrix;
                    if (this._meshToBoneReferal) {
                        this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
                        parentMatrix = BABYLON.Tmp.Matrix[6];
                    }
                    else {
                        parentMatrix = this.parent.getWorldMatrix();
                    }
                    BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
                    localPosition = BABYLON.Tmp.Vector3[1];
                }
                var zero = this.getScene().activeCamera.globalPosition.clone();
                if (this.parent && this.parent.position) {
                    localPosition.addInPlace(this.parent.position);
                    BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
                }
                if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
                    if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
                        zero.x = localPosition.x + BABYLON.Epsilon;
                    if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
                        zero.y = localPosition.y + BABYLON.Epsilon;
                    if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
                        zero.z = localPosition.z + BABYLON.Epsilon;
                }
                BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
                BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
                BABYLON.Tmp.Matrix[3].invert();
                BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
                this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
            }
            // Local world
            BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
            // Parent
            if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
                this._markSyncedWithParent();
                if (this._meshToBoneReferal) {
                    this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
                    BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
                }
                else {
                    this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
                }
            }
            else {
                this._worldMatrix.copyFrom(this._localWorld);
            }
            // Bounding info
            this._updateBoundingInfo();
            // Absolute position
            this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
            // Callbacks
            this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
            if (!this._poseMatrix) {
                this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
            }
            return this._worldMatrix;
        };
        /**
        * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
        * @param func: callback function to add
        */
        AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
            this.onAfterWorldMatrixUpdateObservable.add(func);
        };
        AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
            this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
        };
        AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
            this.computeWorldMatrix();
            this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
        };
        AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
            this.computeWorldMatrix();
            var invLocalWorldMatrix = this._localWorld.clone();
            invLocalWorldMatrix.invert();
            return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
        };
        AbstractMesh.prototype.locallyTranslate = function (vector3) {
            this.computeWorldMatrix(true);
            this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
        };
        AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
            /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
            /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
            /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
            /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
            /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
            /// <returns>Mesh oriented towards targetMesh</returns>
            if (yawCor === void 0) { yawCor = 0; }
            if (pitchCor === void 0) { pitchCor = 0; }
            if (rollCor === void 0) { rollCor = 0; }
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var dv = AbstractMesh._lookAtVectorCache;
            var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
            targetPoint.subtractToRef(pos, dv);
            var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
            var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
            var pitch = Math.atan2(dv.y, len);
            this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
            BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
        };
        AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
            this._meshToBoneReferal = affectedMesh;
            this.parent = bone;
            if (bone.getWorldMatrix().determinant() < 0) {
                this.scalingDeterminant *= -1;
            }
        };
        AbstractMesh.prototype.detachFromBone = function () {
            if (this.parent.getWorldMatrix().determinant() < 0) {
                this.scalingDeterminant *= -1;
            }
            this._meshToBoneReferal = null;
            this.parent = null;
        };
        AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
            return this._boundingInfo.isInFrustum(frustumPlanes);
        };
        AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
            ;
        };
        AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
            if (!this._boundingInfo || !mesh._boundingInfo) {
                return false;
            }
            return this._boundingInfo.intersects(mesh._boundingInfo, precise);
        };
        AbstractMesh.prototype.intersectsPoint = function (point) {
            if (!this._boundingInfo) {
                return false;
            }
            return this._boundingInfo.intersectsPoint(point);
        };
        // Physics
        /**
         *  @Deprecated. Use new PhysicsImpostor instead.
         * */
        AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
            //legacy support
            if (impostor.impostor) {
                options = impostor;
                impostor = impostor.impostor;
            }
            this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
            return this.physicsImpostor.physicsBody;
        };
        AbstractMesh.prototype.getPhysicsImpostor = function () {
            return this.physicsImpostor;
        };
        /**
         * @Deprecated. Use getPhysicsImpostor().getParam("mass");
         */
        AbstractMesh.prototype.getPhysicsMass = function () {
            return this.physicsImpostor.getParam("mass");
        };
        /**
         * @Deprecated. Use getPhysicsImpostor().getParam("friction");
         */
        AbstractMesh.prototype.getPhysicsFriction = function () {
            return this.physicsImpostor.getParam("friction");
        };
        /**
         * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
         */
        AbstractMesh.prototype.getPhysicsRestitution = function () {
            return this.physicsImpostor.getParam("restitution");
        };
        AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
            if (!camera) {
                camera = this.getScene().activeCamera;
            }
            return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
        };
        AbstractMesh.prototype.getDistanceToCamera = function (camera) {
            if (!camera) {
                camera = this.getScene().activeCamera;
            }
            return this.absolutePosition.subtract(camera.position).length();
        };
        AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
            if (!this.physicsImpostor) {
                return;
            }
            this.physicsImpostor.applyImpulse(force, contactPoint);
        };
        AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
            if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
                return;
            }
            this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
                mainPivot: pivot1,
                connectedPivot: pivot2,
                nativeParams: options
            });
        };
        /**
         * @Deprecated
         */
        AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
            BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
            this.updatePhysicsBody();
        };
        /**
         * @Deprecated
         * Calling this function is not needed anymore.
         * The physics engine takes care of transofmration automatically.
         */
        AbstractMesh.prototype.updatePhysicsBody = function () {
            //Unneeded
        };
        Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
            // Collisions
            get: function () {
                return this._checkCollisions;
            },
            set: function (collisionEnabled) {
                this._checkCollisions = collisionEnabled;
                if (this.getScene().workerCollisions) {
                    this.getScene().collisionCoordinator.onMeshUpdated(this);
                }
            },
            enumerable: true,
            configurable: true
        });
        AbstractMesh.prototype.moveWithCollisions = function (velocity) {
            var globalPosition = this.getAbsolutePosition();
            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
            this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
            this._collider.radius = this.ellipsoid;
            this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
        };
        // Submeshes octree
        /**
        * This function will create an octree to help select the right submeshes for rendering, picking and collisions
        * Please note that you must have a decent number of submeshes to get performance improvements when using octree
        */
        AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
            if (maxCapacity === void 0) { maxCapacity = 64; }
            if (maxDepth === void 0) { maxDepth = 2; }
            if (!this._submeshesOctree) {
                this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
            }
            this.computeWorldMatrix(true);
            // Update octree
            var bbox = this.getBoundingInfo().boundingBox;
            this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
            return this._submeshesOctree;
        };
        // Collisions
        AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
            this._generatePointsArray();
            // Transformation
            if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
                subMesh._lastColliderTransformMatrix = transformMatrix.clone();
                subMesh._lastColliderWorldVertices = [];
                subMesh._trianglePlanes = [];
                var start = subMesh.verticesStart;
                var end = (subMesh.verticesStart + subMesh.verticesCount);
                for (var i = start; i < end; i++) {
                    subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
                }
            }
            // Collide
            collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
            if (collider.collisionFound) {
                collider.collidedMesh = this;
            }
        };
        AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
            var subMeshes;
            var len;
            // Octrees
            if (this._submeshesOctree && this.useOctreeForCollisions) {
                var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
                var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
                len = intersections.length;
                subMeshes = intersections.data;
            }
            else {
                subMeshes = this.subMeshes;
                len = subMeshes.length;
            }
            for (var index = 0; index < len; index++) {
                var subMesh = subMeshes[index];
                // Bounding test
                if (len > 1 && !subMesh._checkCollision(collider))
                    continue;
                this._collideForSubMesh(subMesh, transformMatrix, collider);
            }
        };
        AbstractMesh.prototype._checkCollision = function (collider) {
            // Bounding box test
            if (!this._boundingInfo._checkCollision(collider))
                return;
            // Transformation matrix
            BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
            this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
            this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
        };
        // Picking
        AbstractMesh.prototype._generatePointsArray = function () {
            return false;
        };
        AbstractMesh.prototype.intersects = function (ray, fastCheck) {
            var pickingInfo = new BABYLON.PickingInfo();
            if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
                return pickingInfo;
            }
            if (!this._generatePointsArray()) {
                return pickingInfo;
            }
            var intersectInfo = null;
            // Octrees
            var subMeshes;
            var len;
            if (this._submeshesOctree && this.useOctreeForPicking) {
                var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
                var intersections = this._submeshesOctree.intersectsRay(worldRay);
                len = intersections.length;
                subMeshes = intersections.data;
            }
            else {
                subMeshes = this.subMeshes;
                len = subMeshes.length;
            }
            for (var index = 0; index < len; index++) {
                var subMesh = subMeshes[index];
                // Bounding test
                if (len > 1 && !subMesh.canIntersects(ray))
                    continue;
                var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
                if (currentIntersectInfo) {
                    if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
                        intersectInfo = currentIntersectInfo;
                        intersectInfo.subMeshId = index;
                        if (fastCheck) {
                            break;
                        }
                    }
                }
            }
            if (intersectInfo) {
                // Get picked point
                var world = this.getWorldMatrix();
                var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
                var direction = ray.direction.clone();
                direction = direction.scale(intersectInfo.distance);
                var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
                var pickedPoint = worldOrigin.add(worldDirection);
                // Return result
                pickingInfo.hit = true;
                pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
                pickingInfo.pickedPoint = pickedPoint;
                pickingInfo.pickedMesh = this;
                pickingInfo.bu = intersectInfo.bu;
                pickingInfo.bv = intersectInfo.bv;
                pickingInfo.faceId = intersectInfo.faceId;
                pickingInfo.subMeshId = intersectInfo.subMeshId;
                return pickingInfo;
            }
            return pickingInfo;
        };
        AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
            return null;
        };
        AbstractMesh.prototype.releaseSubMeshes = function () {
            if (this.subMeshes) {
                while (this.subMeshes.length) {
                    this.subMeshes[0].dispose();
                }
            }
            else {
                this.subMeshes = new Array();
            }
        };
        AbstractMesh.prototype.dispose = function (doNotRecurse) {
            var _this = this;
            var index;
            // Action manager
            if (this.actionManager) {
                this.actionManager.dispose();
                this.actionManager = null;
            }
            // Skeleton
            this.skeleton = null;
            // Animations
            this.getScene().stopAnimation(this);
            // Physics
            if (this.physicsImpostor) {
                this.physicsImpostor.dispose();
            }
            // Intersections in progress
            for (index = 0; index < this._intersectionsInProgress.length; index++) {
                var other = this._intersectionsInProgress[index];
                var pos = other._intersectionsInProgress.indexOf(this);
                other._intersectionsInProgress.splice(pos, 1);
            }
            this._intersectionsInProgress = [];
            // Lights
            var lights = this.getScene().lights;
            lights.forEach(function (light) {
                var meshIndex = light.includedOnlyMeshes.indexOf(_this);
                if (meshIndex !== -1) {
                    light.includedOnlyMeshes.splice(meshIndex, 1);
                }
                meshIndex = light.excludedMeshes.indexOf(_this);
                if (meshIndex !== -1) {
                    light.excludedMeshes.splice(meshIndex, 1);
                }
                // Shadow generators
                var generator = light.getShadowGenerator();
                if (generator) {
                    meshIndex = generator.getShadowMap().renderList.indexOf(_this);
                    if (meshIndex !== -1) {
                        generator.getShadowMap().renderList.splice(meshIndex, 1);
                    }
                }
            });
            // Edges
            if (this._edgesRenderer) {
                this._edgesRenderer.dispose();
                this._edgesRenderer = null;
            }
            // SubMeshes
            this.releaseSubMeshes();
            // Engine
            this.getScene().getEngine().unbindAllAttributes();
            // Remove from scene
            this.getScene().removeMesh(this);
            if (!doNotRecurse) {
                // Particles
                for (index = 0; index < this.getScene().particleSystems.length; index++) {
                    if (this.getScene().particleSystems[index].emitter === this) {
                        this.getScene().particleSystems[index].dispose();
                        index--;
                    }
                }
                // Children
                var objects = this.getDescendants(true);
                for (index = 0; index < objects.length; index++) {
                    objects[index].dispose();
                }
            }
            else {
                var childMeshes = this.getChildMeshes(true);
                for (index = 0; index < childMeshes.length; index++) {
                    var child = childMeshes[index];
                    child.parent = null;
                    child.computeWorldMatrix(true);
                }
            }
            this.onAfterWorldMatrixUpdateObservable.clear();
            this.onCollideObservable.clear();
            this.onCollisionPositionChangeObservable.clear();
            this._isDisposed = true;
            _super.prototype.dispose.call(this);
        };
        AbstractMesh.prototype.getDirection = function (localAxis) {
            var result = BABYLON.Vector3.Zero();
            this.getDirectionToRef(localAxis, result);
            return result;
        };
        AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
            BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
        };
        AbstractMesh.prototype.setPivotPoint = function (point, space) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (this.getScene().getRenderId() == 0) {
                this.computeWorldMatrix(true);
            }
            var wm = this.getWorldMatrix();
            if (space == BABYLON.Space.WORLD) {
                var tmat = BABYLON.Tmp.Matrix[0];
                wm.invertToRef(tmat);
                point = BABYLON.Vector3.TransformCoordinates(point, tmat);
            }
            BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
            this._pivotMatrix.m[12] = -point.x;
            this._pivotMatrix.m[13] = -point.y;
            this._pivotMatrix.m[14] = -point.z;
            this._cache.pivotMatrixUpdated = true;
        };
        AbstractMesh.prototype.getPivotPoint = function () {
            var point = BABYLON.Vector3.Zero();
            this.getPivotPointToRef(point);
            return point;
        };
        AbstractMesh.prototype.getPivotPointToRef = function (result) {
            result.x = -this._pivotMatrix.m[12];
            result.y = -this._pivotMatrix.m[13];
            result.z = -this._pivotMatrix.m[14];
        };
        AbstractMesh.prototype.getAbsolutePivotPoint = function () {
            var point = BABYLON.Vector3.Zero();
            this.getAbsolutePivotPointToRef(point);
            return point;
        };
        AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
            result.x = this._pivotMatrix.m[12];
            result.y = this._pivotMatrix.m[13];
            result.z = this._pivotMatrix.m[14];
            this.getPivotPointToRef(result);
            BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
        };
        // Statics
        AbstractMesh._BILLBOARDMODE_NONE = 0;
        AbstractMesh._BILLBOARDMODE_X = 1;
        AbstractMesh._BILLBOARDMODE_Y = 2;
        AbstractMesh._BILLBOARDMODE_Z = 4;
        AbstractMesh._BILLBOARDMODE_ALL = 7;
        AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
        AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
        return AbstractMesh;
    }(BABYLON.Node));
    BABYLON.AbstractMesh = AbstractMesh;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.abstractMesh.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Light = (function (_super) {
        __extends(Light, _super);
        function Light(name, scene) {
            _super.call(this, name, scene);
            this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
            this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
            this.intensity = 1.0;
            this.range = Number.MAX_VALUE;
            this.includeOnlyWithLayerMask = 0;
            this.includedOnlyMeshes = new Array();
            this.excludedMeshes = new Array();
            this.excludeWithLayerMask = 0;
            this.lightmapMode = 0;
            // PBR Properties.
            this.radius = 0.00001;
            this._excludedMeshesIds = new Array();
            this._includedOnlyMeshesIds = new Array();
            scene.addLight(this);
        }
        Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
            /**
             * If every light affecting the material is in this lightmapMode,
             * material.lightmapTexture adds or multiplies
             * (depends on material.useLightmapAsShadowmap)
             * after every other light calculations.
             */
            get: function () {
                return Light._LIGHTMAP_DEFAULT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
            /**
             * material.lightmapTexture as only diffuse lighting from this light
             * adds pnly specular lighting from this light
             * adds dynamic shadows
             */
            get: function () {
                return Light._LIGHTMAP_SPECULAR;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
            /**
             * material.lightmapTexture as only lighting
             * no light calculation from this light
             * only adds dynamic shadows from this light
             */
            get: function () {
                return Light._LIGHTMAP_SHADOWSONLY;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         */
        Light.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
            if (this.animations) {
                for (var i = 0; i < this.animations.length; i++) {
                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
                }
            }
            if (fullDetails) {
            }
            return ret;
        };
        Light.prototype.getShadowGenerator = function () {
            return this._shadowGenerator;
        };
        Light.prototype.getAbsolutePosition = function () {
            return BABYLON.Vector3.Zero();
        };
        Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
        };
        Light.prototype._getWorldMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        Light.prototype.canAffectMesh = function (mesh) {
            if (!mesh) {
                return true;
            }
            if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
                return false;
            }
            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
                return false;
            }
            if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
                return false;
            }
            if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
                return false;
            }
            return true;
        };
        Light.prototype.getWorldMatrix = function () {
            this._currentRenderId = this.getScene().getRenderId();
            var worldMatrix = this._getWorldMatrix();
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this._parentedWorldMatrix) {
                    this._parentedWorldMatrix = BABYLON.Matrix.Identity();
                }
                worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
                this._markSyncedWithParent();
                return this._parentedWorldMatrix;
            }
            return worldMatrix;
        };
        Light.prototype.dispose = function () {
            if (this._shadowGenerator) {
                this._shadowGenerator.dispose();
                this._shadowGenerator = null;
            }
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            this.getScene().removeLight(this);
            _super.prototype.dispose.call(this);
        };
        Light.prototype.getTypeID = function () {
            return 0;
        };
        Light.prototype.clone = function (name) {
            return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
        };
        Light.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            // Type
            serializationObject.type = this.getTypeID();
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            // Inclusion / exclusions
            if (this.excludedMeshes.length > 0) {
                serializationObject.excludedMeshesIds = [];
                this.excludedMeshes.forEach(function (mesh) {
                    serializationObject.excludedMeshesIds.push(mesh.id);
                });
            }
            if (this.includedOnlyMeshes.length > 0) {
                serializationObject.includedOnlyMeshesIds = [];
                this.includedOnlyMeshes.forEach(function (mesh) {
                    serializationObject.includedOnlyMeshesIds.push(mesh.id);
                });
            }
            // Animations  
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            serializationObject.ranges = this.serializeAnimationRanges();
            return serializationObject;
        };
        Light.GetConstructorFromName = function (type, name, scene) {
            switch (type) {
                case 0:
                    return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
                case 1:
                    return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
                case 2:
                    return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
                case 3:
                    return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
            }
        };
        Light.Parse = function (parsedLight, scene) {
            var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
            // Inclusion / exclusions
            if (parsedLight.excludedMeshesIds) {
                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
            }
            if (parsedLight.includedOnlyMeshesIds) {
                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
            }
            // Parent
            if (parsedLight.parentId) {
                light._waitingParentId = parsedLight.parentId;
            }
            // Animations
            if (parsedLight.animations) {
                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
                    var parsedAnimation = parsedLight.animations[animationIndex];
                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
            }
            if (parsedLight.autoAnimate) {
                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
            }
            return light;
        };
        //lightmapMode Consts
        Light._LIGHTMAP_DEFAULT = 0;
        Light._LIGHTMAP_SPECULAR = 1;
        Light._LIGHTMAP_SHADOWSONLY = 2;
        __decorate([
            BABYLON.serializeAsColor3()
        ], Light.prototype, "diffuse", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], Light.prototype, "specular", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "intensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "range", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "includeOnlyWithLayerMask", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "excludeWithLayerMask", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "lightmapMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "radius", void 0);
        return Light;
    }(BABYLON.Node));
    BABYLON.Light = Light;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.light.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var PointLight = (function (_super) {
        __extends(PointLight, _super);
        function PointLight(name, position, scene) {
            _super.call(this, name, scene);
            this.position = position;
        }
        PointLight.prototype.getAbsolutePosition = function () {
            return this.transformedPosition ? this.transformedPosition : this.position;
        };
        PointLight.prototype.computeTransformedPosition = function () {
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this.transformedPosition) {
                    this.transformedPosition = BABYLON.Vector3.Zero();
                }
                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
                return true;
            }
            return false;
        };
        PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
            if (this.parent && this.parent.getWorldMatrix) {
                this.computeTransformedPosition();
                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
                return;
            }
            effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
        };
        PointLight.prototype.needCube = function () {
            return true;
        };
        PointLight.prototype.supportsVSM = function () {
            return false;
        };
        PointLight.prototype.needRefreshPerFrame = function () {
            return false;
        };
        PointLight.prototype.getShadowDirection = function (faceIndex) {
            switch (faceIndex) {
                case 0:
                    return new BABYLON.Vector3(1, 0, 0);
                case 1:
                    return new BABYLON.Vector3(-1, 0, 0);
                case 2:
                    return new BABYLON.Vector3(0, -1, 0);
                case 3:
                    return new BABYLON.Vector3(0, 1, 0);
                case 4:
                    return new BABYLON.Vector3(0, 0, 1);
                case 5:
                    return new BABYLON.Vector3(0, 0, -1);
            }
            return BABYLON.Vector3.Zero();
        };
        PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            var activeCamera = this.getScene().activeCamera;
            BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
        };
        PointLight.prototype._getWorldMatrix = function () {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
            return this._worldMatrix;
        };
        PointLight.prototype.getTypeID = function () {
            return 0;
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], PointLight.prototype, "position", void 0);
        return PointLight;
    }(BABYLON.Light));
    BABYLON.PointLight = PointLight;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.pointLight.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var SpotLight = (function (_super) {
        __extends(SpotLight, _super);
        function SpotLight(name, position, direction, angle, exponent, scene) {
            _super.call(this, name, scene);
            this.position = position;
            this.direction = direction;
            this.angle = angle;
            this.exponent = exponent;
        }
        SpotLight.prototype.getAbsolutePosition = function () {
            return this.transformedPosition ? this.transformedPosition : this.position;
        };
        SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            var activeCamera = this.getScene().activeCamera;
            BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
        };
        SpotLight.prototype.needCube = function () {
            return false;
        };
        SpotLight.prototype.supportsVSM = function () {
            return true;
        };
        SpotLight.prototype.needRefreshPerFrame = function () {
            return false;
        };
        SpotLight.prototype.getShadowDirection = function (faceIndex) {
            return this.direction;
        };
        SpotLight.prototype.setDirectionToTarget = function (target) {
            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
            return this.direction;
        };
        SpotLight.prototype.computeTransformedPosition = function () {
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this.transformedPosition) {
                    this.transformedPosition = BABYLON.Vector3.Zero();
                }
                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
                return true;
            }
            return false;
        };
        SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
            var normalizeDirection;
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this._transformedDirection) {
                    this._transformedDirection = BABYLON.Vector3.Zero();
                }
                this.computeTransformedPosition();
                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
                effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
                normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
            }
            else {
                effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
                normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
            }
            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
        };
        SpotLight.prototype._getWorldMatrix = function () {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
            return this._worldMatrix;
        };
        SpotLight.prototype.getTypeID = function () {
            return 2;
        };
        SpotLight.prototype.getRotation = function () {
            this.direction.normalize();
            var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
            var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
            return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], SpotLight.prototype, "position", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], SpotLight.prototype, "direction", void 0);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "angle", void 0);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "exponent", void 0);
        return SpotLight;
    }(BABYLON.Light));
    BABYLON.SpotLight = SpotLight;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.spotLight.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var HemisphericLight = (function (_super) {
        __extends(HemisphericLight, _super);
        function HemisphericLight(name, direction, scene) {
            _super.call(this, name, scene);
            this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
            this.direction = direction;
        }
        HemisphericLight.prototype.setDirectionToTarget = function (target) {
            this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
            return this.direction;
        };
        HemisphericLight.prototype.getShadowGenerator = function () {
            return null;
        };
        HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
            var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
            effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
            effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
        };
        HemisphericLight.prototype._getWorldMatrix = function () {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            return this._worldMatrix;
        };
        HemisphericLight.prototype.getTypeID = function () {
            return 3;
        };
        __decorate([
            BABYLON.serializeAsColor3()
        ], HemisphericLight.prototype, "groundColor", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], HemisphericLight.prototype, "direction", void 0);
        return HemisphericLight;
    }(BABYLON.Light));
    BABYLON.HemisphericLight = HemisphericLight;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.hemisphericLight.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var DirectionalLight = (function (_super) {
        __extends(DirectionalLight, _super);
        function DirectionalLight(name, direction, scene) {
            _super.call(this, name, scene);
            this.shadowOrthoScale = 0.5;
            this.autoUpdateExtends = true;
            // Cache
            this._orthoLeft = Number.MAX_VALUE;
            this._orthoRight = Number.MIN_VALUE;
            this._orthoTop = Number.MIN_VALUE;
            this._orthoBottom = Number.MAX_VALUE;
            this.position = direction.scale(-1);
            this.direction = direction;
        }
        DirectionalLight.prototype.getAbsolutePosition = function () {
            return this.transformedPosition ? this.transformedPosition : this.position;
        };
        DirectionalLight.prototype.setDirectionToTarget = function (target) {
            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
            return this.direction;
        };
        DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            var activeCamera = this.getScene().activeCamera;
            // Check extends
            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
                var tempVector3 = BABYLON.Vector3.Zero();
                this._orthoLeft = Number.MAX_VALUE;
                this._orthoRight = Number.MIN_VALUE;
                this._orthoTop = Number.MIN_VALUE;
                this._orthoBottom = Number.MAX_VALUE;
                for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
                    var mesh = renderList[meshIndex];
                    if (!mesh) {
                        continue;
                    }
                    var boundingInfo = mesh.getBoundingInfo();
                    if (!boundingInfo) {
                        continue;
                    }
                    var boundingBox = boundingInfo.boundingBox;
                    for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
                        BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
                        if (tempVector3.x < this._orthoLeft)
                            this._orthoLeft = tempVector3.x;
                        if (tempVector3.y < this._orthoBottom)
                            this._orthoBottom = tempVector3.y;
                        if (tempVector3.x > this._orthoRight)
                            this._orthoRight = tempVector3.x;
                        if (tempVector3.y > this._orthoTop)
                            this._orthoTop = tempVector3.y;
                    }
                }
            }
            var xOffset = this._orthoRight - this._orthoLeft;
            var yOffset = this._orthoTop - this._orthoBottom;
            BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
        };
        DirectionalLight.prototype.supportsVSM = function () {
            return true;
        };
        DirectionalLight.prototype.needRefreshPerFrame = function () {
            return true;
        };
        DirectionalLight.prototype.needCube = function () {
            return false;
        };
        DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
            return this.direction;
        };
        DirectionalLight.prototype.computeTransformedPosition = function () {
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this.transformedPosition) {
                    this.transformedPosition = BABYLON.Vector3.Zero();
                }
                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
                return true;
            }
            return false;
        };
        DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this._transformedDirection) {
                    this._transformedDirection = BABYLON.Vector3.Zero();
                }
                BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
                effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
                return;
            }
            effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
        };
        DirectionalLight.prototype._getWorldMatrix = function () {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
            return this._worldMatrix;
        };
        DirectionalLight.prototype.getTypeID = function () {
            return 1;
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], DirectionalLight.prototype, "position", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], DirectionalLight.prototype, "direction", void 0);
        __decorate([
            BABYLON.serialize()
        ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
        __decorate([
            BABYLON.serialize()
        ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
        return DirectionalLight;
    }(BABYLON.Light));
    BABYLON.DirectionalLight = DirectionalLight;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.directionalLight.js.map
 
var BABYLON;
(function (BABYLON) {
    var ShadowGenerator = (function () {
        function ShadowGenerator(mapSize, light) {
            var _this = this;
            // Members
            this._filter = ShadowGenerator.FILTER_NONE;
            this.blurScale = 2;
            this._blurBoxOffset = 0;
            this._bias = 0.00005;
            this._lightDirection = BABYLON.Vector3.Zero();
            this.forceBackFacesOnly = false;
            this._darkness = 0;
            this._transparencyShadow = false;
            this._viewMatrix = BABYLON.Matrix.Zero();
            this._projectionMatrix = BABYLON.Matrix.Zero();
            this._transformMatrix = BABYLON.Matrix.Zero();
            this._worldViewProjection = BABYLON.Matrix.Zero();
            this._currentFaceIndex = 0;
            this._currentFaceIndexCache = 0;
            this._useFullFloat = true;
            this._light = light;
            this._scene = light.getScene();
            this._mapSize = mapSize;
            light._shadowGenerator = this;
            // Texture type fallback from float to int if not supported.
            var textureType;
            var caps = this._scene.getEngine().getCaps();
            if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
                this._useFullFloat = true;
                textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
            }
            else {
                this._useFullFloat = false;
                textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            }
            // Render target
            this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._shadowMap.anisotropicFilteringLevel = 1;
            this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
            this._shadowMap.renderParticles = false;
            this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
                _this._currentFaceIndex = faceIndex;
            });
            this._shadowMap.onAfterUnbindObservable.add(function () {
                if (!_this.useBlurVarianceShadowMap) {
                    return;
                }
                if (!_this._shadowMap2) {
                    _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
                    _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
                    _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
                    _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
                        effect.setTexture("textureSampler", _this._shadowMap);
                    });
                    _this.blurBoxOffset = 1;
                }
                _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
            });
            // Custom render function
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                var scene = _this._scene;
                var engine = scene.getEngine();
                // Culling
                engine.setState(subMesh.getMaterial().backFaceCulling);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
                    engine.enableEffect(_this._effect);
                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
                    var material = subMesh.getMaterial();
                    _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
                    _this._effect.setVector3("lightPosition", _this.getLight().position);
                    if (_this.getLight().needCube()) {
                        _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
                    }
                    // Alpha test
                    if (material && material.needAlphaTesting()) {
                        var alphaTexture = material.getAlphaTestTexture();
                        _this._effect.setTexture("diffuseSampler", alphaTexture);
                        _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                    }
                    // Bones
                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                    }
                    if (_this.forceBackFacesOnly) {
                        engine.setState(true, 0, false, true);
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
                    if (_this.forceBackFacesOnly) {
                        engine.setState(true, 0, false, false);
                    }
                }
                else {
                    // Need to reset refresh rate of the shadowMap
                    _this._shadowMap.resetRefreshCounter();
                }
            };
            this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
                var index;
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
                if (_this._transparencyShadow) {
                    for (index = 0; index < transparentSubMeshes.length; index++) {
                        renderSubMesh(transparentSubMeshes.data[index]);
                    }
                }
            };
            this._shadowMap.onClearObservable.add(function (engine) {
                if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
                    engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
                }
                else {
                    engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
                }
            });
        }
        Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
            // Static
            get: function () {
                return ShadowGenerator._FILTER_NONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
            get: function () {
                return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
            get: function () {
                return ShadowGenerator._FILTER_POISSONSAMPLING;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
            get: function () {
                return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "bias", {
            get: function () {
                return this._bias;
            },
            set: function (bias) {
                this._bias = bias;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
            get: function () {
                return this._blurBoxOffset;
            },
            set: function (value) {
                var _this = this;
                if (this._blurBoxOffset === value) {
                    return;
                }
                this._blurBoxOffset = value;
                if (this._boxBlurPostprocess) {
                    this._boxBlurPostprocess.dispose();
                }
                this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
                this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
                });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "filter", {
            get: function () {
                return this._filter;
            },
            set: function (value) {
                if (this._filter === value) {
                    return;
                }
                this._filter = value;
                if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
                    this._shadowMap.anisotropicFilteringLevel = 16;
                    this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
                }
                else {
                    this._shadowMap.anisotropicFilteringLevel = 1;
                    this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
            get: function () {
                return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
            },
            set: function (value) {
                this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
            get: function () {
                return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
                    (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
                        this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
            },
            set: function (value) {
                this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
            get: function () {
                return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
            },
            set: function (value) {
                this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
            var defines = [];
            if (this._useFullFloat) {
                defines.push("#define FULLFLOAT");
            }
            if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
                defines.push("#define VSM");
            }
            if (this.getLight().needCube()) {
                defines.push("#define CUBEMAP");
            }
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var mesh = subMesh.getMesh();
            var material = subMesh.getMaterial();
            // Alpha test
            if (material && material.needAlphaTesting()) {
                defines.push("#define ALPHATEST");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    var alphaTexture = material.getAlphaTestTexture();
                    if (alphaTexture.coordinatesIndex === 1) {
                        attribs.push(BABYLON.VertexBuffer.UV2Kind);
                        defines.push("#define UV2");
                    }
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Instances
            if (useInstances) {
                defines.push("#define INSTANCES");
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
            // Get correct effect      
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
            }
            return this._effect.isReady();
        };
        ShadowGenerator.prototype.getShadowMap = function () {
            return this._shadowMap;
        };
        ShadowGenerator.prototype.getShadowMapForRendering = function () {
            if (this._shadowMap2) {
                return this._shadowMap2;
            }
            return this._shadowMap;
        };
        ShadowGenerator.prototype.getLight = function () {
            return this._light;
        };
        // Methods
        ShadowGenerator.prototype.getTransformMatrix = function () {
            var scene = this._scene;
            if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
                return this._transformMatrix;
            }
            this._currentRenderID = scene.getRenderId();
            this._currentFaceIndexCache = this._currentFaceIndex;
            var lightPosition = this._light.position;
            BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
            if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
                this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
            }
            if (this._light.computeTransformedPosition()) {
                lightPosition = this._light.transformedPosition;
            }
            if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
                this._cachedPosition = lightPosition.clone();
                this._cachedDirection = this._lightDirection.clone();
                BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
                this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
            }
            return this._transformMatrix;
        };
        ShadowGenerator.prototype.getDarkness = function () {
            return this._darkness;
        };
        ShadowGenerator.prototype.setDarkness = function (darkness) {
            if (darkness >= 1.0)
                this._darkness = 1.0;
            else if (darkness <= 0.0)
                this._darkness = 0.0;
            else
                this._darkness = darkness;
        };
        ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
            this._transparencyShadow = hasShadow;
        };
        ShadowGenerator.prototype._packHalf = function (depth) {
            var scale = depth * 255.0;
            var fract = scale - Math.floor(scale);
            return new BABYLON.Vector2(depth - fract / 255.0, fract);
        };
        ShadowGenerator.prototype.dispose = function () {
            this._shadowMap.dispose();
            if (this._shadowMap2) {
                this._shadowMap2.dispose();
            }
            if (this._downSamplePostprocess) {
                this._downSamplePostprocess.dispose();
            }
            if (this._boxBlurPostprocess) {
                this._boxBlurPostprocess.dispose();
            }
        };
        ShadowGenerator.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.lightId = this._light.id;
            serializationObject.mapSize = this.getShadowMap().getRenderSize();
            serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
            serializationObject.usePoissonSampling = this.usePoissonSampling;
            serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
            serializationObject.renderList = [];
            for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
                var mesh = this.getShadowMap().renderList[meshIndex];
                serializationObject.renderList.push(mesh.id);
            }
            return serializationObject;
        };
        ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
            //casting to point light, as light is missing the position attr and typescript complains.
            var light = scene.getLightByID(parsedShadowGenerator.lightId);
            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
                var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
                meshes.forEach(function (mesh) {
                    shadowGenerator.getShadowMap().renderList.push(mesh);
                });
            }
            if (parsedShadowGenerator.usePoissonSampling) {
                shadowGenerator.usePoissonSampling = true;
            }
            else if (parsedShadowGenerator.useVarianceShadowMap) {
                shadowGenerator.useVarianceShadowMap = true;
            }
            else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
                shadowGenerator.useBlurVarianceShadowMap = true;
                if (parsedShadowGenerator.blurScale) {
                    shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
                }
                if (parsedShadowGenerator.blurBoxOffset) {
                    shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
                }
            }
            if (parsedShadowGenerator.bias !== undefined) {
                shadowGenerator.bias = parsedShadowGenerator.bias;
            }
            shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
            return shadowGenerator;
        };
        ShadowGenerator._FILTER_NONE = 0;
        ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
        ShadowGenerator._FILTER_POISSONSAMPLING = 2;
        ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
        return ShadowGenerator;
    }());
    BABYLON.ShadowGenerator = ShadowGenerator;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.shadowGenerator.js.map
 
var BABYLON;
(function (BABYLON) {
    var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
        if (boxMin.x > sphereCenter.x + sphereRadius)
            return false;
        if (sphereCenter.x - sphereRadius > boxMax.x)
            return false;
        if (boxMin.y > sphereCenter.y + sphereRadius)
            return false;
        if (sphereCenter.y - sphereRadius > boxMax.y)
            return false;
        if (boxMin.z > sphereCenter.z + sphereRadius)
            return false;
        if (sphereCenter.z - sphereRadius > boxMax.z)
            return false;
        return true;
    };
    var getLowestRoot = (function () {
        var result = { root: 0, found: false };
        return function (a, b, c, maxR) {
            result.root = 0;
            result.found = false;
            var determinant = b * b - 4.0 * a * c;
            if (determinant < 0)
                return result;
            var sqrtD = Math.sqrt(determinant);
            var r1 = (-b - sqrtD) / (2.0 * a);
            var r2 = (-b + sqrtD) / (2.0 * a);
            if (r1 > r2) {
                var temp = r2;
                r2 = r1;
                r1 = temp;
            }
            if (r1 > 0 && r1 < maxR) {
                result.root = r1;
                result.found = true;
                return result;
            }
            if (r2 > 0 && r2 < maxR) {
                result.root = r2;
                result.found = true;
                return result;
            }
            return result;
        };
    })();
    var Collider = (function () {
        function Collider() {
            this.radius = new BABYLON.Vector3(1, 1, 1);
            this.retry = 0;
            this.basePointWorld = BABYLON.Vector3.Zero();
            this.velocityWorld = BABYLON.Vector3.Zero();
            this.normalizedVelocity = BABYLON.Vector3.Zero();
            this._collisionPoint = BABYLON.Vector3.Zero();
            this._planeIntersectionPoint = BABYLON.Vector3.Zero();
            this._tempVector = BABYLON.Vector3.Zero();
            this._tempVector2 = BABYLON.Vector3.Zero();
            this._tempVector3 = BABYLON.Vector3.Zero();
            this._tempVector4 = BABYLON.Vector3.Zero();
            this._edge = BABYLON.Vector3.Zero();
            this._baseToVertex = BABYLON.Vector3.Zero();
            this._destinationPoint = BABYLON.Vector3.Zero();
            this._slidePlaneNormal = BABYLON.Vector3.Zero();
            this._displacementVector = BABYLON.Vector3.Zero();
        }
        // Methods
        Collider.prototype._initialize = function (source, dir, e) {
            this.velocity = dir;
            BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
            this.basePoint = source;
            source.multiplyToRef(this.radius, this.basePointWorld);
            dir.multiplyToRef(this.radius, this.velocityWorld);
            this.velocityWorldLength = this.velocityWorld.length();
            this.epsilon = e;
            this.collisionFound = false;
        };
        Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
            pa.subtractToRef(point, this._tempVector);
            pb.subtractToRef(point, this._tempVector2);
            BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
            var d = BABYLON.Vector3.Dot(this._tempVector4, n);
            if (d < 0)
                return false;
            pc.subtractToRef(point, this._tempVector3);
            BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
            d = BABYLON.Vector3.Dot(this._tempVector4, n);
            if (d < 0)
                return false;
            BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
            d = BABYLON.Vector3.Dot(this._tempVector4, n);
            return d >= 0;
        };
        Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
            var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
            var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
            if (distance > this.velocityWorldLength + max + sphereRadius) {
                return false;
            }
            if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
                return false;
            return true;
        };
        Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
            var t0;
            var embeddedInPlane = false;
            //defensive programming, actually not needed.
            if (!trianglePlaneArray) {
                trianglePlaneArray = [];
            }
            if (!trianglePlaneArray[faceIndex]) {
                trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
                trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
            }
            var trianglePlane = trianglePlaneArray[faceIndex];
            if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
                return;
            var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
            var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
            if (normalDotVelocity == 0) {
                if (Math.abs(signedDistToTrianglePlane) >= 1.0)
                    return;
                embeddedInPlane = true;
                t0 = 0;
            }
            else {
                t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
                var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
                if (t0 > t1) {
                    var temp = t1;
                    t1 = t0;
                    t0 = temp;
                }
                if (t0 > 1.0 || t1 < 0.0)
                    return;
                if (t0 < 0)
                    t0 = 0;
                if (t0 > 1.0)
                    t0 = 1.0;
            }
            this._collisionPoint.copyFromFloats(0, 0, 0);
            var found = false;
            var t = 1.0;
            if (!embeddedInPlane) {
                this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
                this.velocity.scaleToRef(t0, this._tempVector);
                this._planeIntersectionPoint.addInPlace(this._tempVector);
                if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
                    found = true;
                    t = t0;
                    this._collisionPoint.copyFrom(this._planeIntersectionPoint);
                }
            }
            if (!found) {
                var velocitySquaredLength = this.velocity.lengthSquared();
                var a = velocitySquaredLength;
                this.basePoint.subtractToRef(p1, this._tempVector);
                var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
                var c = this._tempVector.lengthSquared() - 1.0;
                var lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    t = lowestRoot.root;
                    found = true;
                    this._collisionPoint.copyFrom(p1);
                }
                this.basePoint.subtractToRef(p2, this._tempVector);
                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
                c = this._tempVector.lengthSquared() - 1.0;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    t = lowestRoot.root;
                    found = true;
                    this._collisionPoint.copyFrom(p2);
                }
                this.basePoint.subtractToRef(p3, this._tempVector);
                b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
                c = this._tempVector.lengthSquared() - 1.0;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    t = lowestRoot.root;
                    found = true;
                    this._collisionPoint.copyFrom(p3);
                }
                p2.subtractToRef(p1, this._edge);
                p1.subtractToRef(this.basePoint, this._baseToVertex);
                var edgeSquaredLength = this._edge.lengthSquared();
                var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
                var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
                    if (f >= 0.0 && f <= 1.0) {
                        t = lowestRoot.root;
                        found = true;
                        this._edge.scaleInPlace(f);
                        p1.addToRef(this._edge, this._collisionPoint);
                    }
                }
                p3.subtractToRef(p2, this._edge);
                p2.subtractToRef(this.basePoint, this._baseToVertex);
                edgeSquaredLength = this._edge.lengthSquared();
                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
                    if (f >= 0.0 && f <= 1.0) {
                        t = lowestRoot.root;
                        found = true;
                        this._edge.scaleInPlace(f);
                        p2.addToRef(this._edge, this._collisionPoint);
                    }
                }
                p1.subtractToRef(p3, this._edge);
                p3.subtractToRef(this.basePoint, this._baseToVertex);
                edgeSquaredLength = this._edge.lengthSquared();
                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
                    if (f >= 0.0 && f <= 1.0) {
                        t = lowestRoot.root;
                        found = true;
                        this._edge.scaleInPlace(f);
                        p3.addToRef(this._edge, this._collisionPoint);
                    }
                }
            }
            if (found) {
                var distToCollision = t * this.velocity.length();
                if (!this.collisionFound || distToCollision < this.nearestDistance) {
                    if (!this.intersectionPoint) {
                        this.intersectionPoint = this._collisionPoint.clone();
                    }
                    else {
                        this.intersectionPoint.copyFrom(this._collisionPoint);
                    }
                    this.nearestDistance = distToCollision;
                    this.collisionFound = true;
                }
            }
        };
        Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
            for (var i = indexStart; i < indexEnd; i += 3) {
                var p1 = pts[indices[i] - decal];
                var p2 = pts[indices[i + 1] - decal];
                var p3 = pts[indices[i + 2] - decal];
                this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
            }
        };
        Collider.prototype._getResponse = function (pos, vel) {
            pos.addToRef(vel, this._destinationPoint);
            vel.scaleInPlace((this.nearestDistance / vel.length()));
            this.basePoint.addToRef(vel, pos);
            pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
            this._slidePlaneNormal.normalize();
            this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
            pos.addInPlace(this._displacementVector);
            this.intersectionPoint.addInPlace(this._displacementVector);
            this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
            this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
            this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
        };
        return Collider;
    }());
    BABYLON.Collider = Collider;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.collider.js.map
 
var BABYLON;
(function (BABYLON) {
    //WebWorker code will be inserted to this variable.
    BABYLON.CollisionWorker = "";
    (function (WorkerTaskType) {
        WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
        WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
        WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
    })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
    var WorkerTaskType = BABYLON.WorkerTaskType;
    (function (WorkerReplyType) {
        WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
        WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
    })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
    var WorkerReplyType = BABYLON.WorkerReplyType;
    var CollisionCoordinatorWorker = (function () {
        function CollisionCoordinatorWorker() {
            var _this = this;
            this._scaledPosition = BABYLON.Vector3.Zero();
            this._scaledVelocity = BABYLON.Vector3.Zero();
            this.onMeshUpdated = function (mesh) {
                _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
            };
            this.onGeometryUpdated = function (geometry) {
                _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
            };
            this._afterRender = function () {
                if (!_this._init)
                    return;
                if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
                    return;
                }
                //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
                //TODO make sure update runs as fast as possible to be able to update 60 FPS.
                if (_this._runningUpdated > 4) {
                    return;
                }
                ++_this._runningUpdated;
                var payload = {
                    updatedMeshes: _this._addUpdateMeshesList,
                    updatedGeometries: _this._addUpdateGeometriesList,
                    removedGeometries: _this._toRemoveGeometryArray,
                    removedMeshes: _this._toRemoveMeshesArray
                };
                var message = {
                    payload: payload,
                    taskType: WorkerTaskType.UPDATE
                };
                var serializable = [];
                for (var id in payload.updatedGeometries) {
                    if (payload.updatedGeometries.hasOwnProperty(id)) {
                        //prepare transferables
                        serializable.push(message.payload.updatedGeometries[id].indices.buffer);
                        serializable.push(message.payload.updatedGeometries[id].normals.buffer);
                        serializable.push(message.payload.updatedGeometries[id].positions.buffer);
                    }
                }
                _this._worker.postMessage(message, serializable);
                _this._addUpdateMeshesList = {};
                _this._addUpdateGeometriesList = {};
                _this._toRemoveGeometryArray = [];
                _this._toRemoveMeshesArray = [];
            };
            this._onMessageFromWorker = function (e) {
                var returnData = e.data;
                if (returnData.error != WorkerReplyType.SUCCESS) {
                    //TODO what errors can be returned from the worker?
                    BABYLON.Tools.Warn("error returned from worker!");
                    return;
                }
                switch (returnData.taskType) {
                    case WorkerTaskType.INIT:
                        _this._init = true;
                        //Update the worked with ALL of the scene's current state
                        _this._scene.meshes.forEach(function (mesh) {
                            _this.onMeshAdded(mesh);
                        });
                        _this._scene.getGeometries().forEach(function (geometry) {
                            _this.onGeometryAdded(geometry);
                        });
                        break;
                    case WorkerTaskType.UPDATE:
                        _this._runningUpdated--;
                        break;
                    case WorkerTaskType.COLLIDE:
                        _this._runningCollisionTask = false;
                        var returnPayload = returnData.payload;
                        if (!_this._collisionsCallbackArray[returnPayload.collisionId])
                            return;
                        _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
                        //cleanup
                        _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
                        break;
                }
            };
            this._collisionsCallbackArray = [];
            this._init = false;
            this._runningUpdated = 0;
            this._runningCollisionTask = false;
            this._addUpdateMeshesList = {};
            this._addUpdateGeometriesList = {};
            this._toRemoveGeometryArray = [];
            this._toRemoveMeshesArray = [];
        }
        CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
            if (!this._init)
                return;
            if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
                return;
            position.divideToRef(collider.radius, this._scaledPosition);
            velocity.divideToRef(collider.radius, this._scaledVelocity);
            this._collisionsCallbackArray[collisionIndex] = onNewPosition;
            var payload = {
                collider: {
                    position: this._scaledPosition.asArray(),
                    velocity: this._scaledVelocity.asArray(),
                    radius: collider.radius.asArray()
                },
                collisionId: collisionIndex,
                excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
                maximumRetry: maximumRetry
            };
            var message = {
                payload: payload,
                taskType: WorkerTaskType.COLLIDE
            };
            this._worker.postMessage(message);
        };
        CollisionCoordinatorWorker.prototype.init = function (scene) {
            this._scene = scene;
            this._scene.registerAfterRender(this._afterRender);
            var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
            this._worker = new Worker(workerUrl);
            this._worker.onmessage = this._onMessageFromWorker;
            var message = {
                payload: {},
                taskType: WorkerTaskType.INIT
            };
            this._worker.postMessage(message);
        };
        CollisionCoordinatorWorker.prototype.destroy = function () {
            this._scene.unregisterAfterRender(this._afterRender);
            this._worker.terminate();
        };
        CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
            mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
            this.onMeshUpdated(mesh);
        };
        CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
            this._toRemoveMeshesArray.push(mesh.uniqueId);
        };
        CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
            //TODO this will break if the user uses his own function. This should be an array of callbacks!
            geometry.onGeometryUpdated = this.onGeometryUpdated;
            this.onGeometryUpdated(geometry);
        };
        CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
            this._toRemoveGeometryArray.push(geometry.id);
        };
        CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
            var submeshes = [];
            if (mesh.subMeshes) {
                submeshes = mesh.subMeshes.map(function (sm, idx) {
                    return {
                        position: idx,
                        verticesStart: sm.verticesStart,
                        verticesCount: sm.verticesCount,
                        indexStart: sm.indexStart,
                        indexCount: sm.indexCount,
                        hasMaterial: !!sm.getMaterial(),
                        sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
                        sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
                        boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
                        boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
                    };
                });
            }
            var geometryId = null;
            if (mesh instanceof BABYLON.Mesh) {
                geometryId = mesh.geometry ? mesh.geometry.id : null;
            }
            else if (mesh instanceof BABYLON.InstancedMesh) {
                geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
            }
            return {
                uniqueId: mesh.uniqueId,
                id: mesh.id,
                name: mesh.name,
                geometryId: geometryId,
                sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
                sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
                boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
                boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
                worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
                subMeshes: submeshes,
                checkCollisions: mesh.checkCollisions
            };
        };
        CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
            return {
                id: geometry.id,
                positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
                normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
                indices: new Int32Array(geometry.getIndices() || []),
            };
        };
        return CollisionCoordinatorWorker;
    }());
    BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
    var CollisionCoordinatorLegacy = (function () {
        function CollisionCoordinatorLegacy() {
            this._scaledPosition = BABYLON.Vector3.Zero();
            this._scaledVelocity = BABYLON.Vector3.Zero();
            this._finalPosition = BABYLON.Vector3.Zero();
        }
        CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
            position.divideToRef(collider.radius, this._scaledPosition);
            velocity.divideToRef(collider.radius, this._scaledVelocity);
            collider.collidedMesh = null;
            collider.retry = 0;
            collider.initialVelocity = this._scaledVelocity;
            collider.initialPosition = this._scaledPosition;
            this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
            this._finalPosition.multiplyInPlace(collider.radius);
            //run the callback
            onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
        };
        CollisionCoordinatorLegacy.prototype.init = function (scene) {
            this._scene = scene;
        };
        CollisionCoordinatorLegacy.prototype.destroy = function () {
            //Legacy need no destruction method.
        };
        //No update in legacy mode
        CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
        CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
        CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
        CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
        CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
        CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
        CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
            if (excludedMesh === void 0) { excludedMesh = null; }
            var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
            if (collider.retry >= maximumRetry) {
                finalPosition.copyFrom(position);
                return;
            }
            collider._initialize(position, velocity, closeDistance);
            // Check all meshes
            for (var index = 0; index < this._scene.meshes.length; index++) {
                var mesh = this._scene.meshes[index];
                if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
                    mesh._checkCollision(collider);
                }
            }
            if (!collider.collisionFound) {
                position.addToRef(velocity, finalPosition);
                return;
            }
            if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
                collider._getResponse(position, velocity);
            }
            if (velocity.length() <= closeDistance) {
                finalPosition.copyFrom(position);
                return;
            }
            collider.retry++;
            this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
        };
        return CollisionCoordinatorLegacy;
    }());
    BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.collisionCoordinator.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Camera = (function (_super) {
        __extends(Camera, _super);
        function Camera(name, position, scene) {
            _super.call(this, name, scene);
            this.upVector = BABYLON.Vector3.Up();
            this.orthoLeft = null;
            this.orthoRight = null;
            this.orthoBottom = null;
            this.orthoTop = null;
            this.fov = 0.8;
            this.minZ = 1.0;
            this.maxZ = 10000.0;
            this.inertia = 0.9;
            this.mode = Camera.PERSPECTIVE_CAMERA;
            this.isIntermediate = false;
            this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
            this.layerMask = 0x0FFFFFFF;
            this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
            // Camera rig members
            this.cameraRigMode = Camera.RIG_MODE_NONE;
            this._rigCameras = new Array();
            // Cache
            this._computedViewMatrix = BABYLON.Matrix.Identity();
            this._projectionMatrix = new BABYLON.Matrix();
            this._doNotComputeProjectionMatrix = false;
            this._postProcesses = new Array();
            this._transformMatrix = BABYLON.Matrix.Zero();
            this._webvrViewMatrix = BABYLON.Matrix.Identity();
            this._activeMeshes = new BABYLON.SmartArray(256);
            this._globalPosition = BABYLON.Vector3.Zero();
            this._refreshFrustumPlanes = true;
            scene.addCamera(this);
            if (!scene.activeCamera) {
                scene.activeCamera = this;
            }
            this.position = position;
        }
        Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
            get: function () {
                return Camera._PERSPECTIVE_CAMERA;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
            get: function () {
                return Camera._ORTHOGRAPHIC_CAMERA;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
            get: function () {
                return Camera._FOVMODE_VERTICAL_FIXED;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
            get: function () {
                return Camera._FOVMODE_HORIZONTAL_FIXED;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_NONE", {
            get: function () {
                return Camera._RIG_MODE_NONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
            get: function () {
                return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
            get: function () {
                return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
            get: function () {
                return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
            get: function () {
                return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_VR", {
            get: function () {
                return Camera._RIG_MODE_VR;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
            get: function () {
                return Camera._RIG_MODE_WEBVR;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         */
        Camera.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            ret += ", type: " + this.getTypeName();
            if (this.animations) {
                for (var i = 0; i < this.animations.length; i++) {
                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
                }
            }
            if (fullDetails) {
            }
            return ret;
        };
        Object.defineProperty(Camera.prototype, "globalPosition", {
            get: function () {
                return this._globalPosition;
            },
            enumerable: true,
            configurable: true
        });
        Camera.prototype.getActiveMeshes = function () {
            return this._activeMeshes;
        };
        Camera.prototype.isActiveMesh = function (mesh) {
            return (this._activeMeshes.indexOf(mesh) !== -1);
        };
        //Cache
        Camera.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.mode = undefined;
            this._cache.minZ = undefined;
            this._cache.maxZ = undefined;
            this._cache.fov = undefined;
            this._cache.fovMode = undefined;
            this._cache.aspectRatio = undefined;
            this._cache.orthoLeft = undefined;
            this._cache.orthoRight = undefined;
            this._cache.orthoBottom = undefined;
            this._cache.orthoTop = undefined;
            this._cache.renderWidth = undefined;
            this._cache.renderHeight = undefined;
        };
        Camera.prototype._updateCache = function (ignoreParentClass) {
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            var engine = this.getEngine();
            this._cache.position.copyFrom(this.position);
            this._cache.upVector.copyFrom(this.upVector);
            this._cache.mode = this.mode;
            this._cache.minZ = this.minZ;
            this._cache.maxZ = this.maxZ;
            this._cache.fov = this.fov;
            this._cache.fovMode = this.fovMode;
            this._cache.aspectRatio = engine.getAspectRatio(this);
            this._cache.orthoLeft = this.orthoLeft;
            this._cache.orthoRight = this.orthoRight;
            this._cache.orthoBottom = this.orthoBottom;
            this._cache.orthoTop = this.orthoTop;
            this._cache.renderWidth = engine.getRenderWidth();
            this._cache.renderHeight = engine.getRenderHeight();
        };
        Camera.prototype._updateFromScene = function () {
            this.updateCache();
            this.update();
        };
        // Synchronized
        Camera.prototype._isSynchronized = function () {
            return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
        };
        Camera.prototype._isSynchronizedViewMatrix = function () {
            if (!_super.prototype._isSynchronized.call(this))
                return false;
            return this._cache.position.equals(this.position)
                && this._cache.upVector.equals(this.upVector)
                && this.isSynchronizedWithParent();
        };
        Camera.prototype._isSynchronizedProjectionMatrix = function () {
            var check = this._cache.mode === this.mode
                && this._cache.minZ === this.minZ
                && this._cache.maxZ === this.maxZ;
            if (!check) {
                return false;
            }
            var engine = this.getEngine();
            if (this.mode === Camera.PERSPECTIVE_CAMERA) {
                check = this._cache.fov === this.fov
                    && this._cache.fovMode === this.fovMode
                    && this._cache.aspectRatio === engine.getAspectRatio(this);
            }
            else {
                check = this._cache.orthoLeft === this.orthoLeft
                    && this._cache.orthoRight === this.orthoRight
                    && this._cache.orthoBottom === this.orthoBottom
                    && this._cache.orthoTop === this.orthoTop
                    && this._cache.renderWidth === engine.getRenderWidth()
                    && this._cache.renderHeight === engine.getRenderHeight();
            }
            return check;
        };
        // Controls
        Camera.prototype.attachControl = function (element, noPreventDefault) {
        };
        Camera.prototype.detachControl = function (element) {
        };
        Camera.prototype.update = function () {
            if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
                this._updateRigCameras();
            }
            this._checkInputs();
        };
        Camera.prototype._checkInputs = function () {
        };
        Camera.prototype._cascadePostProcessesToRigCams = function () {
            // invalidate framebuffer
            if (this._postProcesses.length > 0) {
                this._postProcesses[0].markTextureDirty();
            }
            // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
            for (var i = 0, len = this._rigCameras.length; i < len; i++) {
                var cam = this._rigCameras[i];
                var rigPostProcess = cam._rigPostProcess;
                // for VR rig, there does not have to be a post process 
                if (rigPostProcess) {
                    var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
                    if (isPass) {
                        // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
                        cam.isIntermediate = this._postProcesses.length === 0;
                    }
                    cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
                    rigPostProcess.markTextureDirty();
                }
                else {
                    cam._postProcesses = this._postProcesses.slice(0);
                }
            }
        };
        Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
            if (insertAt === void 0) { insertAt = null; }
            if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
                BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
                return 0;
            }
            if (insertAt == null || insertAt < 0) {
                this._postProcesses.push(postProcess);
            }
            else {
                this._postProcesses.splice(insertAt, 0, postProcess);
            }
            this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated            
            return this._postProcesses.indexOf(postProcess);
        };
        Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
            if (atIndices === void 0) { atIndices = null; }
            var result = [];
            var i;
            var index;
            if (!atIndices) {
                var idx = this._postProcesses.indexOf(postProcess);
                if (idx !== -1) {
                    this._postProcesses.splice(idx, 1);
                }
            }
            else {
                atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
                // iterate descending, so can just splice as we go
                for (i = atIndices.length - 1; i >= 0; i--) {
                    if (this._postProcesses[atIndices[i]] !== postProcess) {
                        result.push(i);
                        continue;
                    }
                    this._postProcesses.splice(index, 1);
                }
            }
            this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
            return result;
        };
        Camera.prototype.getWorldMatrix = function () {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            var viewMatrix = this.getViewMatrix();
            viewMatrix.invertToRef(this._worldMatrix);
            return this._worldMatrix;
        };
        Camera.prototype._getViewMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        Camera.prototype.getViewMatrix = function (force) {
            this._computedViewMatrix = this._computeViewMatrix(force);
            if (!force && this._isSynchronizedViewMatrix()) {
                return this._computedViewMatrix;
            }
            this._refreshFrustumPlanes = true;
            if (!this.parent || !this.parent.getWorldMatrix) {
                this._globalPosition.copyFrom(this.position);
            }
            else {
                if (!this._worldMatrix) {
                    this._worldMatrix = BABYLON.Matrix.Identity();
                }
                this._computedViewMatrix.invertToRef(this._worldMatrix);
                this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
                this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
                this._computedViewMatrix.invert();
                this._markSyncedWithParent();
            }
            this._currentRenderId = this.getScene().getRenderId();
            return this._computedViewMatrix;
        };
        Camera.prototype._computeViewMatrix = function (force) {
            if (!force && this._isSynchronizedViewMatrix()) {
                return this._computedViewMatrix;
            }
            this._computedViewMatrix = this._getViewMatrix();
            this._currentRenderId = this.getScene().getRenderId();
            return this._computedViewMatrix;
        };
        Camera.prototype.freezeProjectionMatrix = function (projection) {
            this._doNotComputeProjectionMatrix = true;
            if (projection !== undefined) {
                this._projectionMatrix = projection;
            }
        };
        ;
        Camera.prototype.unfreezeProjectionMatrix = function () {
            this._doNotComputeProjectionMatrix = false;
        };
        ;
        Camera.prototype.getProjectionMatrix = function (force) {
            if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
                return this._projectionMatrix;
            }
            this._refreshFrustumPlanes = true;
            var engine = this.getEngine();
            var scene = this.getScene();
            if (this.mode === Camera.PERSPECTIVE_CAMERA) {
                if (this.minZ <= 0) {
                    this.minZ = 0.1;
                }
                if (scene.useRightHandedSystem) {
                    BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
                }
                else {
                    BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
                }
                return this._projectionMatrix;
            }
            var halfWidth = engine.getRenderWidth() / 2.0;
            var halfHeight = engine.getRenderHeight() / 2.0;
            if (scene.useRightHandedSystem) {
                BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
            }
            else {
                BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
            }
            return this._projectionMatrix;
        };
        Camera.prototype.getTranformationMatrix = function () {
            this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
            return this._transformMatrix;
        };
        Camera.prototype.updateFrustumPlanes = function () {
            if (!this._refreshFrustumPlanes) {
                return;
            }
            this.getTranformationMatrix();
            if (!this._frustumPlanes) {
                this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
            }
            else {
                BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
            }
            this._refreshFrustumPlanes = false;
        };
        Camera.prototype.isInFrustum = function (target) {
            this.updateFrustumPlanes();
            return target.isInFrustum(this._frustumPlanes);
        };
        Camera.prototype.isCompletelyInFrustum = function (target) {
            this.updateFrustumPlanes();
            return target.isCompletelyInFrustum(this._frustumPlanes);
        };
        Camera.prototype.dispose = function () {
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            this.getScene().removeCamera(this);
            while (this._rigCameras.length > 0) {
                this._rigCameras.pop().dispose();
            }
            // Postprocesses
            for (var i = 0; i < this._postProcesses.length; ++i) {
                this._postProcesses[i].dispose(this);
            }
            _super.prototype.dispose.call(this);
        };
        // ---- Camera rigs section ----
        Camera.prototype.setCameraRigMode = function (mode, rigParams) {
            while (this._rigCameras.length > 0) {
                this._rigCameras.pop().dispose();
            }
            this.cameraRigMode = mode;
            this._cameraRigParams = {};
            //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target, 
            //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
            this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
            this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
            // create the rig cameras, unless none
            if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
                this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
                this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
            }
            switch (this.cameraRigMode) {
                case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                    this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
                    this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
                    break;
                case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                    var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
                    this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
                    this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
                    break;
                case Camera.RIG_MODE_VR:
                    var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
                    this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
                    this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
                    this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                    this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
                    this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
                    this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
                    this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
                    this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
                    this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                    this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
                    this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
                    this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
                    if (metrics.compensateDistortion) {
                        this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
                        this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
                    }
                    break;
                case Camera.RIG_MODE_WEBVR:
                    if (rigParams.vrDisplay) {
                        //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
                        //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
                        this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
                        this._rigCameras[0].setCameraRigParameter("left", true);
                        this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
                        //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
                        this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                        this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
                        //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
                        this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
                        this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
                        //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
                        this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                        this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
                    }
                    break;
            }
            this._cascadePostProcessesToRigCams();
            this.
                update();
        };
        Camera.prototype._getVRProjectionMatrix = function () {
            BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
            this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
            return this._projectionMatrix;
        };
        Camera.prototype._getWebVRProjectionMatrix = function () {
            var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
            //babylon compatible matrix
            [8, 9, 10, 11].forEach(function (num) {
                projectionArray[num] *= -1;
            });
            BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
            return this._projectionMatrix;
        };
        //Can be used, but we'll use the free camera's view matrix calculation
        Camera.prototype._getWebVRViewMatrix = function () {
            var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
            //babylon compatible matrix
            [8, 9, 10, 11].forEach(function (num) {
                projectionArray[num] *= -1;
            });
            BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
            return this._webvrViewMatrix;
        };
        Camera.prototype.setCameraRigParameter = function (name, value) {
            if (!this._cameraRigParams) {
                this._cameraRigParams = {};
            }
            this._cameraRigParams[name] = value;
            //provisionnally:
            if (name === "interaxialDistance") {
                this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
            }
        };
        /**
         * needs to be overridden by children so sub has required properties to be copied
         */
        Camera.prototype.createRigCamera = function (name, cameraIndex) {
            return null;
        };
        /**
         * May need to be overridden by children
         */
        Camera.prototype._updateRigCameras = function () {
            for (var i = 0; i < this._rigCameras.length; i++) {
                this._rigCameras[i].minZ = this.minZ;
                this._rigCameras[i].maxZ = this.maxZ;
                this._rigCameras[i].fov = this.fov;
            }
            // only update viewport when ANAGLYPH
            if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
                this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
            }
        };
        Camera.prototype._setupInputs = function () {
        };
        Camera.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            // Type
            serializationObject.type = this.getTypeName();
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            if (this.inputs) {
                this.inputs.serialize(serializationObject);
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            serializationObject.ranges = this.serializeAnimationRanges();
            return serializationObject;
        };
        Camera.prototype.getTypeName = function () {
            return "Camera";
        };
        Camera.prototype.clone = function (name) {
            return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
        };
        Camera.prototype.getDirection = function (localAxis) {
            var result = BABYLON.Vector3.Zero();
            this.getDirectionToRef(localAxis, result);
            return result;
        };
        Camera.prototype.getDirectionToRef = function (localAxis, result) {
            BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
        };
        Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
            if (interaxial_distance === void 0) { interaxial_distance = 0; }
            if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
            switch (type) {
                case "ArcRotateCamera":
                    return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
                case "DeviceOrientationCamera":
                    return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "FollowCamera":
                    return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "ArcFollowCamera":
                    return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
                case "GamepadCamera":
                    return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "TouchCamera":
                    return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "VirtualJoysticksCamera":
                    return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "WebVRFreeCamera":
                    return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "VRDeviceOrientationFreeCamera":
                    return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
                case "AnaglyphArcRotateCamera":
                    return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
                case "AnaglyphFreeCamera":
                    return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
                case "AnaglyphGamepadCamera":
                    return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
                case "AnaglyphUniversalCamera":
                    return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
                case "StereoscopicArcRotateCamera":
                    return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
                case "StereoscopicFreeCamera":
                    return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
                case "StereoscopicGamepadCamera":
                    return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
                case "StereoscopicUniversalCamera":
                    return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
                case "FreeCamera":
                    return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
                default:
                    return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
            }
        };
        Camera.Parse = function (parsedCamera, scene) {
            var type = parsedCamera.type;
            var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
            var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
            // Parent
            if (parsedCamera.parentId) {
                camera._waitingParentId = parsedCamera.parentId;
            }
            //If camera has an input manager, let it parse inputs settings
            if (camera.inputs) {
                camera.inputs.parse(parsedCamera);
                camera._setupInputs();
            }
            // Target
            if (parsedCamera.target) {
                if (camera.setTarget) {
                    camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
                }
            }
            // Apply 3d rig, when found
            if (parsedCamera.cameraRigMode) {
                var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
                camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
            }
            // Animations
            if (parsedCamera.animations) {
                for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
                    var parsedAnimation = parsedCamera.animations[animationIndex];
                    camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
            }
            if (parsedCamera.autoAnimate) {
                scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
            }
            return camera;
        };
        // Statics
        Camera._PERSPECTIVE_CAMERA = 0;
        Camera._ORTHOGRAPHIC_CAMERA = 1;
        Camera._FOVMODE_VERTICAL_FIXED = 0;
        Camera._FOVMODE_HORIZONTAL_FIXED = 1;
        Camera._RIG_MODE_NONE = 0;
        Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
        Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
        Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
        Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
        Camera._RIG_MODE_VR = 20;
        Camera._RIG_MODE_WEBVR = 21;
        Camera.ForceAttachControlToAlwaysPreventDefault = false;
        __decorate([
            BABYLON.serializeAsVector3()
        ], Camera.prototype, "position", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], Camera.prototype, "upVector", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoLeft", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoRight", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoBottom", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoTop", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "fov", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "minZ", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "maxZ", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "inertia", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "mode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "layerMask", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "fovMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "cameraRigMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "interaxialDistance", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "isStereoscopicSideBySide", void 0);
        return Camera;
    }(BABYLON.Node));
    BABYLON.Camera = Camera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.camera.js.map
 
var BABYLON;
(function (BABYLON) {
    BABYLON.CameraInputTypes = {};
    var CameraInputsManager = (function () {
        function CameraInputsManager(camera) {
            this.attached = {};
            this.camera = camera;
            this.checkInputs = function () { };
        }
        CameraInputsManager.prototype.add = function (input) {
            var type = input.getSimpleName();
            if (this.attached[type]) {
                BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
                return;
            }
            this.attached[type] = input;
            input.camera = this.camera;
            //for checkInputs, we are dynamically creating a function
            //the goal is to avoid the performance penalty of looping for inputs in the render loop
            if (input.checkInputs) {
                this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
            }
            if (this.attachedElement) {
                input.attachControl(this.attachedElement);
            }
        };
        CameraInputsManager.prototype.remove = function (inputToRemove) {
            for (var cam in this.attached) {
                var input = this.attached[cam];
                if (input === inputToRemove) {
                    input.detachControl(this.attachedElement);
                    delete this.attached[cam];
                    this.rebuildInputCheck();
                }
            }
        };
        CameraInputsManager.prototype.removeByType = function (inputType) {
            for (var cam in this.attached) {
                var input = this.attached[cam];
                if (input.getTypeName() === inputType) {
                    input.detachControl(this.attachedElement);
                    delete this.attached[cam];
                    this.rebuildInputCheck();
                }
            }
        };
        CameraInputsManager.prototype._addCheckInputs = function (fn) {
            var current = this.checkInputs;
            return function () {
                current();
                fn();
            };
        };
        CameraInputsManager.prototype.attachInput = function (input) {
            input.attachControl(this.attachedElement, this.noPreventDefault);
        };
        CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
            if (this.attachedElement) {
                return;
            }
            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
            this.attachedElement = element;
            this.noPreventDefault = noPreventDefault;
            for (var cam in this.attached) {
                var input = this.attached[cam];
                this.attached[cam].attachControl(element, noPreventDefault);
            }
        };
        CameraInputsManager.prototype.detachElement = function (element) {
            if (this.attachedElement !== element) {
                return;
            }
            for (var cam in this.attached) {
                var input = this.attached[cam];
                this.attached[cam].detachControl(element);
            }
            this.attachedElement = null;
        };
        CameraInputsManager.prototype.rebuildInputCheck = function () {
            this.checkInputs = function () { };
            for (var cam in this.attached) {
                var input = this.attached[cam];
                if (input.checkInputs) {
                    this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
                }
            }
        };
        CameraInputsManager.prototype.clear = function () {
            if (this.attachedElement) {
                this.detachElement(this.attachedElement);
            }
            this.attached = {};
            this.attachedElement = null;
            this.checkInputs = function () { };
        };
        CameraInputsManager.prototype.serialize = function (serializedCamera) {
            var inputs = {};
            for (var cam in this.attached) {
                var input = this.attached[cam];
                var res = BABYLON.SerializationHelper.Serialize(input);
                inputs[input.getTypeName()] = res;
            }
            serializedCamera.inputsmgr = inputs;
        };
        CameraInputsManager.prototype.parse = function (parsedCamera) {
            var parsedInputs = parsedCamera.inputsmgr;
            if (parsedInputs) {
                this.clear();
                for (var n in parsedInputs) {
                    var construct = BABYLON.CameraInputTypes[n];
                    if (construct) {
                        var parsedinput = parsedInputs[n];
                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
                        this.add(input);
                    }
                }
            }
            else {
                //2016-03-08 this part is for managing backward compatibility
                for (var n in this.attached) {
                    var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
                    if (construct) {
                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
                        this.remove(this.attached[n]);
                        this.add(input);
                    }
                }
            }
        };
        return CameraInputsManager;
    }());
    BABYLON.CameraInputsManager = CameraInputsManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.cameraInputsManager.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraMouseInput = (function () {
        function FreeCameraMouseInput(touchEnabled) {
            if (touchEnabled === void 0) { touchEnabled = true; }
            this.touchEnabled = touchEnabled;
            this.buttons = [0, 1, 2];
            this.angularSensibility = 2000.0;
        }
        FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var engine = this.camera.getEngine();
            if (!this._pointerInput) {
                this._pointerInput = function (p, s) {
                    var evt = p.event;
                    if (!_this.touchEnabled && evt.pointerType === "touch") {
                        return;
                    }
                    if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
                        return;
                    }
                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                        try {
                            evt.srcElement.setPointerCapture(evt.pointerId);
                        }
                        catch (e) {
                        }
                        _this.previousPosition = {
                            x: evt.clientX,
                            y: evt.clientY
                        };
                        if (!noPreventDefault) {
                            evt.preventDefault();
                            element.focus();
                        }
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
                        try {
                            evt.srcElement.releasePointerCapture(evt.pointerId);
                        }
                        catch (e) {
                        }
                        _this.previousPosition = null;
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
                        if (!_this.previousPosition || engine.isPointerLock) {
                            return;
                        }
                        var offsetX = evt.clientX - _this.previousPosition.x;
                        var offsetY = evt.clientY - _this.previousPosition.y;
                        if (_this.camera.getScene().useRightHandedSystem) {
                            _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
                        }
                        else {
                            _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
                        }
                        _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
                        _this.previousPosition = {
                            x: evt.clientX,
                            y: evt.clientY
                        };
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                };
            }
            this._onMouseMove = function (evt) {
                if (!engine.isPointerLock) {
                    return;
                }
                var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
                var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
                if (_this.camera.getScene().useRightHandedSystem) {
                    _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
                }
                else {
                    _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
                }
                _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
                _this.previousPosition = null;
                if (!noPreventDefault) {
                    evt.preventDefault();
                }
            };
            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
            element.addEventListener("mousemove", this._onMouseMove, false);
        };
        FreeCameraMouseInput.prototype.detachControl = function (element) {
            if (this._observer && element) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                element.removeEventListener("mousemove", this._onMouseMove);
                this._observer = null;
                this._onMouseMove = null;
                this.previousPosition = null;
            }
        };
        FreeCameraMouseInput.prototype.getTypeName = function () {
            return "FreeCameraMouseInput";
        };
        FreeCameraMouseInput.prototype.getSimpleName = function () {
            return "mouse";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraMouseInput.prototype, "buttons", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
        return FreeCameraMouseInput;
    }());
    BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
    BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freecamera.input.mouse.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraKeyboardMoveInput = (function () {
        function FreeCameraKeyboardMoveInput() {
            this._keys = [];
            this.keysUp = [38];
            this.keysDown = [40];
            this.keysLeft = [37];
            this.keysRight = [39];
        }
        FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            if (!this._onKeyDown) {
                element.tabIndex = 1;
                this._onKeyDown = function (evt) {
                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
                        var index = _this._keys.indexOf(evt.keyCode);
                        if (index === -1) {
                            _this._keys.push(evt.keyCode);
                        }
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                };
                this._onKeyUp = function (evt) {
                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
                        var index = _this._keys.indexOf(evt.keyCode);
                        if (index >= 0) {
                            _this._keys.splice(index, 1);
                        }
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                };
                element.addEventListener("keydown", this._onKeyDown, false);
                element.addEventListener("keyup", this._onKeyUp, false);
                BABYLON.Tools.RegisterTopRootEvents([
                    { name: "blur", handler: this._onLostFocus }
                ]);
            }
        };
        FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
            if (this._onKeyDown) {
                element.removeEventListener("keydown", this._onKeyDown);
                element.removeEventListener("keyup", this._onKeyUp);
                BABYLON.Tools.UnregisterTopRootEvents([
                    { name: "blur", handler: this._onLostFocus }
                ]);
                this._keys = [];
                this._onKeyDown = null;
                this._onKeyUp = null;
            }
        };
        FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
            if (this._onKeyDown) {
                var camera = this.camera;
                // Keyboard
                for (var index = 0; index < this._keys.length; index++) {
                    var keyCode = this._keys[index];
                    var speed = camera._computeLocalCameraSpeed();
                    if (this.keysLeft.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(-speed, 0, 0);
                    }
                    else if (this.keysUp.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(0, 0, speed);
                    }
                    else if (this.keysRight.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(speed, 0, 0);
                    }
                    else if (this.keysDown.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(0, 0, -speed);
                    }
                    if (camera.getScene().useRightHandedSystem) {
                        camera._localDirection.z *= -1;
                    }
                    camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
                    BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
                    camera.cameraDirection.addInPlace(camera._transformedDirection);
                }
            }
        };
        FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
            return "FreeCameraKeyboardMoveInput";
        };
        FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
            this._keys = [];
        };
        FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
            return "keyboard";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
        return FreeCameraKeyboardMoveInput;
    }());
    BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
    BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraTouchInput = (function () {
        function FreeCameraTouchInput() {
            this._offsetX = null;
            this._offsetY = null;
            this._pointerCount = 0;
            this._pointerPressed = [];
            this.touchAngularSensibility = 200000.0;
            this.touchMoveSensibility = 250.0;
        }
        FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var previousPosition;
            if (this._pointerInput === undefined) {
                this._onLostFocus = function (evt) {
                    _this._offsetX = null;
                    _this._offsetY = null;
                };
                this._pointerInput = function (p, s) {
                    var evt = p.event;
                    if (evt.pointerType === "mouse") {
                        return;
                    }
                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                        _this._pointerPressed.push(evt.pointerId);
                        if (_this._pointerPressed.length !== 1) {
                            return;
                        }
                        previousPosition = {
                            x: evt.clientX,
                            y: evt.clientY
                        };
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                        var index = _this._pointerPressed.indexOf(evt.pointerId);
                        if (index === -1) {
                            return;
                        }
                        _this._pointerPressed.splice(index, 1);
                        if (index != 0) {
                            return;
                        }
                        previousPosition = null;
                        _this._offsetX = null;
                        _this._offsetY = null;
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                        if (!previousPosition) {
                            return;
                        }
                        var index = _this._pointerPressed.indexOf(evt.pointerId);
                        if (index != 0) {
                            return;
                        }
                        _this._offsetX = evt.clientX - previousPosition.x;
                        _this._offsetY = -(evt.clientY - previousPosition.y);
                    }
                };
            }
            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
            element.addEventListener("blur", this._onLostFocus);
        };
        FreeCameraTouchInput.prototype.detachControl = function (element) {
            if (this._pointerInput && element) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                this._observer = null;
                element.removeEventListener("blur", this._onLostFocus);
                this._onLostFocus = null;
                this._pointerPressed = [];
                this._offsetX = null;
                this._offsetY = null;
                this._pointerCount = 0;
            }
        };
        FreeCameraTouchInput.prototype.checkInputs = function () {
            if (this._offsetX) {
                var camera = this.camera;
                camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
                if (this._pointerPressed.length > 1) {
                    camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
                }
                else {
                    var speed = camera._computeLocalCameraSpeed();
                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
                    BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
                    camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
                }
            }
        };
        FreeCameraTouchInput.prototype.getTypeName = function () {
            return "FreeCameraTouchInput";
        };
        FreeCameraTouchInput.prototype.getSimpleName = function () {
            return "touch";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
        return FreeCameraTouchInput;
    }());
    BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
    BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freecamera.input.touch.js.map
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraDeviceOrientationInput = (function () {
        function FreeCameraDeviceOrientationInput() {
            var _this = this;
            this._screenOrientationAngle = 0;
            this._screenQuaternion = new BABYLON.Quaternion();
            this._alpha = 0;
            this._beta = 0;
            this._gamma = 0;
            this._orientationChanged = function () {
                _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
                _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
                _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
            };
            this._deviceOrientation = function (evt) {
                _this._alpha = evt.alpha;
                _this._beta = evt.beta;
                _this._gamma = evt.gamma;
            };
            this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
            this._orientationChanged();
        }
        Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
            get: function () {
                return this._camera;
            },
            set: function (camera) {
                this._camera = camera;
                if (!this._camera.rotationQuaternion)
                    this._camera.rotationQuaternion = new BABYLON.Quaternion();
            },
            enumerable: true,
            configurable: true
        });
        FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
            window.addEventListener("orientationchange", this._orientationChanged);
            window.addEventListener("deviceorientation", this._deviceOrientation);
            //In certain cases, the attach control is called AFTER orientation was changed,
            //So this is needed.
            this._orientationChanged();
        };
        FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
            window.removeEventListener("orientationchange", this._orientationChanged);
            window.removeEventListener("deviceorientation", this._deviceOrientation);
        };
        FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
            //if no device orientation provided, don't update the rotation.
            //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
            if (!this._alpha)
                return;
            BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
            this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
            this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
            //Mirror on XY Plane
            this._camera.rotationQuaternion.z *= -1;
            this._camera.rotationQuaternion.w *= -1;
        };
        FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
            return "FreeCameraDeviceOrientationInput";
        };
        FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
            return "deviceOrientation";
        };
        return FreeCameraDeviceOrientationInput;
    }());
    BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
    BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraGamepadInput = (function () {
        function FreeCameraGamepadInput() {
            this.gamepadAngularSensibility = 200;
            this.gamepadMoveSensibility = 40;
        }
        FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
        };
        FreeCameraGamepadInput.prototype.detachControl = function (element) {
            if (this._gamepads) {
                this._gamepads.dispose();
            }
            this.gamepad = null;
        };
        FreeCameraGamepadInput.prototype.checkInputs = function () {
            if (this.gamepad) {
                var camera = this.camera;
                var LSValues = this.gamepad.leftStick;
                var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
                var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
                var RSValues = this.gamepad.rightStick;
                var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
                var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
                RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
                RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
                var speed = camera._computeLocalCameraSpeed() * 50.0;
                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
                camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
            }
        };
        FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
            // Only the first gamepad can control the camera
            if (gamepad.index === 0) {
                this.gamepad = gamepad;
            }
        };
        FreeCameraGamepadInput.prototype.getTypeName = function () {
            return "FreeCameraGamepadInput";
        };
        FreeCameraGamepadInput.prototype.getSimpleName = function () {
            return "gamepad";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
        return FreeCameraGamepadInput;
    }());
    BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
    BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var ArcRotateCameraKeyboardMoveInput = (function () {
        function ArcRotateCameraKeyboardMoveInput() {
            this._keys = [];
            this.keysUp = [38];
            this.keysDown = [40];
            this.keysLeft = [37];
            this.keysRight = [39];
        }
        ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            element.tabIndex = 1;
            this._onKeyDown = function (evt) {
                if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                    _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                    _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                    _this.keysRight.indexOf(evt.keyCode) !== -1) {
                    var index = _this._keys.indexOf(evt.keyCode);
                    if (index === -1) {
                        _this._keys.push(evt.keyCode);
                    }
                    if (evt.preventDefault) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                }
            };
            this._onKeyUp = function (evt) {
                if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                    _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                    _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                    _this.keysRight.indexOf(evt.keyCode) !== -1) {
                    var index = _this._keys.indexOf(evt.keyCode);
                    if (index >= 0) {
                        _this._keys.splice(index, 1);
                    }
                    if (evt.preventDefault) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                }
            };
            this._onLostFocus = function () {
                _this._keys = [];
            };
            element.addEventListener("keydown", this._onKeyDown, false);
            element.addEventListener("keyup", this._onKeyUp, false);
            BABYLON.Tools.RegisterTopRootEvents([
                { name: "blur", handler: this._onLostFocus }
            ]);
        };
        ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
            if (element) {
                element.removeEventListener("keydown", this._onKeyDown);
                element.removeEventListener("keyup", this._onKeyUp);
            }
            BABYLON.Tools.UnregisterTopRootEvents([
                { name: "blur", handler: this._onLostFocus }
            ]);
            this._keys = [];
            this._onKeyDown = null;
            this._onKeyUp = null;
            this._onLostFocus = null;
        };
        ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
            if (this._onKeyDown) {
                var camera = this.camera;
                for (var index = 0; index < this._keys.length; index++) {
                    var keyCode = this._keys[index];
                    if (this.keysLeft.indexOf(keyCode) !== -1) {
                        camera.inertialAlphaOffset -= 0.01;
                    }
                    else if (this.keysUp.indexOf(keyCode) !== -1) {
                        camera.inertialBetaOffset -= 0.01;
                    }
                    else if (this.keysRight.indexOf(keyCode) !== -1) {
                        camera.inertialAlphaOffset += 0.01;
                    }
                    else if (this.keysDown.indexOf(keyCode) !== -1) {
                        camera.inertialBetaOffset += 0.01;
                    }
                }
            }
        };
        ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
            return "ArcRotateCameraKeyboardMoveInput";
        };
        ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
            return "keyboard";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
        return ArcRotateCameraKeyboardMoveInput;
    }());
    BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
    BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var ArcRotateCameraMouseWheelInput = (function () {
        function ArcRotateCameraMouseWheelInput() {
            this.wheelPrecision = 3.0;
        }
        ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            this._wheel = function (p, s) {
                //sanity check - this should be a PointerWheel event.
                if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
                    return;
                var event = p.event;
                var delta = 0;
                if (event.wheelDelta) {
                    delta = event.wheelDelta / (_this.wheelPrecision * 40);
                }
                else if (event.detail) {
                    delta = -event.detail / _this.wheelPrecision;
                }
                if (delta)
                    _this.camera.inertialRadiusOffset += delta;
                if (event.preventDefault) {
                    if (!noPreventDefault) {
                        event.preventDefault();
                    }
                }
            };
            this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
        };
        ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
            if (this._observer && element) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                this._observer = null;
                this._wheel = null;
            }
        };
        ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
            return "ArcRotateCameraMouseWheelInput";
        };
        ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
            return "mousewheel";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
        return ArcRotateCameraMouseWheelInput;
    }());
    BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
    BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var eventPrefix = BABYLON.Tools.GetPointerPrefix();
    var ArcRotateCameraPointersInput = (function () {
        function ArcRotateCameraPointersInput() {
            this.buttons = [0, 1, 2];
            this.angularSensibilityX = 1000.0;
            this.angularSensibilityY = 1000.0;
            this.pinchPrecision = 6.0;
            this.panningSensibility = 50.0;
            this._isPanClick = false;
            this.pinchInwards = true;
        }
        ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var engine = this.camera.getEngine();
            var cacheSoloPointer; // cache pointer object for better perf on camera rotation
            var pointA, pointB;
            var previousPinchDistance = 0;
            this._pointerInput = function (p, s) {
                var evt = p.event;
                if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
                    return;
                }
                if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                    try {
                        evt.srcElement.setPointerCapture(evt.pointerId);
                    }
                    catch (e) {
                    }
                    // Manage panning with pan button click
                    _this._isPanClick = evt.button === _this.camera._panningMouseButton;
                    // manage pointers
                    cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
                    if (pointA === undefined) {
                        pointA = cacheSoloPointer;
                    }
                    else if (pointB === undefined) {
                        pointB = cacheSoloPointer;
                    }
                    if (!noPreventDefault) {
                        evt.preventDefault();
                        element.focus();
                    }
                }
                else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
                    try {
                        evt.srcElement.releasePointerCapture(evt.pointerId);
                    }
                    catch (e) {
                    }
                    cacheSoloPointer = null;
                    previousPinchDistance = 0;
                    //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, 
                    //but emptying completly pointers collection is required to fix a bug on iPhone : 
                    //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers  
                    //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
                    pointA = pointB = undefined;
                    if (!noPreventDefault) {
                        evt.preventDefault();
                    }
                }
                else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
                    if (!noPreventDefault) {
                        evt.preventDefault();
                    }
                    // One button down
                    if (pointA && pointB === undefined) {
                        if (_this.panningSensibility !== 0 &&
                            ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
                                (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
                            _this.camera
                                .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
                            _this.camera
                                .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
                        }
                        else {
                            var offsetX = evt.clientX - cacheSoloPointer.x;
                            var offsetY = evt.clientY - cacheSoloPointer.y;
                            _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
                            _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
                        }
                        cacheSoloPointer.x = evt.clientX;
                        cacheSoloPointer.y = evt.clientY;
                    }
                    else if (pointA && pointB) {
                        //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
                        var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
                        ed.x = evt.clientX;
                        ed.y = evt.clientY;
                        var direction = _this.pinchInwards ? 1 : -1;
                        var distX = pointA.x - pointB.x;
                        var distY = pointA.y - pointB.y;
                        var pinchSquaredDistance = (distX * distX) + (distY * distY);
                        if (previousPinchDistance === 0) {
                            previousPinchDistance = pinchSquaredDistance;
                            return;
                        }
                        if (pinchSquaredDistance !== previousPinchDistance) {
                            _this.camera
                                .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
                                (_this.pinchPrecision *
                                    ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
                                    direction);
                            previousPinchDistance = pinchSquaredDistance;
                        }
                    }
                }
            };
            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
            this._onContextMenu = function (evt) {
                evt.preventDefault();
            };
            if (!this.camera._useCtrlForPanning) {
                element.addEventListener("contextmenu", this._onContextMenu, false);
            }
            this._onLostFocus = function () {
                //this._keys = [];
                pointA = pointB = undefined;
                previousPinchDistance = 0;
                cacheSoloPointer = null;
            };
            this._onMouseMove = function (evt) {
                if (!engine.isPointerLock) {
                    return;
                }
                var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
                var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
                _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
                _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
                if (!noPreventDefault) {
                    evt.preventDefault();
                }
            };
            this._onGestureStart = function (e) {
                if (window.MSGesture === undefined) {
                    return;
                }
                if (!_this._MSGestureHandler) {
                    _this._MSGestureHandler = new MSGesture();
                    _this._MSGestureHandler.target = element;
                }
                _this._MSGestureHandler.addPointer(e.pointerId);
            };
            this._onGesture = function (e) {
                _this.camera.radius *= e.scale;
                if (e.preventDefault) {
                    if (!noPreventDefault) {
                        e.stopPropagation();
                        e.preventDefault();
                    }
                }
            };
            element.addEventListener("mousemove", this._onMouseMove, false);
            element.addEventListener("MSPointerDown", this._onGestureStart, false);
            element.addEventListener("MSGestureChange", this._onGesture, false);
            element.addEventListener("keydown", this._onKeyDown, false);
            element.addEventListener("keyup", this._onKeyUp, false);
            BABYLON.Tools.RegisterTopRootEvents([
                { name: "blur", handler: this._onLostFocus }
            ]);
        };
        ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
            if (element && this._observer) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                this._observer = null;
                element.removeEventListener("contextmenu", this._onContextMenu);
                element.removeEventListener("mousemove", this._onMouseMove);
                element.removeEventListener("MSPointerDown", this._onGestureStart);
                element.removeEventListener("MSGestureChange", this._onGesture);
                element.removeEventListener("keydown", this._onKeyDown);
                element.removeEventListener("keyup", this._onKeyUp);
                this._isPanClick = false;
                this.pinchInwards = true;
                this._onKeyDown = null;
                this._onKeyUp = null;
                this._onMouseMove = null;
                this._onGestureStart = null;
                this._onGesture = null;
                this._MSGestureHandler = null;
                this._onLostFocus = null;
                this._onContextMenu = null;
            }
            BABYLON.Tools.UnregisterTopRootEvents([
                { name: "blur", handler: this._onLostFocus }
            ]);
        };
        ArcRotateCameraPointersInput.prototype.getTypeName = function () {
            return "ArcRotateCameraPointersInput";
        };
        ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
            return "pointers";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
        return ArcRotateCameraPointersInput;
    }());
    BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
    BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var ArcRotateCameraGamepadInput = (function () {
        function ArcRotateCameraGamepadInput() {
            this.gamepadRotationSensibility = 80;
            this.gamepadMoveSensibility = 40;
        }
        ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
        };
        ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
            if (this._gamepads) {
                this._gamepads.dispose();
            }
            this.gamepad = null;
        };
        ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
            if (this.gamepad) {
                var camera = this.camera;
                var RSValues = this.gamepad.rightStick;
                if (RSValues.x != 0) {
                    var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
                    if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
                        camera.inertialAlphaOffset += normalizedRX;
                    }
                }
                if (RSValues.y != 0) {
                    var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
                    if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
                        camera.inertialBetaOffset += normalizedRY;
                    }
                }
                var LSValues = this.gamepad.leftStick;
                if (LSValues.y != 0) {
                    var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
                    if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
                        this.camera.inertialRadiusOffset -= normalizedLY;
                    }
                }
            }
        };
        ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
            // Only the first gamepad can control the camera
            if (gamepad.index === 0) {
                this.gamepad = gamepad;
            }
        };
        ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
            return "ArcRotateCameraGamepadInput";
        };
        ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
            return "gamepad";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
        return ArcRotateCameraGamepadInput;
    }());
    BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
    BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
 
var BABYLON;
(function (BABYLON) {
    var ArcRotateCameraVRDeviceOrientationInput = (function () {
        function ArcRotateCameraVRDeviceOrientationInput() {
            this.alphaCorrection = 1;
            this.betaCorrection = 1;
            this.gammaCorrection = 1;
            this._alpha = 0;
            this._beta = 0;
            this._gamma = 0;
            this._dirty = false;
            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
        }
        ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
            this.camera.attachControl(element, noPreventDefault);
            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
        };
        ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
            var camera = this.camera;
            this._alpha = +evt.alpha | 0;
            this._beta = +evt.beta | 0;
            this._gamma = +evt.gamma | 0;
            this._dirty = true;
        };
        ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
            if (this._dirty) {
                this._dirty = false;
                if (this._gamma < 0) {
                    this._gamma = 180 + this._gamma;
                }
                this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
                this.camera.beta = (this._gamma / 180.0 * Math.PI);
            }
        };
        ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
        };
        ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
            return "ArcRotateCameraVRDeviceOrientationInput";
        };
        ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
            return "VRDeviceOrientation";
        };
        return ArcRotateCameraVRDeviceOrientationInput;
    }());
    BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
    BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var TargetCamera = (function (_super) {
        __extends(TargetCamera, _super);
        function TargetCamera(name, position, scene) {
            _super.call(this, name, position, scene);
            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
            this.cameraRotation = new BABYLON.Vector2(0, 0);
            this.rotation = new BABYLON.Vector3(0, 0, 0);
            this.speed = 2.0;
            this.noRotationConstraint = false;
            this.lockedTarget = null;
            this._currentTarget = BABYLON.Vector3.Zero();
            this._viewMatrix = BABYLON.Matrix.Zero();
            this._camMatrix = BABYLON.Matrix.Zero();
            this._cameraTransformMatrix = BABYLON.Matrix.Zero();
            this._cameraRotationMatrix = BABYLON.Matrix.Zero();
            this._referencePoint = new BABYLON.Vector3(0, 0, 1);
            this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
            this._transformedReferencePoint = BABYLON.Vector3.Zero();
            this._lookAtTemp = BABYLON.Matrix.Zero();
            this._tempMatrix = BABYLON.Matrix.Zero();
        }
        TargetCamera.prototype.getFrontPosition = function (distance) {
            var direction = this.getTarget().subtract(this.position);
            direction.normalize();
            direction.scaleInPlace(distance);
            return this.globalPosition.add(direction);
        };
        TargetCamera.prototype._getLockedTargetPosition = function () {
            if (!this.lockedTarget) {
                return null;
            }
            if (this.lockedTarget.absolutePosition) {
                this.lockedTarget.computeWorldMatrix();
            }
            return this.lockedTarget.absolutePosition || this.lockedTarget;
        };
        // Cache
        TargetCamera.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
        };
        TargetCamera.prototype._updateCache = function (ignoreParentClass) {
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            var lockedTargetPosition = this._getLockedTargetPosition();
            if (!lockedTargetPosition) {
                this._cache.lockedTarget = null;
            }
            else {
                if (!this._cache.lockedTarget) {
                    this._cache.lockedTarget = lockedTargetPosition.clone();
                }
                else {
                    this._cache.lockedTarget.copyFrom(lockedTargetPosition);
                }
            }
            this._cache.rotation.copyFrom(this.rotation);
            if (this.rotationQuaternion)
                this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
        };
        // Synchronized
        TargetCamera.prototype._isSynchronizedViewMatrix = function () {
            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
                return false;
            }
            var lockedTargetPosition = this._getLockedTargetPosition();
            return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
                && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
        };
        // Methods
        TargetCamera.prototype._computeLocalCameraSpeed = function () {
            var engine = this.getEngine();
            return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
        };
        // Target
        TargetCamera.prototype.setTarget = function (target) {
            this.upVector.normalize();
            BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
            this._camMatrix.invert();
            this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
            var vDir = target.subtract(this.position);
            if (vDir.x >= 0.0) {
                this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
            }
            else {
                this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
            }
            this.rotation.z = 0;
            if (isNaN(this.rotation.x)) {
                this.rotation.x = 0;
            }
            if (isNaN(this.rotation.y)) {
                this.rotation.y = 0;
            }
            if (isNaN(this.rotation.z)) {
                this.rotation.z = 0;
            }
            if (this.rotationQuaternion) {
                BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
            }
        };
        TargetCamera.prototype.getTarget = function () {
            return this._currentTarget;
        };
        TargetCamera.prototype._decideIfNeedsToMove = function () {
            return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
        };
        TargetCamera.prototype._updatePosition = function () {
            this.position.addInPlace(this.cameraDirection);
        };
        TargetCamera.prototype._checkInputs = function () {
            var needToMove = this._decideIfNeedsToMove();
            var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
            // Move
            if (needToMove) {
                this._updatePosition();
            }
            // Rotate
            if (needToRotate) {
                this.rotation.x += this.cameraRotation.x;
                this.rotation.y += this.cameraRotation.y;
                if (!this.noRotationConstraint) {
                    var limit = (Math.PI / 2) * 0.95;
                    if (this.rotation.x > limit)
                        this.rotation.x = limit;
                    if (this.rotation.x < -limit)
                        this.rotation.x = -limit;
                }
            }
            // Inertia
            if (needToMove) {
                if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
                    this.cameraDirection.x = 0;
                }
                if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
                    this.cameraDirection.y = 0;
                }
                if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
                    this.cameraDirection.z = 0;
                }
                this.cameraDirection.scaleInPlace(this.inertia);
            }
            if (needToRotate) {
                if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
                    this.cameraRotation.x = 0;
                }
                if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
                    this.cameraRotation.y = 0;
                }
                this.cameraRotation.scaleInPlace(this.inertia);
            }
            _super.prototype._checkInputs.call(this);
        };
        TargetCamera.prototype._updateCameraRotationMatrix = function () {
            if (this.rotationQuaternion) {
                this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
                //update the up vector!
                BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
            }
            else {
                BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
            }
        };
        TargetCamera.prototype._getViewMatrix = function () {
            if (!this.lockedTarget) {
                // Compute
                this._updateCameraRotationMatrix();
                BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
                // Computing target and final matrix
                this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
            }
            else {
                this._currentTarget.copyFrom(this._getLockedTargetPosition());
            }
            if (this.getScene().useRightHandedSystem) {
                BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
            }
            else {
                BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
            }
            return this._viewMatrix;
        };
        /**
         * @override
         * Override Camera.createRigCamera
         */
        TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
            if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
                var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
                if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
                    if (!this.rotationQuaternion) {
                        this.rotationQuaternion = new BABYLON.Quaternion();
                    }
                    rigCamera._cameraRigParams = {};
                    rigCamera.rotationQuaternion = new BABYLON.Quaternion();
                }
                return rigCamera;
            }
            return null;
        };
        /**
         * @override
         * Override Camera._updateRigCameras
         */
        TargetCamera.prototype._updateRigCameras = function () {
            var camLeft = this._rigCameras[0];
            var camRight = this._rigCameras[1];
            switch (this.cameraRigMode) {
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                    //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
                    var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
                    var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
                    camLeft.setTarget(this.getTarget());
                    camRight.setTarget(this.getTarget());
                    break;
                case BABYLON.Camera.RIG_MODE_VR:
                case BABYLON.Camera.RIG_MODE_WEBVR:
                    if (camLeft.rotationQuaternion) {
                        camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
                        camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
                    }
                    else {
                        camLeft.rotation.copyFrom(this.rotation);
                        camRight.rotation.copyFrom(this.rotation);
                    }
                    camLeft.position.copyFrom(this.position);
                    camRight.position.copyFrom(this.position);
                    break;
            }
            _super.prototype._updateRigCameras.call(this);
        };
        TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
            if (!this._rigCamTransformMatrix) {
                this._rigCamTransformMatrix = new BABYLON.Matrix();
            }
            var target = this.getTarget();
            BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
            this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
        };
        TargetCamera.prototype.getTypeName = function () {
            return "TargetCamera";
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], TargetCamera.prototype, "rotation", void 0);
        __decorate([
            BABYLON.serialize()
        ], TargetCamera.prototype, "speed", void 0);
        __decorate([
            BABYLON.serializeAsMeshReference("lockedTargetId")
        ], TargetCamera.prototype, "lockedTarget", void 0);
        return TargetCamera;
    }(BABYLON.Camera));
    BABYLON.TargetCamera = TargetCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.targetCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var FreeCamera = (function (_super) {
        __extends(FreeCamera, _super);
        function FreeCamera(name, position, scene) {
            var _this = this;
            _super.call(this, name, position, scene);
            this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
            this.checkCollisions = false;
            this.applyGravity = false;
            this._collider = new BABYLON.Collider();
            this._needMoveForGravity = false;
            this._oldPosition = BABYLON.Vector3.Zero();
            this._diffPosition = BABYLON.Vector3.Zero();
            this._newPosition = BABYLON.Vector3.Zero();
            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
                if (collidedMesh === void 0) { collidedMesh = null; }
                //TODO move this to the collision coordinator!
                if (_this.getScene().workerCollisions)
                    newPosition.multiplyInPlace(_this._collider.radius);
                var updatePosition = function (newPos) {
                    _this._newPosition.copyFrom(newPos);
                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
                    var oldPosition = _this.position.clone();
                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
                        _this.position.addInPlace(_this._diffPosition);
                        if (_this.onCollide && collidedMesh) {
                            _this.onCollide(collidedMesh);
                        }
                    }
                };
                updatePosition(newPosition);
            };
            this.inputs = new BABYLON.FreeCameraInputsManager(this);
            this.inputs.addKeyboard().addMouse();
        }
        Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
            //-- begin properties for backward compatibility for inputs
            get: function () {
                var mouse = this.inputs.attached["mouse"];
                if (mouse)
                    return mouse.angularSensibility;
            },
            set: function (value) {
                var mouse = this.inputs.attached["mouse"];
                if (mouse)
                    mouse.angularSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysUp", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysUp;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysUp = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysDown", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysDown;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysDown = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysLeft", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysLeft;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysLeft = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysRight", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysRight;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysRight = value;
            },
            enumerable: true,
            configurable: true
        });
        // Controls
        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
            this.inputs.attachElement(element, noPreventDefault);
        };
        FreeCamera.prototype.detachControl = function (element) {
            this.inputs.detachElement(element);
            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
            this.cameraRotation = new BABYLON.Vector2(0, 0);
        };
        FreeCamera.prototype._collideWithWorld = function (velocity) {
            var globalPosition;
            if (this.parent) {
                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
            }
            else {
                globalPosition = this.position;
            }
            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
            this._collider.radius = this.ellipsoid;
            //no need for clone, as long as gravity is not on.
            var actualVelocity = velocity;
            //add gravity to the velocity to prevent the dual-collision checking
            if (this.applyGravity) {
                //this prevents mending with cameraDirection, a global variable of the free camera class.
                actualVelocity = velocity.add(this.getScene().gravity);
            }
            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
        };
        FreeCamera.prototype._checkInputs = function () {
            if (!this._localDirection) {
                this._localDirection = BABYLON.Vector3.Zero();
                this._transformedDirection = BABYLON.Vector3.Zero();
            }
            this.inputs.checkInputs();
            _super.prototype._checkInputs.call(this);
        };
        FreeCamera.prototype._decideIfNeedsToMove = function () {
            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
        };
        FreeCamera.prototype._updatePosition = function () {
            if (this.checkCollisions && this.getScene().collisionsEnabled) {
                this._collideWithWorld(this.cameraDirection);
            }
            else {
                this.position.addInPlace(this.cameraDirection);
            }
        };
        FreeCamera.prototype.dispose = function () {
            this.inputs.clear();
            _super.prototype.dispose.call(this);
        };
        FreeCamera.prototype.getTypeName = function () {
            return "FreeCamera";
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], FreeCamera.prototype, "ellipsoid", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCamera.prototype, "checkCollisions", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCamera.prototype, "applyGravity", void 0);
        return FreeCamera;
    }(BABYLON.TargetCamera));
    BABYLON.FreeCamera = FreeCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freeCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraInputsManager = (function (_super) {
        __extends(FreeCameraInputsManager, _super);
        function FreeCameraInputsManager(camera) {
            _super.call(this, camera);
        }
        FreeCameraInputsManager.prototype.addKeyboard = function () {
            this.add(new BABYLON.FreeCameraKeyboardMoveInput());
            return this;
        };
        FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
            if (touchEnabled === void 0) { touchEnabled = true; }
            this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
            return this;
        };
        FreeCameraInputsManager.prototype.addGamepad = function () {
            this.add(new BABYLON.FreeCameraGamepadInput());
            return this;
        };
        FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
            this.add(new BABYLON.FreeCameraDeviceOrientationInput());
            return this;
        };
        FreeCameraInputsManager.prototype.addTouch = function () {
            this.add(new BABYLON.FreeCameraTouchInput());
            return this;
        };
        FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
            this.add(new BABYLON.FreeCameraVirtualJoystickInput());
            return this;
        };
        return FreeCameraInputsManager;
    }(BABYLON.CameraInputsManager));
    BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freeCameraInputsManager.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var FollowCamera = (function (_super) {
        __extends(FollowCamera, _super);
        function FollowCamera(name, position, scene, lockedTarget) {
            _super.call(this, name, position, scene);
            this.radius = 12;
            this.rotationOffset = 0;
            this.heightOffset = 4;
            this.cameraAcceleration = 0.05;
            this.maxCameraSpeed = 20;
            this.lockedTarget = lockedTarget;
        }
        FollowCamera.prototype.getRadians = function (degrees) {
            return degrees * Math.PI / 180;
        };
        FollowCamera.prototype.follow = function (cameraTarget) {
            if (!cameraTarget)
                return;
            var yRotation;
            if (cameraTarget.rotationQuaternion) {
                var rotMatrix = new BABYLON.Matrix();
                cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
                yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
            }
            else {
                yRotation = cameraTarget.rotation.y;
            }
            var radians = this.getRadians(this.rotationOffset) + yRotation;
            var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
            var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
            var dx = targetX - this.position.x;
            var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
            var dz = (targetZ) - this.position.z;
            var vx = dx * this.cameraAcceleration * 2; //this is set to .05
            var vy = dy * this.cameraAcceleration;
            var vz = dz * this.cameraAcceleration * 2;
            if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
                vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
            }
            if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
                vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
            }
            if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
                vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
            }
            this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
            this.setTarget(cameraTarget.position);
        };
        FollowCamera.prototype._checkInputs = function () {
            _super.prototype._checkInputs.call(this);
            this.follow(this.lockedTarget);
        };
        FollowCamera.prototype.getTypeName = function () {
            return "FollowCamera";
        };
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "radius", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "rotationOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "heightOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "cameraAcceleration", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "maxCameraSpeed", void 0);
        __decorate([
            BABYLON.serializeAsMeshReference("lockedTargetId")
        ], FollowCamera.prototype, "lockedTarget", void 0);
        return FollowCamera;
    }(BABYLON.TargetCamera));
    BABYLON.FollowCamera = FollowCamera;
    var ArcFollowCamera = (function (_super) {
        __extends(ArcFollowCamera, _super);
        function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
            _super.call(this, name, BABYLON.Vector3.Zero(), scene);
            this.alpha = alpha;
            this.beta = beta;
            this.radius = radius;
            this.target = target;
            this._cartesianCoordinates = BABYLON.Vector3.Zero();
            this.follow();
        }
        ArcFollowCamera.prototype.follow = function () {
            this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
            this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
            this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
            this.position = this.target.position.add(this._cartesianCoordinates);
            this.setTarget(this.target.position);
        };
        ArcFollowCamera.prototype._checkInputs = function () {
            _super.prototype._checkInputs.call(this);
            this.follow();
        };
        ArcFollowCamera.prototype.getTypeName = function () {
            return "ArcFollowCamera";
        };
        return ArcFollowCamera;
    }(BABYLON.TargetCamera));
    BABYLON.ArcFollowCamera = ArcFollowCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.followCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // We're mainly based on the logic defined into the FreeCamera code
    var TouchCamera = (function (_super) {
        __extends(TouchCamera, _super);
        //-- end properties for backward compatibility for inputs
        function TouchCamera(name, position, scene) {
            _super.call(this, name, position, scene);
            this.inputs.addTouch();
            this._setupInputs();
        }
        Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
            //-- Begin properties for backward compatibility for inputs
            get: function () {
                var touch = this.inputs.attached["touch"];
                if (touch)
                    return touch.touchAngularSensibility;
            },
            set: function (value) {
                var touch = this.inputs.attached["touch"];
                if (touch)
                    touch.touchAngularSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
            get: function () {
                var touch = this.inputs.attached["touch"];
                if (touch)
                    return touch.touchMoveSensibility;
            },
            set: function (value) {
                var touch = this.inputs.attached["touch"];
                if (touch)
                    touch.touchMoveSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        TouchCamera.prototype.getTypeName = function () {
            return "TouchCamera";
        };
        TouchCamera.prototype._setupInputs = function () {
            var mouse = this.inputs.attached["mouse"];
            if (mouse) {
                mouse.touchEnabled = false;
            }
        };
        return TouchCamera;
    }(BABYLON.FreeCamera));
    BABYLON.TouchCamera = TouchCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.touchCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var ArcRotateCamera = (function (_super) {
        __extends(ArcRotateCamera, _super);
        function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
            var _this = this;
            _super.call(this, name, BABYLON.Vector3.Zero(), scene);
            this.inertialAlphaOffset = 0;
            this.inertialBetaOffset = 0;
            this.inertialRadiusOffset = 0;
            this.lowerAlphaLimit = null;
            this.upperAlphaLimit = null;
            this.lowerBetaLimit = 0.01;
            this.upperBetaLimit = Math.PI;
            this.lowerRadiusLimit = null;
            this.upperRadiusLimit = null;
            this.inertialPanningX = 0;
            this.inertialPanningY = 0;
            //-- end properties for backward compatibility for inputs        
            this.zoomOnFactor = 1;
            this.targetScreenOffset = BABYLON.Vector2.Zero();
            this.allowUpsideDown = true;
            this._viewMatrix = new BABYLON.Matrix();
            // Panning
            this.panningAxis = new BABYLON.Vector3(1, 1, 0);
            this.checkCollisions = false;
            this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
            this._collider = new BABYLON.Collider();
            this._previousPosition = BABYLON.Vector3.Zero();
            this._collisionVelocity = BABYLON.Vector3.Zero();
            this._newPosition = BABYLON.Vector3.Zero();
            this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
                if (collidedMesh === void 0) { collidedMesh = null; }
                if (_this.getScene().workerCollisions && _this.checkCollisions) {
                    newPosition.multiplyInPlace(_this._collider.radius);
                }
                if (!collidedMesh) {
                    _this._previousPosition.copyFrom(_this.position);
                }
                else {
                    _this.setPosition(newPosition);
                    if (_this.onCollide) {
                        _this.onCollide(collidedMesh);
                    }
                }
                // Recompute because of constraints
                var cosa = Math.cos(_this.alpha);
                var sina = Math.sin(_this.alpha);
                var cosb = Math.cos(_this.beta);
                var sinb = Math.sin(_this.beta);
                if (sinb === 0) {
                    sinb = 0.0001;
                }
                var target = _this._getTargetPosition();
                target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
                _this.position.copyFrom(_this._newPosition);
                var up = _this.upVector;
                if (_this.allowUpsideDown && _this.beta < 0) {
                    up = up.clone();
                    up = up.negate();
                }
                BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
                _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
                _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
                _this._collisionTriggered = false;
            };
            if (!target) {
                this.target = BABYLON.Vector3.Zero();
            }
            else {
                this.target = target;
            }
            this.alpha = alpha;
            this.beta = beta;
            this.radius = radius;
            this.getViewMatrix();
            this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
            this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
        }
        Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
            //-- begin properties for backward compatibility for inputs       
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers)
                    return pointers.angularSensibilityX;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.angularSensibilityX = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers)
                    return pointers.angularSensibilityY;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.angularSensibilityY = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers)
                    return pointers.pinchPrecision;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.pinchPrecision = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers)
                    return pointers.panningSensibility;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.panningSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysUp;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysUp = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysDown;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysDown = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysLeft;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysLeft = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    return keyboard.keysRight;
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard)
                    keyboard.keysRight = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
            get: function () {
                var mousewheel = this.inputs.attached["mousewheel"];
                if (mousewheel)
                    return mousewheel.wheelPrecision;
            },
            set: function (value) {
                var mousewheel = this.inputs.attached["mousewheel"];
                if (mousewheel)
                    mousewheel.wheelPrecision = value;
            },
            enumerable: true,
            configurable: true
        });
        // Cache
        ArcRotateCamera.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.alpha = undefined;
            this._cache.beta = undefined;
            this._cache.radius = undefined;
            this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
        };
        ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            this._cache.target.copyFrom(this._getTargetPosition());
            this._cache.alpha = this.alpha;
            this._cache.beta = this.beta;
            this._cache.radius = this.radius;
            this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
        };
        ArcRotateCamera.prototype._getTargetPosition = function () {
            if (this.target.getAbsolutePosition) {
                var pos = this.target.getAbsolutePosition();
                return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
            }
            return this.target;
        };
        // Synchronized
        ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
            if (!_super.prototype._isSynchronizedViewMatrix.call(this))
                return false;
            return this._cache.target.equals(this.target)
                && this._cache.alpha === this.alpha
                && this._cache.beta === this.beta
                && this._cache.radius === this.radius
                && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
        };
        // Methods
        ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
            var _this = this;
            if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
            if (panningMouseButton === void 0) { panningMouseButton = 2; }
            this._useCtrlForPanning = useCtrlForPanning;
            this._panningMouseButton = panningMouseButton;
            this.inputs.attachElement(element, noPreventDefault);
            this._reset = function () {
                _this.inertialAlphaOffset = 0;
                _this.inertialBetaOffset = 0;
                _this.inertialRadiusOffset = 0;
            };
        };
        ArcRotateCamera.prototype.detachControl = function (element) {
            this.inputs.detachElement(element);
            if (this._reset) {
                this._reset();
            }
        };
        ArcRotateCamera.prototype._checkInputs = function () {
            //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
            if (this._collisionTriggered) {
                return;
            }
            this.inputs.checkInputs();
            // Inertia
            if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
                if (this.getScene().useRightHandedSystem) {
                    this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
                }
                else {
                    this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
                }
                this.beta += this.inertialBetaOffset;
                this.radius -= this.inertialRadiusOffset;
                this.inertialAlphaOffset *= this.inertia;
                this.inertialBetaOffset *= this.inertia;
                this.inertialRadiusOffset *= this.inertia;
                if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
                    this.inertialAlphaOffset = 0;
                if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
                    this.inertialBetaOffset = 0;
                if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
                    this.inertialRadiusOffset = 0;
            }
            // Panning inertia
            if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
                if (!this._localDirection) {
                    this._localDirection = BABYLON.Vector3.Zero();
                    this._transformedDirection = BABYLON.Vector3.Zero();
                }
                this.inertialPanningX *= this.inertia;
                this.inertialPanningY *= this.inertia;
                if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
                    this.inertialPanningX = 0;
                if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
                    this.inertialPanningY = 0;
                this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
                this._localDirection.multiplyInPlace(this.panningAxis);
                this._viewMatrix.invertToRef(this._cameraTransformMatrix);
                BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
                //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
                if (!this.panningAxis.y) {
                    this._transformedDirection.y = 0;
                }
                if (!this.target.getAbsolutePosition) {
                    this.target.addInPlace(this._transformedDirection);
                }
            }
            // Limits
            this._checkLimits();
            _super.prototype._checkInputs.call(this);
        };
        ArcRotateCamera.prototype._checkLimits = function () {
            if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
                if (this.allowUpsideDown && this.beta > Math.PI) {
                    this.beta = this.beta - (2 * Math.PI);
                }
            }
            else {
                if (this.beta < this.lowerBetaLimit) {
                    this.beta = this.lowerBetaLimit;
                }
            }
            if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
                if (this.allowUpsideDown && this.beta < -Math.PI) {
                    this.beta = this.beta + (2 * Math.PI);
                }
            }
            else {
                if (this.beta > this.upperBetaLimit) {
                    this.beta = this.upperBetaLimit;
                }
            }
            if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
                this.alpha = this.lowerAlphaLimit;
            }
            if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
                this.alpha = this.upperAlphaLimit;
            }
            if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
                this.radius = this.lowerRadiusLimit;
            }
            if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
                this.radius = this.upperRadiusLimit;
            }
        };
        ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
            var radiusv3 = this.position.subtract(this._getTargetPosition());
            this.radius = radiusv3.length();
            // Alpha
            this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
            if (radiusv3.z < 0) {
                this.alpha = 2 * Math.PI - this.alpha;
            }
            // Beta
            this.beta = Math.acos(radiusv3.y / this.radius);
            this._checkLimits();
        };
        ArcRotateCamera.prototype.setPosition = function (position) {
            if (this.position.equals(position)) {
                return;
            }
            this.position.copyFrom(position);
            this.rebuildAnglesAndRadius();
        };
        ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
            if (toBoundingCenter === void 0) { toBoundingCenter = false; }
            if (this._getTargetPosition().equals(target)) {
                return;
            }
            if (toBoundingCenter && target.getBoundingInfo) {
                this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
            }
            else {
                this._targetBoundingCenter = null;
            }
            this.target = target;
            this.rebuildAnglesAndRadius();
        };
        ArcRotateCamera.prototype._getViewMatrix = function () {
            // Compute
            var cosa = Math.cos(this.alpha);
            var sina = Math.sin(this.alpha);
            var cosb = Math.cos(this.beta);
            var sinb = Math.sin(this.beta);
            if (sinb === 0) {
                sinb = 0.0001;
            }
            var target = this._getTargetPosition();
            target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
            if (this.getScene().collisionsEnabled && this.checkCollisions) {
                this._collider.radius = this.collisionRadius;
                this._newPosition.subtractToRef(this.position, this._collisionVelocity);
                this._collisionTriggered = true;
                this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
            }
            else {
                this.position.copyFrom(this._newPosition);
                var up = this.upVector;
                if (this.allowUpsideDown && this.beta < 0) {
                    up = up.clone();
                    up = up.negate();
                }
                if (this.getScene().useRightHandedSystem) {
                    BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
                }
                else {
                    BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
                }
                this._viewMatrix.m[12] += this.targetScreenOffset.x;
                this._viewMatrix.m[13] += this.targetScreenOffset.y;
            }
            this._currentTarget = target;
            return this._viewMatrix;
        };
        ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
            if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
            meshes = meshes || this.getScene().meshes;
            var minMaxVector = BABYLON.Mesh.MinMax(meshes);
            var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
            this.radius = distance * this.zoomOnFactor;
            this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
        };
        ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
            if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
            var meshesOrMinMaxVector;
            var distance;
            if (meshesOrMinMaxVectorAndDistance.min === undefined) {
                meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
                meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
                distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
            }
            else {
                meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
                distance = meshesOrMinMaxVectorAndDistance.distance;
            }
            this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
            if (!doNotUpdateMaxZ) {
                this.maxZ = distance * 2;
            }
        };
        /**
         * @override
         * Override Camera.createRigCamera
         */
        ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
            var alphaShift;
            switch (this.cameraRigMode) {
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                case BABYLON.Camera.RIG_MODE_VR:
                    alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
                    break;
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                    alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
                    break;
            }
            var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
            rigCam._cameraRigParams = {};
            return rigCam;
        };
        /**
         * @override
         * Override Camera._updateRigCameras
         */
        ArcRotateCamera.prototype._updateRigCameras = function () {
            var camLeft = this._rigCameras[0];
            var camRight = this._rigCameras[1];
            camLeft.beta = camRight.beta = this.beta;
            camLeft.radius = camRight.radius = this.radius;
            switch (this.cameraRigMode) {
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                case BABYLON.Camera.RIG_MODE_VR:
                    camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
                    camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
                    break;
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                    camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
                    camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
                    break;
            }
            _super.prototype._updateRigCameras.call(this);
        };
        ArcRotateCamera.prototype.dispose = function () {
            this.inputs.clear();
            _super.prototype.dispose.call(this);
        };
        ArcRotateCamera.prototype.getTypeName = function () {
            return "ArcRotateCamera";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "alpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "beta", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "radius", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], ArcRotateCamera.prototype, "target", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
        return ArcRotateCamera;
    }(BABYLON.TargetCamera));
    BABYLON.ArcRotateCamera = ArcRotateCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcRotateCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var ArcRotateCameraInputsManager = (function (_super) {
        __extends(ArcRotateCameraInputsManager, _super);
        function ArcRotateCameraInputsManager(camera) {
            _super.call(this, camera);
        }
        ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
            this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
            return this;
        };
        ArcRotateCameraInputsManager.prototype.addPointers = function () {
            this.add(new BABYLON.ArcRotateCameraPointersInput());
            return this;
        };
        ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
            this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
            return this;
        };
        ArcRotateCameraInputsManager.prototype.addGamepad = function () {
            this.add(new BABYLON.ArcRotateCameraGamepadInput());
            return this;
        };
        ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
            this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
            return this;
        };
        return ArcRotateCameraInputsManager;
    }(BABYLON.CameraInputsManager));
    BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
 
var BABYLON;
(function (BABYLON) {
    var RenderingManager = (function () {
        function RenderingManager(scene) {
            this._renderingGroups = new Array();
            this._autoClearDepthStencil = {};
            this._customOpaqueSortCompareFn = {};
            this._customAlphaTestSortCompareFn = {};
            this._customTransparentSortCompareFn = {};
            this._renderinGroupInfo = null;
            this._scene = scene;
            for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
                this._autoClearDepthStencil[i] = true;
            }
        }
        RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
            if (this._scene._activeParticleSystems.length === 0) {
                return;
            }
            // Particles
            var activeCamera = this._scene.activeCamera;
            this._scene._particlesDuration.beginMonitoring();
            for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
                var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
                if (particleSystem.renderingGroupId !== index) {
                    continue;
                }
                if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
                    continue;
                }
                this._clearDepthStencilBuffer();
                if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
                    this._scene._activeParticles.addCount(particleSystem.render(), false);
                }
            }
            this._scene._particlesDuration.endMonitoring(false);
        };
        RenderingManager.prototype._renderSprites = function (index) {
            if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
                return;
            }
            // Sprites       
            var activeCamera = this._scene.activeCamera;
            this._scene._spritesDuration.beginMonitoring();
            for (var id = 0; id < this._scene.spriteManagers.length; id++) {
                var spriteManager = this._scene.spriteManagers[id];
                if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
                    this._clearDepthStencilBuffer();
                    spriteManager.render();
                }
            }
            this._scene._spritesDuration.endMonitoring(false);
        };
        RenderingManager.prototype._clearDepthStencilBuffer = function () {
            if (this._depthStencilBufferAlreadyCleaned) {
                return;
            }
            this._scene.getEngine().clear(0, false, true, true);
            this._depthStencilBufferAlreadyCleaned = true;
        };
        RenderingManager.prototype._renderSpritesAndParticles = function () {
            if (this._currentRenderSprites) {
                this._renderSprites(this._currentIndex);
            }
            if (this._currentRenderParticles) {
                this._renderParticles(this._currentIndex, this._currentActiveMeshes);
            }
        };
        RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
            // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
            var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
            var info = null;
            if (observable) {
                if (!this._renderinGroupInfo) {
                    this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
                }
                info = this._renderinGroupInfo;
                info.scene = this._scene;
                info.camera = this._scene.activeCamera;
            }
            this._currentActiveMeshes = activeMeshes;
            this._currentRenderParticles = renderParticles;
            this._currentRenderSprites = renderSprites;
            for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
                this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
                var renderingGroup = this._renderingGroups[index];
                var needToStepBack = false;
                this._currentIndex = index;
                if (renderingGroup) {
                    var renderingGroupMask = 0;
                    // Fire PRECLEAR stage
                    if (observable) {
                        renderingGroupMask = Math.pow(2, index);
                        info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
                        info.renderingGroupId = index;
                        observable.notifyObservers(info, renderingGroupMask);
                    }
                    // Clear depth/stencil if needed
                    if (this._autoClearDepthStencil[index]) {
                        this._clearDepthStencilBuffer();
                    }
                    // Fire PREOPAQUE stage
                    if (observable) {
                        info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
                        observable.notifyObservers(info, renderingGroupMask);
                    }
                    if (!renderingGroup.onBeforeTransparentRendering) {
                        renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
                    }
                    // Fire PRETRANSPARENT stage
                    if (observable) {
                        info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
                        observable.notifyObservers(info, renderingGroupMask);
                    }
                    if (!renderingGroup.render(customRenderFunction)) {
                        this._renderingGroups.splice(index, 1);
                        needToStepBack = true;
                        this._renderSpritesAndParticles();
                    }
                    // Fire POSTTRANSPARENT stage
                    if (observable) {
                        info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
                        observable.notifyObservers(info, renderingGroupMask);
                    }
                }
                else {
                    this._renderSpritesAndParticles();
                    if (observable) {
                        var renderingGroupMask = Math.pow(2, index);
                        info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
                        info.renderingGroupId = index;
                        observable.notifyObservers(info, renderingGroupMask);
                        info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
                        observable.notifyObservers(info, renderingGroupMask);
                    }
                }
                if (needToStepBack) {
                    index--;
                }
            }
        };
        RenderingManager.prototype.reset = function () {
            for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
                var renderingGroup = this._renderingGroups[index];
                if (renderingGroup) {
                    renderingGroup.prepare();
                }
            }
        };
        RenderingManager.prototype.dispatch = function (subMesh) {
            var mesh = subMesh.getMesh();
            var renderingGroupId = mesh.renderingGroupId || 0;
            if (!this._renderingGroups[renderingGroupId]) {
                this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
            }
            this._renderingGroups[renderingGroupId].dispatch(subMesh);
        };
        /**
         * Overrides the default sort function applied in the renderging group to prepare the meshes.
         * This allowed control for front to back rendering or reversly depending of the special needs.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
         * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
         * @param transparentSortCompareFn The transparent queue comparison function use to sort.
         */
        RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
            this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
            this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
            if (this._renderingGroups[renderingGroupId]) {
                var group = this._renderingGroups[renderingGroupId];
                group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
                group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
                group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
            }
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         */
        RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
            this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
        };
        /**
         * The max id used for rendering groups (not included)
         */
        RenderingManager.MAX_RENDERINGGROUPS = 4;
        /**
         * The min id used for rendering groups (included)
         */
        RenderingManager.MIN_RENDERINGGROUPS = 0;
        return RenderingManager;
    }());
    BABYLON.RenderingManager = RenderingManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.renderingManager.js.map
 
var BABYLON;
(function (BABYLON) {
    var RenderingGroup = (function () {
        /**
         * Creates a new rendering group.
         * @param index The rendering group index
         * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
         * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
         * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
         */
        function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this.index = index;
            this._opaqueSubMeshes = new BABYLON.SmartArray(256);
            this._transparentSubMeshes = new BABYLON.SmartArray(256);
            this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
            this._scene = scene;
            this.opaqueSortCompareFn = opaqueSortCompareFn;
            this.alphaTestSortCompareFn = alphaTestSortCompareFn;
            this.transparentSortCompareFn = transparentSortCompareFn;
        }
        Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
            /**
             * Set the opaque sort comparison function.
             * If null the sub meshes will be render in the order they were created
             */
            set: function (value) {
                this._opaqueSortCompareFn = value;
                if (value) {
                    this._renderOpaque = this.renderOpaqueSorted;
                }
                else {
                    this._renderOpaque = RenderingGroup.renderUnsorted;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
            /**
             * Set the alpha test sort comparison function.
             * If null the sub meshes will be render in the order they were created
             */
            set: function (value) {
                this._alphaTestSortCompareFn = value;
                if (value) {
                    this._renderAlphaTest = this.renderAlphaTestSorted;
                }
                else {
                    this._renderAlphaTest = RenderingGroup.renderUnsorted;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
            /**
             * Set the transparent sort comparison function.
             * If null the sub meshes will be render in the order they were created
             */
            set: function (value) {
                if (value) {
                    this._transparentSortCompareFn = value;
                }
                else {
                    this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
                }
                this._renderTransparent = this.renderTransparentSorted;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Render all the sub meshes contained in the group.
         * @param customRenderFunction Used to override the default render behaviour of the group.
         * @returns true if rendered some submeshes.
         */
        RenderingGroup.prototype.render = function (customRenderFunction) {
            if (customRenderFunction) {
                customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
                return true;
            }
            if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
                if (this.onBeforeTransparentRendering) {
                    this.onBeforeTransparentRendering();
                }
                return false;
            }
            var engine = this._scene.getEngine();
            // Opaque
            this._renderOpaque(this._opaqueSubMeshes);
            // Alpha test
            engine.setAlphaTesting(true);
            this._renderAlphaTest(this._alphaTestSubMeshes);
            engine.setAlphaTesting(false);
            if (this.onBeforeTransparentRendering) {
                this.onBeforeTransparentRendering();
            }
            // Transparent
            this._renderTransparent(this._transparentSubMeshes);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            return true;
        };
        /**
         * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
            return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
        };
        /**
         * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
            return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
        };
        /**
         * Renders the opaque submeshes in the order from the transparentSortCompareFn.
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
            return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
        };
        /**
         * Renders the submeshes in a specified order.
         * @param subMeshes The submeshes to sort before render
         * @param sortCompareFn The comparison function use to sort
         * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
         * @param transparent Specifies to activate blending if true
         */
        RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
            var subIndex = 0;
            var subMesh;
            for (; subIndex < subMeshes.length; subIndex++) {
                subMesh = subMeshes.data[subIndex];
                subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
                subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
            }
            var sortedArray = subMeshes.data.slice(0, subMeshes.length);
            sortedArray.sort(sortCompareFn);
            for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
                subMesh = sortedArray[subIndex];
                subMesh.render(transparent);
            }
        };
        /**
         * Renders the submeshes in the order they were dispatched (no sort applied).
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.renderUnsorted = function (subMeshes) {
            for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
                var submesh = subMeshes.data[subIndex];
                submesh.render(false);
            }
        };
        /**
         * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
         * are rendered back to front if in the same alpha index.
         *
         * @param a The first submesh
         * @param b The second submesh
         * @returns The result of the comparison
         */
        RenderingGroup.defaultTransparentSortCompare = function (a, b) {
            // Alpha index first
            if (a._alphaIndex > b._alphaIndex) {
                return 1;
            }
            if (a._alphaIndex < b._alphaIndex) {
                return -1;
            }
            // Then distance to camera
            return RenderingGroup.backToFrontSortCompare(a, b);
        };
        /**
         * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
         * are rendered back to front.
         *
         * @param a The first submesh
         * @param b The second submesh
         * @returns The result of the comparison
         */
        RenderingGroup.backToFrontSortCompare = function (a, b) {
            // Then distance to camera
            if (a._distanceToCamera < b._distanceToCamera) {
                return 1;
            }
            if (a._distanceToCamera > b._distanceToCamera) {
                return -1;
            }
            return 0;
        };
        /**
         * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
         * are rendered front to back (prevent overdraw).
         *
         * @param a The first submesh
         * @param b The second submesh
         * @returns The result of the comparison
         */
        RenderingGroup.frontToBackSortCompare = function (a, b) {
            // Then distance to camera
            if (a._distanceToCamera < b._distanceToCamera) {
                return -1;
            }
            if (a._distanceToCamera > b._distanceToCamera) {
                return 1;
            }
            return 0;
        };
        /**
         * Resets the different lists of submeshes to prepare a new frame.
         */
        RenderingGroup.prototype.prepare = function () {
            this._opaqueSubMeshes.reset();
            this._transparentSubMeshes.reset();
            this._alphaTestSubMeshes.reset();
        };
        /**
         * Inserts the submesh in its correct queue depending on its material.
         * @param subMesh The submesh to dispatch
         */
        RenderingGroup.prototype.dispatch = function (subMesh) {
            var material = subMesh.getMaterial();
            var mesh = subMesh.getMesh();
            if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
                this._transparentSubMeshes.push(subMesh);
            }
            else if (material.needAlphaTesting()) {
                this._alphaTestSubMeshes.push(subMesh);
            }
            else {
                this._opaqueSubMeshes.push(subMesh); // Opaque
            }
        };
        return RenderingGroup;
    }());
    BABYLON.RenderingGroup = RenderingGroup;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.renderingGroup.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var PointerEventTypes = (function () {
        function PointerEventTypes() {
        }
        Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
            get: function () {
                return PointerEventTypes._POINTERDOWN;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PointerEventTypes, "POINTERUP", {
            get: function () {
                return PointerEventTypes._POINTERUP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
            get: function () {
                return PointerEventTypes._POINTERMOVE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
            get: function () {
                return PointerEventTypes._POINTERWHEEL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PointerEventTypes, "POINTERPICK", {
            get: function () {
                return PointerEventTypes._POINTERPICK;
            },
            enumerable: true,
            configurable: true
        });
        PointerEventTypes._POINTERDOWN = 0x01;
        PointerEventTypes._POINTERUP = 0x02;
        PointerEventTypes._POINTERMOVE = 0x04;
        PointerEventTypes._POINTERWHEEL = 0x08;
        PointerEventTypes._POINTERPICK = 0x10;
        return PointerEventTypes;
    }());
    BABYLON.PointerEventTypes = PointerEventTypes;
    var PointerInfoBase = (function () {
        function PointerInfoBase(type, event) {
            this.type = type;
            this.event = event;
        }
        return PointerInfoBase;
    }());
    BABYLON.PointerInfoBase = PointerInfoBase;
    /**
     * This class is used to store pointer related info for the onPrePointerObservable event.
     * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
     */
    var PointerInfoPre = (function (_super) {
        __extends(PointerInfoPre, _super);
        function PointerInfoPre(type, event, localX, localY) {
            _super.call(this, type, event);
            this.skipOnPointerObservable = false;
            this.localPosition = new BABYLON.Vector2(localX, localY);
        }
        return PointerInfoPre;
    }(PointerInfoBase));
    BABYLON.PointerInfoPre = PointerInfoPre;
    /**
     * This type contains all the data related to a pointer event in Babylon.js.
     * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
     */
    var PointerInfo = (function (_super) {
        __extends(PointerInfo, _super);
        function PointerInfo(type, event, pickInfo) {
            _super.call(this, type, event);
            this.pickInfo = pickInfo;
        }
        return PointerInfo;
    }(PointerInfoBase));
    BABYLON.PointerInfo = PointerInfo;
    /**
     * This class is used by the onRenderingGroupObservable
     */
    var RenderingGroupInfo = (function () {
        function RenderingGroupInfo() {
        }
        /**
         * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
         * This stage will be fired no matter what
         */
        RenderingGroupInfo.STAGE_PRECLEAR = 1;
        /**
         * Called before opaque object are rendered.
         * This stage will be fired only if there's 3D Opaque content to render
         */
        RenderingGroupInfo.STAGE_PREOPAQUE = 2;
        /**
         * Called after the opaque objects are rendered and before the transparent ones
         * This stage will be fired only if there's 3D transparent content to render
         */
        RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
        /**
         * Called after the transparent object are rendered, last hook of the renderingGroup phase
         * This stage will be fired no matter what
         */
        RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
        return RenderingGroupInfo;
    }());
    BABYLON.RenderingGroupInfo = RenderingGroupInfo;
    /**
     * Represents a scene to be rendered by the engine.
     * @see http://doc.babylonjs.com/page.php?p=21911
     */
    var Scene = (function () {
        /**
         * @constructor
         * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
         */
        function Scene(engine) {
            // Members
            this.autoClear = true;
            this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
            this.ambientColor = new BABYLON.Color3(0, 0, 0);
            this.forceWireframe = false;
            this.forcePointsCloud = false;
            this.forceShowBoundingBoxes = false;
            this.animationsEnabled = true;
            this.constantlyUpdateMeshUnderPointer = false;
            this.useRightHandedSystem = false;
            this.hoverCursor = "pointer";
            // Metadata
            this.metadata = null;
            // Events
            /**
            * An event triggered when the scene is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the scene
            * @type {BABYLON.Observable}
            */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the scene
            * @type {BABYLON.Observable}
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered when the scene is ready
            * @type {BABYLON.Observable}
            */
            this.onReadyObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering a camera
            * @type {BABYLON.Observable}
            */
            this.onBeforeCameraRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering a camera
            * @type {BABYLON.Observable}
            */
            this.onAfterCameraRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered when a camera is created
            * @type {BABYLON.Observable}
            */
            this.onNewCameraAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a camera is removed
            * @type {BABYLON.Observable}
            */
            this.onCameraRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a light is created
            * @type {BABYLON.Observable}
            */
            this.onNewLightAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a light is removed
            * @type {BABYLON.Observable}
            */
            this.onLightRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a geometry is created
            * @type {BABYLON.Observable}
            */
            this.onNewGeometryAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a geometry is removed
            * @type {BABYLON.Observable}
            */
            this.onGeometryRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a mesh is created
            * @type {BABYLON.Observable}
            */
            this.onNewMeshAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a mesh is removed
            * @type {BABYLON.Observable}
            */
            this.onMeshRemovedObservable = new BABYLON.Observable();
            /**
             * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
             * The RenderinGroupInfo class contains all the information about the context in which the observable is called
             * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
             */
            this.onRenderingGroupObservable = new BABYLON.Observable();
            // Animations
            this.animations = [];
            /**
             * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
             * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
             */
            this.onPrePointerObservable = new BABYLON.Observable();
            /**
             * Observable event triggered each time an input event is received from the rendering canvas
             */
            this.onPointerObservable = new BABYLON.Observable();
            this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
            this._startingPointerPosition = new BABYLON.Vector2(0, 0);
            this._startingPointerTime = 0;
            // Fog
            /**
            * is fog enabled on this scene.
            * @type {boolean}
            */
            this.fogEnabled = true;
            this.fogMode = Scene.FOGMODE_NONE;
            this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
            this.fogDensity = 0.1;
            this.fogStart = 0;
            this.fogEnd = 1000.0;
            // Lights
            /**
            * is shadow enabled on this scene.
            * @type {boolean}
            */
            this.shadowsEnabled = true;
            /**
            * is light enabled on this scene.
            * @type {boolean}
            */
            this.lightsEnabled = true;
            /**
            * All of the lights added to this scene.
            * @see BABYLON.Light
            * @type {BABYLON.Light[]}
            */
            this.lights = new Array();
            // Cameras
            /**
            * All of the cameras added to this scene.
            * @see BABYLON.Camera
            * @type {BABYLON.Camera[]}
            */
            this.cameras = new Array();
            this.activeCameras = new Array();
            // Meshes
            /**
            * All of the (abstract) meshes added to this scene.
            * @see BABYLON.AbstractMesh
            * @type {BABYLON.AbstractMesh[]}
            */
            this.meshes = new Array();
            // Geometries
            this._geometries = new Array();
            this.materials = new Array();
            this.multiMaterials = new Array();
            // Textures
            this.texturesEnabled = true;
            this.textures = new Array();
            // Particles
            this.particlesEnabled = true;
            this.particleSystems = new Array();
            // Sprites
            this.spritesEnabled = true;
            this.spriteManagers = new Array();
            // Layers
            this.layers = new Array();
            this.highlightLayers = new Array();
            // Skeletons
            this.skeletonsEnabled = true;
            this.skeletons = new Array();
            // Lens flares
            this.lensFlaresEnabled = true;
            this.lensFlareSystems = new Array();
            // Collisions
            this.collisionsEnabled = true;
            this.gravity = new BABYLON.Vector3(0, -9.807, 0);
            // Postprocesses
            this.postProcessesEnabled = true;
            // Customs render targets
            this.renderTargetsEnabled = true;
            this.dumpNextRenderTargets = false;
            this.customRenderTargets = new Array();
            // Imported meshes
            this.importedMeshesFiles = new Array();
            // Probes
            this.probesEnabled = true;
            this.reflectionProbes = new Array();
            this._actionManagers = new Array();
            this._meshesForIntersections = new BABYLON.SmartArray(256);
            // Procedural textures
            this.proceduralTexturesEnabled = true;
            this._proceduralTextures = new Array();
            this.soundTracks = new Array();
            this._audioEnabled = true;
            this._headphone = false;
            // Performance counters
            this._totalMeshesCounter = new BABYLON.PerfCounter();
            this._totalLightsCounter = new BABYLON.PerfCounter();
            this._totalMaterialsCounter = new BABYLON.PerfCounter();
            this._totalTexturesCounter = new BABYLON.PerfCounter();
            this._totalVertices = new BABYLON.PerfCounter();
            this._activeIndices = new BABYLON.PerfCounter();
            this._activeParticles = new BABYLON.PerfCounter();
            this._lastFrameDuration = new BABYLON.PerfCounter();
            this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
            this._renderTargetsDuration = new BABYLON.PerfCounter();
            this._particlesDuration = new BABYLON.PerfCounter();
            this._renderDuration = new BABYLON.PerfCounter();
            this._spritesDuration = new BABYLON.PerfCounter();
            this._activeBones = new BABYLON.PerfCounter();
            this._renderId = 0;
            this._executeWhenReadyTimeoutId = -1;
            this._intermediateRendering = false;
            this._toBeDisposed = new BABYLON.SmartArray(256);
            this._pendingData = []; //ANY
            this._activeMeshes = new BABYLON.SmartArray(256);
            this._processedMaterials = new BABYLON.SmartArray(256);
            this._renderTargets = new BABYLON.SmartArray(256);
            this._activeParticleSystems = new BABYLON.SmartArray(256);
            this._activeSkeletons = new BABYLON.SmartArray(32);
            this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
            this._activeAnimatables = new Array();
            this._transformMatrix = BABYLON.Matrix.Zero();
            this._edgesRenderers = new BABYLON.SmartArray(16);
            this._uniqueIdCounter = 0;
            this._engine = engine;
            engine.scenes.push(this);
            this._externalData = new BABYLON.StringDictionary();
            this._uid = null;
            this._renderingManager = new BABYLON.RenderingManager(this);
            this.postProcessManager = new BABYLON.PostProcessManager(this);
            this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
            this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
            if (BABYLON.OutlineRenderer) {
                this._outlineRenderer = new BABYLON.OutlineRenderer(this);
            }
            this.attachControl();
            if (BABYLON.SoundTrack) {
                this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
            }
            //simplification queue
            if (BABYLON.SimplificationQueue) {
                this.simplificationQueue = new BABYLON.SimplificationQueue();
            }
            //collision coordinator initialization. For now legacy per default.
            this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
        }
        Object.defineProperty(Scene, "FOGMODE_NONE", {
            get: function () {
                return Scene._FOGMODE_NONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene, "FOGMODE_EXP", {
            get: function () {
                return Scene._FOGMODE_EXP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene, "FOGMODE_EXP2", {
            get: function () {
                return Scene._FOGMODE_EXP2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene, "FOGMODE_LINEAR", {
            get: function () {
                return Scene._FOGMODE_LINEAR;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "beforeRender", {
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "afterRender", {
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "beforeCameraRender", {
            set: function (callback) {
                if (this._onBeforeCameraRenderObserver) {
                    this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
                }
                this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "afterCameraRender", {
            set: function (callback) {
                if (this._onAfterCameraRenderObserver) {
                    this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
                }
                this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
            get: function () {
                return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "defaultMaterial", {
            get: function () {
                if (!this._defaultMaterial) {
                    this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
                }
                return this._defaultMaterial;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "debugLayer", {
            // Properties
            get: function () {
                if (!this._debugLayer) {
                    this._debugLayer = new BABYLON.DebugLayer(this);
                }
                return this._debugLayer;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "workerCollisions", {
            get: function () {
                return this._workerCollisions;
            },
            set: function (enabled) {
                enabled = (enabled && !!Worker);
                this._workerCollisions = enabled;
                if (this.collisionCoordinator) {
                    this.collisionCoordinator.destroy();
                }
                this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
                this.collisionCoordinator.init(this);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "SelectionOctree", {
            get: function () {
                return this._selectionOctree;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "meshUnderPointer", {
            /**
             * The mesh that is currently under the pointer.
             * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
             */
            get: function () {
                return this._pointerOverMesh;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "pointerX", {
            /**
             * Current on-screen X position of the pointer
             * @return {number} X position of the pointer
             */
            get: function () {
                return this._pointerX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "pointerY", {
            /**
             * Current on-screen Y position of the pointer
             * @return {number} Y position of the pointer
             */
            get: function () {
                return this._pointerY;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getCachedMaterial = function () {
            return this._cachedMaterial;
        };
        Scene.prototype.getBoundingBoxRenderer = function () {
            return this._boundingBoxRenderer;
        };
        Scene.prototype.getOutlineRenderer = function () {
            return this._outlineRenderer;
        };
        Scene.prototype.getEngine = function () {
            return this._engine;
        };
        Scene.prototype.getTotalVertices = function () {
            return this._totalVertices.current;
        };
        Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
            get: function () {
                return this._totalVertices;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getActiveIndices = function () {
            return this._activeIndices.current;
        };
        Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
            get: function () {
                return this._activeIndices;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getActiveParticles = function () {
            return this._activeParticles.current;
        };
        Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
            get: function () {
                return this._activeParticles;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getActiveBones = function () {
            return this._activeBones.current;
        };
        Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
            get: function () {
                return this._activeBones;
            },
            enumerable: true,
            configurable: true
        });
        // Stats
        Scene.prototype.getLastFrameDuration = function () {
            return this._lastFrameDuration.current;
        };
        Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
            get: function () {
                return this._lastFrameDuration;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getEvaluateActiveMeshesDuration = function () {
            return this._evaluateActiveMeshesDuration.current;
        };
        Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
            get: function () {
                return this._evaluateActiveMeshesDuration;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getActiveMeshes = function () {
            return this._activeMeshes;
        };
        Scene.prototype.getRenderTargetsDuration = function () {
            return this._renderTargetsDuration.current;
        };
        Scene.prototype.getRenderDuration = function () {
            return this._renderDuration.current;
        };
        Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
            get: function () {
                return this._renderDuration;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getParticlesDuration = function () {
            return this._particlesDuration.current;
        };
        Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
            get: function () {
                return this._particlesDuration;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getSpritesDuration = function () {
            return this._spritesDuration.current;
        };
        Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
            get: function () {
                return this._spritesDuration;
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype.getAnimationRatio = function () {
            return this._animationRatio;
        };
        Scene.prototype.getRenderId = function () {
            return this._renderId;
        };
        Scene.prototype.incrementRenderId = function () {
            this._renderId++;
        };
        Scene.prototype._updatePointerPosition = function (evt) {
            var canvasRect = this._engine.getRenderingCanvasClientRect();
            this._pointerX = evt.clientX - canvasRect.left;
            this._pointerY = evt.clientY - canvasRect.top;
            this._unTranslatedPointerX = this._pointerX;
            this._unTranslatedPointerY = this._pointerY;
            if (this.cameraToUseForPointers) {
                this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
                this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
            }
        };
        // Pointers handling
        /**
        * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
        * @param attachUp defines if you want to attach events to pointerup
        * @param attachDown defines if you want to attach events to pointerdown
        * @param attachMove defines if you want to attach events to pointermove
        */
        Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
            var _this = this;
            if (attachUp === void 0) { attachUp = true; }
            if (attachDown === void 0) { attachDown = true; }
            if (attachMove === void 0) { attachMove = true; }
            var spritePredicate = function (sprite) {
                return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
            };
            this._onPointerMove = function (evt) {
                _this._updatePointerPosition(evt);
                // PreObservable support
                if (_this.onPrePointerObservable.hasObservers()) {
                    var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
                    var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
                    _this.onPrePointerObservable.notifyObservers(pi, type);
                    if (pi.skipOnPointerObservable) {
                        return;
                    }
                }
                if (!_this.cameraToUseForPointers && !_this.activeCamera) {
                    return;
                }
                var canvas = _this._engine.getRenderingCanvas();
                if (!_this.pointerMovePredicate) {
                    _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
                }
                // Meshes
                var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
                if (pickResult.hit && pickResult.pickedMesh) {
                    _this.setPointerOverSprite(null);
                    _this.setPointerOverMesh(pickResult.pickedMesh);
                    if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
                        if (_this._pointerOverMesh.actionManager.hoverCursor) {
                            canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
                        }
                        else {
                            canvas.style.cursor = _this.hoverCursor;
                        }
                    }
                    else {
                        canvas.style.cursor = "";
                    }
                }
                else {
                    _this.setPointerOverMesh(null);
                    // Sprites
                    pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
                    if (pickResult.hit && pickResult.pickedSprite) {
                        _this.setPointerOverSprite(pickResult.pickedSprite);
                        if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
                            canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
                        }
                        else {
                            canvas.style.cursor = _this.hoverCursor;
                        }
                    }
                    else {
                        _this.setPointerOverSprite(null);
                        // Restore pointer
                        canvas.style.cursor = "";
                    }
                }
                if (_this.onPointerMove) {
                    _this.onPointerMove(evt, pickResult);
                }
                if (_this.onPointerObservable.hasObservers()) {
                    var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
                    var pi = new PointerInfo(type, evt, pickResult);
                    _this.onPointerObservable.notifyObservers(pi, type);
                }
            };
            this._onPointerDown = function (evt) {
                _this._updatePointerPosition(evt);
                // PreObservable support
                if (_this.onPrePointerObservable.hasObservers()) {
                    var type = PointerEventTypes.POINTERDOWN;
                    var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
                    _this.onPrePointerObservable.notifyObservers(pi, type);
                    if (pi.skipOnPointerObservable) {
                        return;
                    }
                }
                if (!_this.cameraToUseForPointers && !_this.activeCamera) {
                    return;
                }
                _this._startingPointerPosition.x = _this._pointerX;
                _this._startingPointerPosition.y = _this._pointerY;
                _this._startingPointerTime = new Date().getTime();
                if (!_this.pointerDownPredicate) {
                    _this.pointerDownPredicate = function (mesh) {
                        return mesh.isPickable && mesh.isVisible && mesh.isReady();
                    };
                }
                // Meshes
                _this._pickedDownMesh = null;
                var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
                if (pickResult.hit && pickResult.pickedMesh) {
                    if (pickResult.pickedMesh.actionManager) {
                        _this._pickedDownMesh = pickResult.pickedMesh;
                        if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
                            switch (evt.button) {
                                case 0:
                                    pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                    break;
                                case 1:
                                    pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                    break;
                                case 2:
                                    pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                    break;
                            }
                            if (pickResult.pickedMesh.actionManager) {
                                pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                            }
                        }
                        if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
                            var that = _this;
                            window.setTimeout(function () {
                                var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
                                if (pickResult.hit && pickResult.pickedMesh) {
                                    if (pickResult.pickedMesh.actionManager) {
                                        if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
                                            that._startingPointerTime = 0;
                                            pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                        }
                                    }
                                }
                            }, BABYLON.ActionManager.LongPressDelay);
                        }
                    }
                }
                if (_this.onPointerDown) {
                    _this.onPointerDown(evt, pickResult);
                }
                if (_this.onPointerObservable.hasObservers()) {
                    var type = PointerEventTypes.POINTERDOWN;
                    var pi = new PointerInfo(type, evt, pickResult);
                    _this.onPointerObservable.notifyObservers(pi, type);
                }
                // Sprites
                _this._pickedDownSprite = null;
                if (_this.spriteManagers.length > 0) {
                    pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
                    if (pickResult.hit && pickResult.pickedSprite) {
                        if (pickResult.pickedSprite.actionManager) {
                            _this._pickedDownSprite = pickResult.pickedSprite;
                            switch (evt.button) {
                                case 0:
                                    pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
                                    break;
                                case 1:
                                    pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
                                    break;
                                case 2:
                                    pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
                                    break;
                            }
                            if (pickResult.pickedSprite.actionManager) {
                                pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
                            }
                        }
                    }
                }
            };
            this._onPointerUp = function (evt) {
                _this._updatePointerPosition(evt);
                // PreObservable support
                if (_this.onPrePointerObservable.hasObservers()) {
                    var type = PointerEventTypes.POINTERUP;
                    var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
                    _this.onPrePointerObservable.notifyObservers(pi, type);
                    if (pi.skipOnPointerObservable) {
                        return;
                    }
                }
                if (!_this.cameraToUseForPointers && !_this.activeCamera) {
                    return;
                }
                if (!_this.pointerUpPredicate) {
                    _this.pointerUpPredicate = function (mesh) {
                        return mesh.isPickable && mesh.isVisible && mesh.isReady();
                    };
                }
                // Meshes
                var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
                if (pickResult.hit && pickResult.pickedMesh) {
                    if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
                        if (_this.onPointerPick) {
                            _this.onPointerPick(evt, pickResult);
                        }
                        if (_this.onPointerObservable.hasObservers()) {
                            var type = PointerEventTypes.POINTERPICK;
                            var pi = new PointerInfo(type, evt, pickResult);
                            _this.onPointerObservable.notifyObservers(pi, type);
                        }
                    }
                    if (pickResult.pickedMesh.actionManager) {
                        pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                        if (pickResult.pickedMesh.actionManager) {
                            if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
                                pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                            }
                        }
                    }
                }
                if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
                    _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
                }
                if (_this.onPointerUp) {
                    _this.onPointerUp(evt, pickResult);
                }
                if (_this.onPointerObservable.hasObservers()) {
                    var type = PointerEventTypes.POINTERUP;
                    var pi = new PointerInfo(type, evt, pickResult);
                    _this.onPointerObservable.notifyObservers(pi, type);
                }
                _this._startingPointerTime = 0;
                // Sprites
                if (_this.spriteManagers.length > 0) {
                    pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
                    if (pickResult.hit && pickResult.pickedSprite) {
                        if (pickResult.pickedSprite.actionManager) {
                            pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
                            if (pickResult.pickedSprite.actionManager) {
                                if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
                                    pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
                                }
                            }
                        }
                    }
                    if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
                        _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
                    }
                }
            };
            this._onKeyDown = function (evt) {
                if (_this.actionManager) {
                    _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
                }
            };
            this._onKeyUp = function (evt) {
                if (_this.actionManager) {
                    _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
                }
            };
            var eventPrefix = BABYLON.Tools.GetPointerPrefix();
            var canvas = this._engine.getRenderingCanvas();
            if (attachMove) {
                canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
                // Wheel
                canvas.addEventListener('mousewheel', this._onPointerMove, false);
                canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
            }
            if (attachDown) {
                canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
            }
            if (attachUp) {
                canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
            }
            canvas.tabIndex = 1;
            canvas.addEventListener("keydown", this._onKeyDown, false);
            canvas.addEventListener("keyup", this._onKeyUp, false);
        };
        Scene.prototype.detachControl = function () {
            var eventPrefix = BABYLON.Tools.GetPointerPrefix();
            var canvas = this._engine.getRenderingCanvas();
            canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
            canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
            canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
            // Wheel
            canvas.removeEventListener('mousewheel', this._onPointerMove);
            canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
            canvas.removeEventListener("keydown", this._onKeyDown);
            canvas.removeEventListener("keyup", this._onKeyUp);
        };
        // Ready
        Scene.prototype.isReady = function () {
            if (this._pendingData.length > 0) {
                return false;
            }
            var index;
            for (index = 0; index < this._geometries.length; index++) {
                var geometry = this._geometries[index];
                if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                    return false;
                }
            }
            for (index = 0; index < this.meshes.length; index++) {
                var mesh = this.meshes[index];
                if (!mesh.isReady()) {
                    return false;
                }
                var mat = mesh.material;
                if (mat) {
                    if (!mat.isReady(mesh)) {
                        return false;
                    }
                }
            }
            return true;
        };
        Scene.prototype.resetCachedMaterial = function () {
            this._cachedMaterial = null;
        };
        Scene.prototype.registerBeforeRender = function (func) {
            this.onBeforeRenderObservable.add(func);
        };
        Scene.prototype.unregisterBeforeRender = function (func) {
            this.onBeforeRenderObservable.removeCallback(func);
        };
        Scene.prototype.registerAfterRender = function (func) {
            this.onAfterRenderObservable.add(func);
        };
        Scene.prototype.unregisterAfterRender = function (func) {
            this.onAfterRenderObservable.removeCallback(func);
        };
        Scene.prototype._addPendingData = function (data) {
            this._pendingData.push(data);
        };
        Scene.prototype._removePendingData = function (data) {
            var index = this._pendingData.indexOf(data);
            if (index !== -1) {
                this._pendingData.splice(index, 1);
            }
        };
        Scene.prototype.getWaitingItemsCount = function () {
            return this._pendingData.length;
        };
        /**
         * Registers a function to be executed when the scene is ready.
         * @param {Function} func - the function to be executed.
         */
        Scene.prototype.executeWhenReady = function (func) {
            var _this = this;
            this.onReadyObservable.add(func);
            if (this._executeWhenReadyTimeoutId !== -1) {
                return;
            }
            this._executeWhenReadyTimeoutId = setTimeout(function () {
                _this._checkIsReady();
            }, 150);
        };
        Scene.prototype._checkIsReady = function () {
            var _this = this;
            if (this.isReady()) {
                this.onReadyObservable.notifyObservers(this);
                this.onReadyObservable.clear();
                this._executeWhenReadyTimeoutId = -1;
                return;
            }
            this._executeWhenReadyTimeoutId = setTimeout(function () {
                _this._checkIsReady();
            }, 150);
        };
        // Animations
        /**
         * Will start the animation sequence of a given target
         * @param target - the target
         * @param {number} from - from which frame should animation start
         * @param {number} to - till which frame should animation run.
         * @param {boolean} [loop] - should the animation loop
         * @param {number} [speedRatio] - the speed in which to run the animation
         * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
         * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
         * @return {BABYLON.Animatable} the animatable object created for this animation
         * @see BABYLON.Animatable
         * @see http://doc.babylonjs.com/page.php?p=22081
         */
        Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
            if (speedRatio === void 0) { speedRatio = 1.0; }
            this.stopAnimation(target);
            if (!animatable) {
                animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
            }
            // Local animations
            if (target.animations) {
                animatable.appendAnimations(target, target.animations);
            }
            // Children animations
            if (target.getAnimatables) {
                var animatables = target.getAnimatables();
                for (var index = 0; index < animatables.length; index++) {
                    this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
                }
            }
            animatable.reset();
            return animatable;
        };
        Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
            if (speedRatio === undefined) {
                speedRatio = 1.0;
            }
            var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
            return animatable;
        };
        Scene.prototype.getAnimatableByTarget = function (target) {
            for (var index = 0; index < this._activeAnimatables.length; index++) {
                if (this._activeAnimatables[index].target === target) {
                    return this._activeAnimatables[index];
                }
            }
            return null;
        };
        Object.defineProperty(Scene.prototype, "Animatables", {
            get: function () {
                return this._activeAnimatables;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Will stop the animation of the given target
         * @param target - the target
         * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
         * @see beginAnimation
         */
        Scene.prototype.stopAnimation = function (target, animationName) {
            var animatable = this.getAnimatableByTarget(target);
            if (animatable) {
                animatable.stop(animationName);
            }
        };
        Scene.prototype._animate = function () {
            if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
                return;
            }
            if (!this._animationStartDate) {
                if (this._pendingData.length > 0) {
                    return;
                }
                this._animationStartDate = BABYLON.Tools.Now;
            }
            // Getting time
            var now = BABYLON.Tools.Now;
            var delay = now - this._animationStartDate;
            for (var index = 0; index < this._activeAnimatables.length; index++) {
                this._activeAnimatables[index]._animate(delay);
            }
        };
        // Matrix
        Scene.prototype.getViewMatrix = function () {
            return this._viewMatrix;
        };
        Scene.prototype.getProjectionMatrix = function () {
            return this._projectionMatrix;
        };
        Scene.prototype.getTransformMatrix = function () {
            return this._transformMatrix;
        };
        Scene.prototype.setTransformMatrix = function (view, projection) {
            this._viewMatrix = view;
            this._projectionMatrix = projection;
            this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
            // Update frustum
            if (!this._frustumPlanes) {
                this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
            }
            else {
                BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
            }
        };
        // Methods
        Scene.prototype.addMesh = function (newMesh) {
            newMesh.uniqueId = this._uniqueIdCounter++;
            var position = this.meshes.push(newMesh);
            //notify the collision coordinator
            this.collisionCoordinator.onMeshAdded(newMesh);
            this.onNewMeshAddedObservable.notifyObservers(newMesh);
        };
        Scene.prototype.removeMesh = function (toRemove) {
            var index = this.meshes.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if mesh found 
                this.meshes.splice(index, 1);
            }
            //notify the collision coordinator
            this.collisionCoordinator.onMeshRemoved(toRemove);
            this.onMeshRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        Scene.prototype.removeSkeleton = function (toRemove) {
            var index = this.skeletons.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if mesh found 
                this.skeletons.splice(index, 1);
            }
            return index;
        };
        Scene.prototype.removeLight = function (toRemove) {
            var index = this.lights.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if mesh found 
                this.lights.splice(index, 1);
            }
            this.onLightRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        Scene.prototype.removeCamera = function (toRemove) {
            var index = this.cameras.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if mesh found 
                this.cameras.splice(index, 1);
            }
            // Remove from activeCameras
            var index2 = this.activeCameras.indexOf(toRemove);
            if (index2 !== -1) {
                // Remove from the scene if mesh found
                this.activeCameras.splice(index2, 1);
            }
            // Reset the activeCamera
            if (this.activeCamera === toRemove) {
                if (this.cameras.length > 0) {
                    this.activeCamera = this.cameras[0];
                }
                else {
                    this.activeCamera = null;
                }
            }
            this.onCameraRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        Scene.prototype.addLight = function (newLight) {
            newLight.uniqueId = this._uniqueIdCounter++;
            var position = this.lights.push(newLight);
            this.onNewLightAddedObservable.notifyObservers(newLight);
        };
        Scene.prototype.addCamera = function (newCamera) {
            newCamera.uniqueId = this._uniqueIdCounter++;
            var position = this.cameras.push(newCamera);
            this.onNewCameraAddedObservable.notifyObservers(newCamera);
        };
        /**
         * Switch active camera
         * @param {Camera} newCamera - new active camera
         * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
         */
        Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
            if (attachControl === void 0) { attachControl = true; }
            var canvas = this._engine.getRenderingCanvas();
            this.activeCamera.detachControl(canvas);
            this.activeCamera = newCamera;
            if (attachControl) {
                newCamera.attachControl(canvas);
            }
        };
        /**
         * sets the active camera of the scene using its ID
         * @param {string} id - the camera's ID
         * @return {BABYLON.Camera|null} the new active camera or null if none found.
         * @see activeCamera
         */
        Scene.prototype.setActiveCameraByID = function (id) {
            var camera = this.getCameraByID(id);
            if (camera) {
                this.activeCamera = camera;
                return camera;
            }
            return null;
        };
        /**
         * sets the active camera of the scene using its name
         * @param {string} name - the camera's name
         * @return {BABYLON.Camera|null} the new active camera or null if none found.
         * @see activeCamera
         */
        Scene.prototype.setActiveCameraByName = function (name) {
            var camera = this.getCameraByName(name);
            if (camera) {
                this.activeCamera = camera;
                return camera;
            }
            return null;
        };
        /**
         * get a material using its id
         * @param {string} the material's ID
         * @return {BABYLON.Material|null} the material or null if none found.
         */
        Scene.prototype.getMaterialByID = function (id) {
            for (var index = 0; index < this.materials.length; index++) {
                if (this.materials[index].id === id) {
                    return this.materials[index];
                }
            }
            return null;
        };
        /**
         * get a material using its name
         * @param {string} the material's name
         * @return {BABYLON.Material|null} the material or null if none found.
         */
        Scene.prototype.getMaterialByName = function (name) {
            for (var index = 0; index < this.materials.length; index++) {
                if (this.materials[index].name === name) {
                    return this.materials[index];
                }
            }
            return null;
        };
        Scene.prototype.getLensFlareSystemByName = function (name) {
            for (var index = 0; index < this.lensFlareSystems.length; index++) {
                if (this.lensFlareSystems[index].name === name) {
                    return this.lensFlareSystems[index];
                }
            }
            return null;
        };
        Scene.prototype.getLensFlareSystemByID = function (id) {
            for (var index = 0; index < this.lensFlareSystems.length; index++) {
                if (this.lensFlareSystems[index].id === id) {
                    return this.lensFlareSystems[index];
                }
            }
            return null;
        };
        Scene.prototype.getCameraByID = function (id) {
            for (var index = 0; index < this.cameras.length; index++) {
                if (this.cameras[index].id === id) {
                    return this.cameras[index];
                }
            }
            return null;
        };
        Scene.prototype.getCameraByUniqueID = function (uniqueId) {
            for (var index = 0; index < this.cameras.length; index++) {
                if (this.cameras[index].uniqueId === uniqueId) {
                    return this.cameras[index];
                }
            }
            return null;
        };
        /**
         * get a camera using its name
         * @param {string} the camera's name
         * @return {BABYLON.Camera|null} the camera or null if none found.
         */
        Scene.prototype.getCameraByName = function (name) {
            for (var index = 0; index < this.cameras.length; index++) {
                if (this.cameras[index].name === name) {
                    return this.cameras[index];
                }
            }
            return null;
        };
        /**
         * get a bone using its id
         * @param {string} the bone's id
         * @return {BABYLON.Bone|null} the bone or null if not found
         */
        Scene.prototype.getBoneByID = function (id) {
            for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
                var skeleton = this.skeletons[skeletonIndex];
                for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
                    if (skeleton.bones[boneIndex].id === id) {
                        return skeleton.bones[boneIndex];
                    }
                }
            }
            return null;
        };
        /**
        * get a bone using its id
        * @param {string} the bone's name
        * @return {BABYLON.Bone|null} the bone or null if not found
        */
        Scene.prototype.getBoneByName = function (name) {
            for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
                var skeleton = this.skeletons[skeletonIndex];
                for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
                    if (skeleton.bones[boneIndex].name === name) {
                        return skeleton.bones[boneIndex];
                    }
                }
            }
            return null;
        };
        /**
         * get a light node using its name
         * @param {string} the light's name
         * @return {BABYLON.Light|null} the light or null if none found.
         */
        Scene.prototype.getLightByName = function (name) {
            for (var index = 0; index < this.lights.length; index++) {
                if (this.lights[index].name === name) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * get a light node using its ID
         * @param {string} the light's id
         * @return {BABYLON.Light|null} the light or null if none found.
         */
        Scene.prototype.getLightByID = function (id) {
            for (var index = 0; index < this.lights.length; index++) {
                if (this.lights[index].id === id) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * get a light node using its scene-generated unique ID
         * @param {number} the light's unique id
         * @return {BABYLON.Light|null} the light or null if none found.
         */
        Scene.prototype.getLightByUniqueID = function (uniqueId) {
            for (var index = 0; index < this.lights.length; index++) {
                if (this.lights[index].uniqueId === uniqueId) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * get a particle system by id
         * @param id {number} the particle system id
         * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
         */
        Scene.prototype.getParticleSystemByID = function (id) {
            for (var index = 0; index < this.particleSystems.length; index++) {
                if (this.particleSystems[index].id === id) {
                    return this.particleSystems[index];
                }
            }
            return null;
        };
        /**
         * get a geometry using its ID
         * @param {string} the geometry's id
         * @return {BABYLON.Geometry|null} the geometry or null if none found.
         */
        Scene.prototype.getGeometryByID = function (id) {
            for (var index = 0; index < this._geometries.length; index++) {
                if (this._geometries[index].id === id) {
                    return this._geometries[index];
                }
            }
            return null;
        };
        /**
         * add a new geometry to this scene.
         * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
         * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
         * @return {boolean} was the geometry added or not
         */
        Scene.prototype.pushGeometry = function (geometry, force) {
            if (!force && this.getGeometryByID(geometry.id)) {
                return false;
            }
            this._geometries.push(geometry);
            //notify the collision coordinator
            this.collisionCoordinator.onGeometryAdded(geometry);
            this.onNewGeometryAddedObservable.notifyObservers(geometry);
            return true;
        };
        /**
         * Removes an existing geometry
         * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
         * @return {boolean} was the geometry removed or not
         */
        Scene.prototype.removeGeometry = function (geometry) {
            var index = this._geometries.indexOf(geometry);
            if (index > -1) {
                this._geometries.splice(index, 1);
                //notify the collision coordinator
                this.collisionCoordinator.onGeometryDeleted(geometry);
                this.onGeometryRemovedObservable.notifyObservers(geometry);
                return true;
            }
            return false;
        };
        Scene.prototype.getGeometries = function () {
            return this._geometries;
        };
        /**
         * Get the first added mesh found of a given ID
         * @param {string} id - the id to search for
         * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
         */
        Scene.prototype.getMeshByID = function (id) {
            for (var index = 0; index < this.meshes.length; index++) {
                if (this.meshes[index].id === id) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        Scene.prototype.getMeshesByID = function (id) {
            return this.meshes.filter(function (m) {
                return m.id === id;
            });
        };
        /**
         * Get a mesh with its auto-generated unique id
         * @param {number} uniqueId - the unique id to search for
         * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
         */
        Scene.prototype.getMeshByUniqueID = function (uniqueId) {
            for (var index = 0; index < this.meshes.length; index++) {
                if (this.meshes[index].uniqueId === uniqueId) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        /**
         * Get a the last added mesh found of a given ID
         * @param {string} id - the id to search for
         * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
         */
        Scene.prototype.getLastMeshByID = function (id) {
            for (var index = this.meshes.length - 1; index >= 0; index--) {
                if (this.meshes[index].id === id) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        /**
         * Get a the last added node (Mesh, Camera, Light) found of a given ID
         * @param {string} id - the id to search for
         * @return {BABYLON.Node|null} the node found or null if not found at all.
         */
        Scene.prototype.getLastEntryByID = function (id) {
            var index;
            for (index = this.meshes.length - 1; index >= 0; index--) {
                if (this.meshes[index].id === id) {
                    return this.meshes[index];
                }
            }
            for (index = this.cameras.length - 1; index >= 0; index--) {
                if (this.cameras[index].id === id) {
                    return this.cameras[index];
                }
            }
            for (index = this.lights.length - 1; index >= 0; index--) {
                if (this.lights[index].id === id) {
                    return this.lights[index];
                }
            }
            return null;
        };
        Scene.prototype.getNodeByID = function (id) {
            var mesh = this.getMeshByID(id);
            if (mesh) {
                return mesh;
            }
            var light = this.getLightByID(id);
            if (light) {
                return light;
            }
            var camera = this.getCameraByID(id);
            if (camera) {
                return camera;
            }
            var bone = this.getBoneByID(id);
            return bone;
        };
        Scene.prototype.getNodeByName = function (name) {
            var mesh = this.getMeshByName(name);
            if (mesh) {
                return mesh;
            }
            var light = this.getLightByName(name);
            if (light) {
                return light;
            }
            var camera = this.getCameraByName(name);
            if (camera) {
                return camera;
            }
            var bone = this.getBoneByName(name);
            return bone;
        };
        Scene.prototype.getMeshByName = function (name) {
            for (var index = 0; index < this.meshes.length; index++) {
                if (this.meshes[index].name === name) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        Scene.prototype.getSoundByName = function (name) {
            var index;
            if (BABYLON.AudioEngine) {
                for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
                    if (this.mainSoundTrack.soundCollection[index].name === name) {
                        return this.mainSoundTrack.soundCollection[index];
                    }
                }
                for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
                    for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
                        if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
                            return this.soundTracks[sdIndex].soundCollection[index];
                        }
                    }
                }
            }
            return null;
        };
        Scene.prototype.getLastSkeletonByID = function (id) {
            for (var index = this.skeletons.length - 1; index >= 0; index--) {
                if (this.skeletons[index].id === id) {
                    return this.skeletons[index];
                }
            }
            return null;
        };
        Scene.prototype.getSkeletonById = function (id) {
            for (var index = 0; index < this.skeletons.length; index++) {
                if (this.skeletons[index].id === id) {
                    return this.skeletons[index];
                }
            }
            return null;
        };
        Scene.prototype.getSkeletonByName = function (name) {
            for (var index = 0; index < this.skeletons.length; index++) {
                if (this.skeletons[index].name === name) {
                    return this.skeletons[index];
                }
            }
            return null;
        };
        Scene.prototype.isActiveMesh = function (mesh) {
            return (this._activeMeshes.indexOf(mesh) !== -1);
        };
        Object.defineProperty(Scene.prototype, "uid", {
            /**
             * Return a unique id as a string which can serve as an identifier for the scene
             */
            get: function () {
                if (!this._uid) {
                    this._uid = BABYLON.Tools.RandomId();
                }
                return this._uid;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Add an externaly attached data from its key.
         * This method call will fail and return false, if such key already exists.
         * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
         * @param key the unique key that identifies the data
         * @param data the data object to associate to the key for this Engine instance
         * @return true if no such key were already present and the data was added successfully, false otherwise
         */
        Scene.prototype.addExternalData = function (key, data) {
            return this._externalData.add(key, data);
        };
        /**
         * Get an externaly attached data from its key
         * @param key the unique key that identifies the data
         * @return the associated data, if present (can be null), or undefined if not present
         */
        Scene.prototype.getExternalData = function (key) {
            return this._externalData.get(key);
        };
        /**
         * Get an externaly attached data from its key, create it using a factory if it's not already present
         * @param key the unique key that identifies the data
         * @param factory the factory that will be called to create the instance if and only if it doesn't exists
         * @return the associated data, can be null if the factory returned null.
         */
        Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
            return this._externalData.getOrAddWithFactory(key, factory);
        };
        /**
         * Remove an externaly attached data from the Engine instance
         * @param key the unique key that identifies the data
         * @return true if the data was successfully removed, false if it doesn't exist
         */
        Scene.prototype.removeExternalData = function (key) {
            return this._externalData.remove(key);
        };
        Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
            if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
                var material = subMesh.getMaterial();
                if (mesh.showSubMeshesBoundingBox) {
                    this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
                }
                if (material) {
                    // Render targets
                    if (material.getRenderTargetTextures) {
                        if (this._processedMaterials.indexOf(material) === -1) {
                            this._processedMaterials.push(material);
                            this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
                        }
                    }
                    // Dispatch
                    this._activeIndices.addCount(subMesh.indexCount, false);
                    this._renderingManager.dispatch(subMesh);
                }
            }
        };
        Scene.prototype._isInIntermediateRendering = function () {
            return this._intermediateRendering;
        };
        Scene.prototype._evaluateActiveMeshes = function () {
            this.activeCamera._activeMeshes.reset();
            this._activeMeshes.reset();
            this._renderingManager.reset();
            this._processedMaterials.reset();
            this._activeParticleSystems.reset();
            this._activeSkeletons.reset();
            this._softwareSkinnedMeshes.reset();
            this._boundingBoxRenderer.reset();
            this._edgesRenderers.reset();
            // Meshes
            var meshes;
            var len;
            if (this._selectionOctree) {
                var selection = this._selectionOctree.select(this._frustumPlanes);
                meshes = selection.data;
                len = selection.length;
            }
            else {
                len = this.meshes.length;
                meshes = this.meshes;
            }
            for (var meshIndex = 0; meshIndex < len; meshIndex++) {
                var mesh = meshes[meshIndex];
                if (mesh.isBlocked) {
                    continue;
                }
                this._totalVertices.addCount(mesh.getTotalVertices(), false);
                if (!mesh.isReady() || !mesh.isEnabled()) {
                    continue;
                }
                mesh.computeWorldMatrix();
                // Intersections
                if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
                    this._meshesForIntersections.pushNoDuplicate(mesh);
                }
                // Switch to current LOD
                var meshLOD = mesh.getLOD(this.activeCamera);
                if (!meshLOD) {
                    continue;
                }
                mesh._preActivate();
                if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
                    this._activeMeshes.push(mesh);
                    this.activeCamera._activeMeshes.push(mesh);
                    mesh._activate(this._renderId);
                    this._activeMesh(mesh, meshLOD);
                }
            }
            // Particle systems
            this._particlesDuration.beginMonitoring();
            var beforeParticlesDate = BABYLON.Tools.Now;
            if (this.particlesEnabled) {
                BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
                for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
                    var particleSystem = this.particleSystems[particleIndex];
                    if (!particleSystem.isStarted()) {
                        continue;
                    }
                    if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
                        this._activeParticleSystems.push(particleSystem);
                        particleSystem.animate();
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
            }
            this._particlesDuration.endMonitoring(false);
        };
        Scene.prototype._activeMesh = function (sourceMesh, mesh) {
            if (mesh.skeleton && this.skeletonsEnabled) {
                if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
                    mesh.skeleton.prepare();
                }
                if (!mesh.computeBonesUsingShaders) {
                    this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
                }
            }
            if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
                this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
            }
            if (sourceMesh._edgesRenderer) {
                this._edgesRenderers.push(sourceMesh._edgesRenderer);
            }
            if (mesh && mesh.subMeshes) {
                // Submeshes Octrees
                var len;
                var subMeshes;
                if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
                    var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
                    len = intersections.length;
                    subMeshes = intersections.data;
                }
                else {
                    subMeshes = mesh.subMeshes;
                    len = subMeshes.length;
                }
                for (var subIndex = 0; subIndex < len; subIndex++) {
                    var subMesh = subMeshes[subIndex];
                    this._evaluateSubMesh(subMesh, mesh);
                }
            }
        };
        Scene.prototype.updateTransformMatrix = function (force) {
            this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
        };
        Scene.prototype._renderForCamera = function (camera) {
            var engine = this._engine;
            var startTime = BABYLON.Tools.Now;
            this.activeCamera = camera;
            if (!this.activeCamera)
                throw new Error("Active camera not set");
            BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
            // Viewport
            engine.setViewport(this.activeCamera.viewport);
            // Camera
            this.resetCachedMaterial();
            this._renderId++;
            this.updateTransformMatrix();
            this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
            // Meshes
            this._evaluateActiveMeshesDuration.beginMonitoring();
            BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
            this._evaluateActiveMeshes();
            this._evaluateActiveMeshesDuration.endMonitoring(false);
            BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
            // Software skinning
            for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
                var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
                mesh.applySkeleton(mesh.skeleton);
            }
            // Render targets
            this._renderTargetsDuration.beginMonitoring();
            var needsRestoreFrameBuffer = false;
            var beforeRenderTargetDate = BABYLON.Tools.Now;
            if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
                this._intermediateRendering = true;
                BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
                for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
                    var renderTarget = this._renderTargets.data[renderIndex];
                    if (renderTarget._shouldRender()) {
                        this._renderId++;
                        var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
                        renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
                this._intermediateRendering = false;
                this._renderId++;
                needsRestoreFrameBuffer = true; // Restore back buffer
            }
            // Render HighlightLayer Texture
            var stencilState = this._engine.getStencilBuffer();
            var renderhighlights = false;
            if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
                this._intermediateRendering = true;
                for (var i = 0; i < this.highlightLayers.length; i++) {
                    var highlightLayer = this.highlightLayers[i];
                    if (highlightLayer.shouldRender() &&
                        (!highlightLayer.camera ||
                            (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
                            (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
                        renderhighlights = true;
                        var renderTarget = highlightLayer._mainTexture;
                        if (renderTarget._shouldRender()) {
                            this._renderId++;
                            renderTarget.render(false, false);
                            needsRestoreFrameBuffer = true;
                        }
                    }
                }
                this._intermediateRendering = false;
                this._renderId++;
            }
            if (needsRestoreFrameBuffer) {
                engine.restoreDefaultFramebuffer();
            }
            this._renderTargetsDuration.endMonitoring(false);
            // Prepare Frame
            this.postProcessManager._prepareFrame();
            this._renderDuration.beginMonitoring();
            // Backgrounds
            var layerIndex;
            var layer;
            if (this.layers.length) {
                engine.setDepthBuffer(false);
                for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
                    layer = this.layers[layerIndex];
                    if (layer.isBackground) {
                        layer.render();
                    }
                }
                engine.setDepthBuffer(true);
            }
            // Render
            BABYLON.Tools.StartPerformanceCounter("Main render");
            // Activate HighlightLayer stencil
            if (renderhighlights) {
                this._engine.setStencilBuffer(true);
            }
            this._renderingManager.render(null, null, true, true);
            // Restore HighlightLayer stencil
            if (renderhighlights) {
                this._engine.setStencilBuffer(stencilState);
            }
            BABYLON.Tools.EndPerformanceCounter("Main render");
            // Bounding boxes
            this._boundingBoxRenderer.render();
            // Edges
            for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
                this._edgesRenderers.data[edgesRendererIndex].render();
            }
            // Lens flares
            if (this.lensFlaresEnabled) {
                BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
                for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
                    var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
                    if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
                        lensFlareSystem.render();
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
            }
            // Foregrounds
            if (this.layers.length) {
                engine.setDepthBuffer(false);
                for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
                    layer = this.layers[layerIndex];
                    if (!layer.isBackground) {
                        layer.render();
                    }
                }
                engine.setDepthBuffer(true);
            }
            // Highlight Layer
            if (renderhighlights) {
                engine.setDepthBuffer(false);
                for (var i = 0; i < this.highlightLayers.length; i++) {
                    if (this.highlightLayers[i].shouldRender()) {
                        this.highlightLayers[i].render();
                    }
                }
                engine.setDepthBuffer(true);
            }
            this._renderDuration.endMonitoring(false);
            // Finalize frame
            this.postProcessManager._finalizeFrame(camera.isIntermediate);
            // Update camera
            this.activeCamera._updateFromScene();
            // Reset some special arrays
            this._renderTargets.reset();
            this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
            BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
        };
        Scene.prototype._processSubCameras = function (camera) {
            if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
                this._renderForCamera(camera);
                return;
            }
            // rig cameras
            for (var index = 0; index < camera._rigCameras.length; index++) {
                this._renderForCamera(camera._rigCameras[index]);
            }
            this.activeCamera = camera;
            this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
            // Update camera
            this.activeCamera._updateFromScene();
        };
        Scene.prototype._checkIntersections = function () {
            for (var index = 0; index < this._meshesForIntersections.length; index++) {
                var sourceMesh = this._meshesForIntersections.data[index];
                for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
                    var action = sourceMesh.actionManager.actions[actionIndex];
                    if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                        var parameters = action.getTriggerParameter();
                        var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
                        var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
                        var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
                        if (areIntersecting && currentIntersectionInProgress === -1) {
                            if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
                                action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
                                sourceMesh._intersectionsInProgress.push(otherMesh);
                            }
                            else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                                sourceMesh._intersectionsInProgress.push(otherMesh);
                            }
                        }
                        else if (!areIntersecting && currentIntersectionInProgress > -1) {
                            //They intersected, and now they don't.
                            //is this trigger an exit trigger? execute an event.
                            if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                                action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
                            }
                            //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
                            if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                                sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
                            }
                        }
                    }
                }
            }
        };
        Scene.prototype.render = function () {
            this._lastFrameDuration.beginMonitoring();
            this._particlesDuration.fetchNewFrame();
            this._spritesDuration.fetchNewFrame();
            this._activeParticles.fetchNewFrame();
            this._renderDuration.fetchNewFrame();
            this._renderTargetsDuration.fetchNewFrame();
            this._evaluateActiveMeshesDuration.fetchNewFrame();
            this._totalVertices.fetchNewFrame();
            this._activeIndices.fetchNewFrame();
            this._activeBones.fetchNewFrame();
            this.getEngine().drawCallsPerfCounter.fetchNewFrame();
            this._meshesForIntersections.reset();
            this.resetCachedMaterial();
            BABYLON.Tools.StartPerformanceCounter("Scene rendering");
            // Actions
            if (this.actionManager) {
                this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
            }
            //Simplification Queue
            if (this.simplificationQueue && !this.simplificationQueue.running) {
                this.simplificationQueue.executeNext();
            }
            // Animations
            var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
            this._animationRatio = deltaTime * (60.0 / 1000.0);
            this._animate();
            // Physics
            if (this._physicsEngine) {
                BABYLON.Tools.StartPerformanceCounter("Physics");
                this._physicsEngine._step(deltaTime / 1000.0);
                BABYLON.Tools.EndPerformanceCounter("Physics");
            }
            // Before render
            this.onBeforeRenderObservable.notifyObservers(this);
            // Customs render targets
            this._renderTargetsDuration.beginMonitoring();
            var beforeRenderTargetDate = BABYLON.Tools.Now;
            var engine = this.getEngine();
            var currentActiveCamera = this.activeCamera;
            if (this.renderTargetsEnabled) {
                BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
                for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
                    var renderTarget = this.customRenderTargets[customIndex];
                    if (renderTarget._shouldRender()) {
                        this._renderId++;
                        this.activeCamera = renderTarget.activeCamera || this.activeCamera;
                        if (!this.activeCamera)
                            throw new Error("Active camera not set");
                        // Viewport
                        engine.setViewport(this.activeCamera.viewport);
                        // Camera
                        this.updateTransformMatrix();
                        renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
                this._renderId++;
            }
            if (this.customRenderTargets.length > 0) {
                engine.restoreDefaultFramebuffer();
            }
            this._renderTargetsDuration.endMonitoring();
            this.activeCamera = currentActiveCamera;
            // Procedural textures
            if (this.proceduralTexturesEnabled) {
                BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
                for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
                    var proceduralTexture = this._proceduralTextures[proceduralIndex];
                    if (proceduralTexture._shouldRender()) {
                        proceduralTexture.render();
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
            }
            // Clear
            this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
            // Shadows
            if (this.shadowsEnabled) {
                for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
                    var light = this.lights[lightIndex];
                    var shadowGenerator = light.getShadowGenerator();
                    if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
                        this._renderTargets.push(shadowGenerator.getShadowMap());
                    }
                }
            }
            // Depth renderer
            if (this._depthRenderer) {
                this._renderTargets.push(this._depthRenderer.getDepthMap());
            }
            // RenderPipeline
            this.postProcessRenderPipelineManager.update();
            // Multi-cameras?
            if (this.activeCameras.length > 0) {
                for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
                    if (cameraIndex > 0) {
                        this._engine.clear(0, false, true, true);
                    }
                    this._processSubCameras(this.activeCameras[cameraIndex]);
                }
            }
            else {
                if (!this.activeCamera) {
                    throw new Error("No camera defined");
                }
                this._processSubCameras(this.activeCamera);
            }
            // Intersection checks
            this._checkIntersections();
            // Update the audio listener attached to the camera
            if (BABYLON.AudioEngine) {
                this._updateAudioParameters();
            }
            // After render
            if (this.afterRender) {
                this.afterRender();
            }
            this.onAfterRenderObservable.notifyObservers(this);
            // Cleaning
            for (var index = 0; index < this._toBeDisposed.length; index++) {
                this._toBeDisposed.data[index].dispose();
                this._toBeDisposed[index] = null;
            }
            this._toBeDisposed.reset();
            if (this.dumpNextRenderTargets) {
                this.dumpNextRenderTargets = false;
            }
            BABYLON.Tools.EndPerformanceCounter("Scene rendering");
            this._lastFrameDuration.endMonitoring();
            this._totalMeshesCounter.addCount(this.meshes.length, true);
            this._totalLightsCounter.addCount(this.lights.length, true);
            this._totalMaterialsCounter.addCount(this.materials.length, true);
            this._totalTexturesCounter.addCount(this.textures.length, true);
            this._activeBones.addCount(0, true);
            this._activeIndices.addCount(0, true);
            this._activeParticles.addCount(0, true);
        };
        Scene.prototype._updateAudioParameters = function () {
            if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
                return;
            }
            var listeningCamera;
            var audioEngine = BABYLON.Engine.audioEngine;
            if (this.activeCameras.length > 0) {
                listeningCamera = this.activeCameras[0];
            }
            else {
                listeningCamera = this.activeCamera;
            }
            if (listeningCamera && audioEngine.canUseWebAudio) {
                audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
                var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
                var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
                cameraDirection.normalize();
                audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
                var i;
                for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
                    var sound = this.mainSoundTrack.soundCollection[i];
                    if (sound.useCustomAttenuation) {
                        sound.updateDistanceFromListener();
                    }
                }
                for (i = 0; i < this.soundTracks.length; i++) {
                    for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
                        sound = this.soundTracks[i].soundCollection[j];
                        if (sound.useCustomAttenuation) {
                            sound.updateDistanceFromListener();
                        }
                    }
                }
            }
        };
        Object.defineProperty(Scene.prototype, "audioEnabled", {
            // Audio
            get: function () {
                return this._audioEnabled;
            },
            set: function (value) {
                this._audioEnabled = value;
                if (BABYLON.AudioEngine) {
                    if (this._audioEnabled) {
                        this._enableAudio();
                    }
                    else {
                        this._disableAudio();
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype._disableAudio = function () {
            var i;
            for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
                this.mainSoundTrack.soundCollection[i].pause();
            }
            for (i = 0; i < this.soundTracks.length; i++) {
                for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
                    this.soundTracks[i].soundCollection[j].pause();
                }
            }
        };
        Scene.prototype._enableAudio = function () {
            var i;
            for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
                if (this.mainSoundTrack.soundCollection[i].isPaused) {
                    this.mainSoundTrack.soundCollection[i].play();
                }
            }
            for (i = 0; i < this.soundTracks.length; i++) {
                for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
                    if (this.soundTracks[i].soundCollection[j].isPaused) {
                        this.soundTracks[i].soundCollection[j].play();
                    }
                }
            }
        };
        Object.defineProperty(Scene.prototype, "headphone", {
            get: function () {
                return this._headphone;
            },
            set: function (value) {
                this._headphone = value;
                if (BABYLON.AudioEngine) {
                    if (this._headphone) {
                        this._switchAudioModeForHeadphones();
                    }
                    else {
                        this._switchAudioModeForNormalSpeakers();
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Scene.prototype._switchAudioModeForHeadphones = function () {
            this.mainSoundTrack.switchPanningModelToHRTF();
            for (var i = 0; i < this.soundTracks.length; i++) {
                this.soundTracks[i].switchPanningModelToHRTF();
            }
        };
        Scene.prototype._switchAudioModeForNormalSpeakers = function () {
            this.mainSoundTrack.switchPanningModelToEqualPower();
            for (var i = 0; i < this.soundTracks.length; i++) {
                this.soundTracks[i].switchPanningModelToEqualPower();
            }
        };
        Scene.prototype.enableDepthRenderer = function () {
            if (this._depthRenderer) {
                return this._depthRenderer;
            }
            this._depthRenderer = new BABYLON.DepthRenderer(this);
            return this._depthRenderer;
        };
        Scene.prototype.disableDepthRenderer = function () {
            if (!this._depthRenderer) {
                return;
            }
            this._depthRenderer.dispose();
            this._depthRenderer = null;
        };
        Scene.prototype.freezeMaterials = function () {
            for (var i = 0; i < this.materials.length; i++) {
                this.materials[i].freeze();
            }
        };
        Scene.prototype.unfreezeMaterials = function () {
            for (var i = 0; i < this.materials.length; i++) {
                this.materials[i].unfreeze();
            }
        };
        Scene.prototype.dispose = function () {
            this.beforeRender = null;
            this.afterRender = null;
            this.skeletons = [];
            this._boundingBoxRenderer.dispose();
            if (this._depthRenderer) {
                this._depthRenderer.dispose();
            }
            // Debug layer
            if (this._debugLayer) {
                this._debugLayer.hide();
            }
            // Events
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onBeforeRenderObservable.clear();
            this.onAfterRenderObservable.clear();
            this.detachControl();
            // Release sounds & sounds tracks
            if (BABYLON.AudioEngine) {
                this.disposeSounds();
            }
            // Detach cameras
            var canvas = this._engine.getRenderingCanvas();
            var index;
            for (index = 0; index < this.cameras.length; index++) {
                this.cameras[index].detachControl(canvas);
            }
            // Release lights
            while (this.lights.length) {
                this.lights[0].dispose();
            }
            // Release meshes
            while (this.meshes.length) {
                this.meshes[0].dispose(true);
            }
            // Release cameras
            while (this.cameras.length) {
                this.cameras[0].dispose();
            }
            // Release materials
            while (this.materials.length) {
                this.materials[0].dispose();
            }
            // Release particles
            while (this.particleSystems.length) {
                this.particleSystems[0].dispose();
            }
            // Release sprites
            while (this.spriteManagers.length) {
                this.spriteManagers[0].dispose();
            }
            // Release layers
            while (this.layers.length) {
                this.layers[0].dispose();
            }
            while (this.highlightLayers.length) {
                this.highlightLayers[0].dispose();
            }
            // Release textures
            while (this.textures.length) {
                this.textures[0].dispose();
            }
            // Post-processes
            this.postProcessManager.dispose();
            // Physics
            if (this._physicsEngine) {
                this.disablePhysicsEngine();
            }
            // Remove from engine
            index = this._engine.scenes.indexOf(this);
            if (index > -1) {
                this._engine.scenes.splice(index, 1);
            }
            this._engine.wipeCaches();
        };
        // Release sounds & sounds tracks
        Scene.prototype.disposeSounds = function () {
            this.mainSoundTrack.dispose();
            for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
                this.soundTracks[scIndex].dispose();
            }
        };
        // Octrees
        Scene.prototype.getWorldExtends = function () {
            var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            for (var index = 0; index < this.meshes.length; index++) {
                var mesh = this.meshes[index];
                mesh.computeWorldMatrix(true);
                var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
                var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
                BABYLON.Tools.CheckExtends(minBox, min, max);
                BABYLON.Tools.CheckExtends(maxBox, min, max);
            }
            return {
                min: min,
                max: max
            };
        };
        Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
            if (maxCapacity === void 0) { maxCapacity = 64; }
            if (maxDepth === void 0) { maxDepth = 2; }
            if (!this._selectionOctree) {
                this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
            }
            var worldExtends = this.getWorldExtends();
            // Update octree
            this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
            return this._selectionOctree;
        };
        // Picking
        Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
            if (cameraViewSpace === void 0) { cameraViewSpace = false; }
            var engine = this._engine;
            if (!camera) {
                if (!this.activeCamera)
                    throw new Error("Active camera not set");
                camera = this.activeCamera;
            }
            var cameraViewport = camera.viewport;
            var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            // Moving coordinates to local viewport world
            x = x / this._engine.getHardwareScalingLevel() - viewport.x;
            y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
            return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
            //       return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
        };
        Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
            var engine = this._engine;
            if (!camera) {
                if (!this.activeCamera)
                    throw new Error("Active camera not set");
                camera = this.activeCamera;
            }
            var cameraViewport = camera.viewport;
            var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            var identity = BABYLON.Matrix.Identity();
            // Moving coordinates to local viewport world
            x = x / this._engine.getHardwareScalingLevel() - viewport.x;
            y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
            return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
        };
        Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
            var pickingInfo = null;
            for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
                var mesh = this.meshes[meshIndex];
                if (predicate) {
                    if (!predicate(mesh)) {
                        continue;
                    }
                }
                else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
                    continue;
                }
                var world = mesh.getWorldMatrix();
                var ray = rayFunction(world);
                var result = mesh.intersects(ray, fastCheck);
                if (!result || !result.hit)
                    continue;
                if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
                    continue;
                pickingInfo = result;
                if (fastCheck) {
                    break;
                }
            }
            return pickingInfo || new BABYLON.PickingInfo();
        };
        Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
            var pickingInfos = new Array();
            for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
                var mesh = this.meshes[meshIndex];
                if (predicate) {
                    if (!predicate(mesh)) {
                        continue;
                    }
                }
                else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
                    continue;
                }
                var world = mesh.getWorldMatrix();
                var ray = rayFunction(world);
                var result = mesh.intersects(ray, false);
                if (!result || !result.hit)
                    continue;
                pickingInfos.push(result);
            }
            return pickingInfos;
        };
        Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
            var pickingInfo = null;
            camera = camera || this.activeCamera;
            if (this.spriteManagers.length > 0) {
                for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
                    var spriteManager = this.spriteManagers[spriteIndex];
                    if (!spriteManager.isPickable) {
                        continue;
                    }
                    var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
                    if (!result || !result.hit)
                        continue;
                    if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
                        continue;
                    pickingInfo = result;
                    if (fastCheck) {
                        break;
                    }
                }
            }
            return pickingInfo || new BABYLON.PickingInfo();
        };
        /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
        /// <param name="x">X position on screen</param>
        /// <param name="y">Y position on screen</param>
        /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
        /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
        /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
        Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
            var _this = this;
            return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
        };
        /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
        /// <param name="x">X position on screen</param>
        /// <param name="y">Y position on screen</param>
        /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
        /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
        /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
        Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
            return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
        };
        Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
            var _this = this;
            return this._internalPick(function (world) {
                if (!_this._pickWithRayInverseMatrix) {
                    _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
                }
                world.invertToRef(_this._pickWithRayInverseMatrix);
                return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
            }, predicate, fastCheck);
        };
        /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
        /// <param name="x">X position on screen</param>
        /// <param name="y">Y position on screen</param>
        /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
        /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
        Scene.prototype.multiPick = function (x, y, predicate, camera) {
            var _this = this;
            return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
        };
        /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
        /// <param name="ray">Ray to use</param>
        /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
        Scene.prototype.multiPickWithRay = function (ray, predicate) {
            var _this = this;
            return this._internalMultiPick(function (world) {
                if (!_this._pickWithRayInverseMatrix) {
                    _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
                }
                world.invertToRef(_this._pickWithRayInverseMatrix);
                return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
            }, predicate);
        };
        Scene.prototype.setPointerOverMesh = function (mesh) {
            if (this._pointerOverMesh === mesh) {
                return;
            }
            if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
                this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
            }
            this._pointerOverMesh = mesh;
            if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
                this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
            }
        };
        Scene.prototype.getPointerOverMesh = function () {
            return this._pointerOverMesh;
        };
        Scene.prototype.setPointerOverSprite = function (sprite) {
            if (this._pointerOverSprite === sprite) {
                return;
            }
            if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
                this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
            }
            this._pointerOverSprite = sprite;
            if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
                this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
            }
        };
        Scene.prototype.getPointerOverSprite = function () {
            return this._pointerOverSprite;
        };
        // Physics
        Scene.prototype.getPhysicsEngine = function () {
            return this._physicsEngine;
        };
        /**
         * Enables physics to the current scene
         * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
         * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
         * @return {boolean} was the physics engine initialized
         */
        Scene.prototype.enablePhysics = function (gravity, plugin) {
            if (this._physicsEngine) {
                return true;
            }
            try {
                this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
                return true;
            }
            catch (e) {
                BABYLON.Tools.Error(e.message);
                return false;
            }
        };
        Scene.prototype.disablePhysicsEngine = function () {
            if (!this._physicsEngine) {
                return;
            }
            this._physicsEngine.dispose();
            this._physicsEngine = undefined;
        };
        Scene.prototype.isPhysicsEnabled = function () {
            return this._physicsEngine !== undefined;
        };
        /**
         *
         * Sets the gravity of the physics engine (and NOT of the scene)
         * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
         */
        Scene.prototype.setGravity = function (gravity) {
            BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
            if (!this._physicsEngine) {
                return;
            }
            this._physicsEngine.setGravity(gravity);
        };
        /**
         * Legacy support, using the new API
         * @Deprecated
         */
        Scene.prototype.createCompoundImpostor = function (parts, options) {
            BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
            if (parts.parts) {
                options = parts;
                parts = parts.parts;
            }
            var mainMesh = parts[0].mesh;
            mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
            for (var index = 1; index < parts.length; index++) {
                var mesh = parts[index].mesh;
                if (mesh.parent !== mainMesh) {
                    mesh.position = mesh.position.subtract(mainMesh.position);
                    mesh.parent = mainMesh;
                }
                mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
            }
            mainMesh.physicsImpostor.forceUpdate();
        };
        Scene.prototype.deleteCompoundImpostor = function (compound) {
            var mesh = compound.parts[0].mesh;
            mesh.physicsImpostor.dispose();
            mesh.physicsImpostor = null;
        };
        // Misc.
        Scene.prototype.createDefaultCameraOrLight = function () {
            // Light
            if (this.lights.length === 0) {
                new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
            }
            // Camera
            if (!this.activeCamera) {
                var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
                // Compute position
                var worldExtends = this.getWorldExtends();
                var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
                camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
                camera.setTarget(worldCenter);
                this.activeCamera = camera;
            }
        };
        // Tags
        Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
            if (tagsQuery === undefined) {
                // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
                return list;
            }
            var listByTags = [];
            forEach = forEach || (function (item) { return; });
            for (var i in list) {
                var item = list[i];
                if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
                    listByTags.push(item);
                    forEach(item);
                }
            }
            return listByTags;
        };
        Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.meshes, tagsQuery, forEach);
        };
        Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.cameras, tagsQuery, forEach);
        };
        Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.lights, tagsQuery, forEach);
        };
        Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
        };
        /**
         * Overrides the default sort function applied in the renderging group to prepare the meshes.
         * This allowed control for front to back rendering or reversly depending of the special needs.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
         * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
         * @param transparentSortCompareFn The transparent queue comparison function use to sort.
         */
        Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         */
        Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
            this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
        };
        // Statics
        Scene._FOGMODE_NONE = 0;
        Scene._FOGMODE_EXP = 1;
        Scene._FOGMODE_EXP2 = 2;
        Scene._FOGMODE_LINEAR = 3;
        Scene.MinDeltaTime = 1.0;
        Scene.MaxDeltaTime = 1000.0;
        return Scene;
    }());
    BABYLON.Scene = Scene;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.scene.js.map
 
var BABYLON;
(function (BABYLON) {
    var Buffer = (function () {
        function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
            if (engine instanceof BABYLON.Mesh) {
                this._engine = engine.getScene().getEngine();
            }
            else {
                this._engine = engine;
            }
            this._updatable = updatable;
            this._data = data;
            this._strideSize = stride;
            if (!postponeInternalCreation) {
                this.create();
            }
            this._instanced = instanced;
        }
        Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
            // a lot of these parameters are ignored as they are overriden by the buffer
            return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
        };
        // Properties
        Buffer.prototype.isUpdatable = function () {
            return this._updatable;
        };
        Buffer.prototype.getData = function () {
            return this._data;
        };
        Buffer.prototype.getBuffer = function () {
            return this._buffer;
        };
        Buffer.prototype.getStrideSize = function () {
            return this._strideSize;
        };
        Buffer.prototype.getIsInstanced = function () {
            return this._instanced;
        };
        // Methods
        Buffer.prototype.create = function (data) {
            if (!data && this._buffer) {
                return; // nothing to do
            }
            data = data || this._data;
            if (!this._buffer) {
                if (this._updatable) {
                    this._buffer = this._engine.createDynamicVertexBuffer(data);
                    this._data = data;
                }
                else {
                    this._buffer = this._engine.createVertexBuffer(data);
                }
            }
            else if (this._updatable) {
                this._engine.updateDynamicVertexBuffer(this._buffer, data);
                this._data = data;
            }
        };
        Buffer.prototype.update = function (data) {
            this.create(data);
        };
        Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
            if (!this._buffer) {
                return;
            }
            if (this._updatable) {
                this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
                this._data = null;
            }
        };
        Buffer.prototype.dispose = function () {
            if (!this._buffer) {
                return;
            }
            if (this._engine._releaseBuffer(this._buffer)) {
                this._buffer = null;
            }
        };
        return Buffer;
    }());
    BABYLON.Buffer = Buffer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.buffer.js.map
 
var BABYLON;
(function (BABYLON) {
    var VertexBuffer = (function () {
        function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
            if (!stride) {
                // Deduce stride from kind
                switch (kind) {
                    case VertexBuffer.PositionKind:
                        stride = 3;
                        break;
                    case VertexBuffer.NormalKind:
                        stride = 3;
                        break;
                    case VertexBuffer.UVKind:
                    case VertexBuffer.UV2Kind:
                    case VertexBuffer.UV3Kind:
                    case VertexBuffer.UV4Kind:
                    case VertexBuffer.UV5Kind:
                    case VertexBuffer.UV6Kind:
                        stride = 2;
                        break;
                    case VertexBuffer.ColorKind:
                        stride = 4;
                        break;
                    case VertexBuffer.MatricesIndicesKind:
                    case VertexBuffer.MatricesIndicesExtraKind:
                        stride = 4;
                        break;
                    case VertexBuffer.MatricesWeightsKind:
                    case VertexBuffer.MatricesWeightsExtraKind:
                        stride = 4;
                        break;
                }
            }
            if (data instanceof BABYLON.Buffer) {
                if (!stride) {
                    stride = data.getStrideSize();
                }
                this._buffer = data;
                this._ownsBuffer = false;
            }
            else {
                this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
                this._ownsBuffer = true;
            }
            this._stride = stride;
            this._offset = offset ? offset : 0;
            this._size = size ? size : stride;
            this._kind = kind;
        }
        VertexBuffer.prototype.getKind = function () {
            return this._kind;
        };
        // Properties
        VertexBuffer.prototype.isUpdatable = function () {
            return this._buffer.isUpdatable();
        };
        VertexBuffer.prototype.getData = function () {
            return this._buffer.getData();
        };
        VertexBuffer.prototype.getBuffer = function () {
            return this._buffer.getBuffer();
        };
        VertexBuffer.prototype.getStrideSize = function () {
            return this._stride;
        };
        VertexBuffer.prototype.getOffset = function () {
            return this._offset;
        };
        VertexBuffer.prototype.getSize = function () {
            return this._size;
        };
        VertexBuffer.prototype.getIsInstanced = function () {
            return this._buffer.getIsInstanced();
        };
        // Methods
        VertexBuffer.prototype.create = function (data) {
            return this._buffer.create(data);
        };
        VertexBuffer.prototype.update = function (data) {
            return this._buffer.update(data);
        };
        VertexBuffer.prototype.updateDirectly = function (data, offset) {
            return this._buffer.updateDirectly(data, offset);
        };
        VertexBuffer.prototype.dispose = function () {
            if (this._ownsBuffer) {
                this._buffer.dispose();
            }
        };
        Object.defineProperty(VertexBuffer, "PositionKind", {
            get: function () {
                return VertexBuffer._PositionKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "NormalKind", {
            get: function () {
                return VertexBuffer._NormalKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "UVKind", {
            get: function () {
                return VertexBuffer._UVKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "UV2Kind", {
            get: function () {
                return VertexBuffer._UV2Kind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "UV3Kind", {
            get: function () {
                return VertexBuffer._UV3Kind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "UV4Kind", {
            get: function () {
                return VertexBuffer._UV4Kind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "UV5Kind", {
            get: function () {
                return VertexBuffer._UV5Kind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "UV6Kind", {
            get: function () {
                return VertexBuffer._UV6Kind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "ColorKind", {
            get: function () {
                return VertexBuffer._ColorKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
            get: function () {
                return VertexBuffer._MatricesIndicesKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
            get: function () {
                return VertexBuffer._MatricesWeightsKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
            get: function () {
                return VertexBuffer._MatricesIndicesExtraKind;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
            get: function () {
                return VertexBuffer._MatricesWeightsExtraKind;
            },
            enumerable: true,
            configurable: true
        });
        // Enums
        VertexBuffer._PositionKind = "position";
        VertexBuffer._NormalKind = "normal";
        VertexBuffer._UVKind = "uv";
        VertexBuffer._UV2Kind = "uv2";
        VertexBuffer._UV3Kind = "uv3";
        VertexBuffer._UV4Kind = "uv4";
        VertexBuffer._UV5Kind = "uv5";
        VertexBuffer._UV6Kind = "uv6";
        VertexBuffer._ColorKind = "color";
        VertexBuffer._MatricesIndicesKind = "matricesIndices";
        VertexBuffer._MatricesWeightsKind = "matricesWeights";
        VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
        VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
        return VertexBuffer;
    }());
    BABYLON.VertexBuffer = VertexBuffer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.vertexBuffer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * Creates an instance based on a source mesh.
     */
    var InstancedMesh = (function (_super) {
        __extends(InstancedMesh, _super);
        function InstancedMesh(name, source) {
            _super.call(this, name, source.getScene());
            source.instances.push(this);
            this._sourceMesh = source;
            this.position.copyFrom(source.position);
            this.rotation.copyFrom(source.rotation);
            this.scaling.copyFrom(source.scaling);
            if (source.rotationQuaternion) {
                this.rotationQuaternion = source.rotationQuaternion.clone();
            }
            this.infiniteDistance = source.infiniteDistance;
            this.setPivotMatrix(source.getPivotMatrix());
            this.refreshBoundingInfo();
            this._syncSubMeshes();
        }
        Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
            // Methods
            get: function () {
                return this._sourceMesh.receiveShadows;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "material", {
            get: function () {
                return this._sourceMesh.material;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "visibility", {
            get: function () {
                return this._sourceMesh.visibility;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "skeleton", {
            get: function () {
                return this._sourceMesh.skeleton;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
            get: function () {
                return this._sourceMesh.renderingGroupId;
            },
            enumerable: true,
            configurable: true
        });
        InstancedMesh.prototype.getTotalVertices = function () {
            return this._sourceMesh.getTotalVertices();
        };
        Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
            get: function () {
                return this._sourceMesh;
            },
            enumerable: true,
            configurable: true
        });
        InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
            return this._sourceMesh.getVerticesData(kind, copyWhenShared);
        };
        InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
            return this._sourceMesh.isVerticesDataPresent(kind);
        };
        InstancedMesh.prototype.getIndices = function () {
            return this._sourceMesh.getIndices();
        };
        Object.defineProperty(InstancedMesh.prototype, "_positions", {
            get: function () {
                return this._sourceMesh._positions;
            },
            enumerable: true,
            configurable: true
        });
        InstancedMesh.prototype.refreshBoundingInfo = function () {
            var meshBB = this._sourceMesh.getBoundingInfo();
            this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
            this._updateBoundingInfo();
        };
        InstancedMesh.prototype._preActivate = function () {
            if (this._currentLOD) {
                this._currentLOD._preActivate();
            }
        };
        InstancedMesh.prototype._activate = function (renderId) {
            if (this._currentLOD) {
                this._currentLOD._registerInstanceForRenderId(this, renderId);
            }
        };
        InstancedMesh.prototype.getLOD = function (camera) {
            this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
            if (this._currentLOD === this.sourceMesh) {
                return this;
            }
            return this._currentLOD;
        };
        InstancedMesh.prototype._syncSubMeshes = function () {
            this.releaseSubMeshes();
            if (this._sourceMesh.subMeshes) {
                for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
                    this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
                }
            }
        };
        InstancedMesh.prototype._generatePointsArray = function () {
            return this._sourceMesh._generatePointsArray();
        };
        // Clone
        InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
            var result = this._sourceMesh.createInstance(name);
            // Deep copy
            BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
            // Bounding info
            this.refreshBoundingInfo();
            // Parent
            if (newParent) {
                result.parent = newParent;
            }
            if (!doNotCloneChildren) {
                // Children
                for (var index = 0; index < this.getScene().meshes.length; index++) {
                    var mesh = this.getScene().meshes[index];
                    if (mesh.parent === this) {
                        mesh.clone(mesh.name, result);
                    }
                }
            }
            result.computeWorldMatrix(true);
            return result;
        };
        // Dispoe
        InstancedMesh.prototype.dispose = function (doNotRecurse) {
            // Remove from mesh
            var index = this._sourceMesh.instances.indexOf(this);
            this._sourceMesh.instances.splice(index, 1);
            _super.prototype.dispose.call(this, doNotRecurse);
        };
        return InstancedMesh;
    }(BABYLON.AbstractMesh));
    BABYLON.InstancedMesh = InstancedMesh;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.instancedMesh.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var _InstancesBatch = (function () {
        function _InstancesBatch() {
            this.mustReturn = false;
            this.visibleInstances = new Array();
            this.renderSelf = new Array();
        }
        return _InstancesBatch;
    }());
    BABYLON._InstancesBatch = _InstancesBatch;
    var Mesh = (function (_super) {
        __extends(Mesh, _super);
        /**
         * @constructor
         * @param {string} name The value used by scene.getMeshByName() to do a lookup.
         * @param {Scene} scene The scene to add this mesh to.
         * @param {Node} parent The parent of this mesh, if it has one
         * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
         * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
         *                  When false, achieved by calling a clone(), also passing False.
         *                  This will make creation of children, recursive.
         */
        function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
            if (parent === void 0) { parent = null; }
            if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
            _super.call(this, name, scene);
            // Events 
            /**
             * An event triggered before rendering the mesh
             * @type {BABYLON.Observable}
             */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the mesh
            * @type {BABYLON.Observable}
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered before drawing the mesh
            * @type {BABYLON.Observable}
            */
            this.onBeforeDrawObservable = new BABYLON.Observable();
            // Members
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this.instances = new Array();
            this._LODLevels = new Array();
            this._visibleInstances = {};
            this._renderIdForInstances = new Array();
            this._batchCache = new _InstancesBatch();
            this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
            this._sideOrientation = Mesh._DEFAULTSIDE;
            this._areNormalsFrozen = false; // Will be used by ribbons mainly
            if (source) {
                // Geometry
                if (source._geometry) {
                    source._geometry.applyToMesh(this);
                }
                // Deep copy
                BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
                // Parent
                this.parent = source.parent;
                // Pivot
                this.setPivotMatrix(source.getPivotMatrix());
                this.id = name + "." + source.id;
                // Material
                this.material = source.material;
                var index;
                if (!doNotCloneChildren) {
                    // Children
                    for (index = 0; index < scene.meshes.length; index++) {
                        var mesh = scene.meshes[index];
                        if (mesh.parent === source) {
                            // doNotCloneChildren is always going to be False
                            var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
                        }
                    }
                }
                // Physics clone  
                var physicsEngine = this.getScene().getPhysicsEngine();
                if (clonePhysicsImpostor && physicsEngine) {
                    var impostor = physicsEngine.getImpostorForPhysicsObject(source);
                    if (impostor) {
                        this.physicsImpostor = impostor.clone(this);
                    }
                }
                // Particles
                for (index = 0; index < scene.particleSystems.length; index++) {
                    var system = scene.particleSystems[index];
                    if (system.emitter === source) {
                        system.clone(system.name, this);
                    }
                }
                this.computeWorldMatrix(true);
            }
            // Parent
            if (parent !== null) {
                this.parent = parent;
            }
        }
        Object.defineProperty(Mesh, "FRONTSIDE", {
            /**
             * Mesh side orientation : usually the external or front surface
             */
            get: function () {
                return Mesh._FRONTSIDE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "BACKSIDE", {
            /**
             * Mesh side orientation : usually the internal or back surface
             */
            get: function () {
                return Mesh._BACKSIDE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "DOUBLESIDE", {
            /**
             * Mesh side orientation : both internal and external or front and back surfaces
             */
            get: function () {
                return Mesh._DOUBLESIDE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "DEFAULTSIDE", {
            /**
             * Mesh side orientation : by default, `FRONTSIDE`
             */
            get: function () {
                return Mesh._DEFAULTSIDE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "NO_CAP", {
            /**
             * Mesh cap setting : no cap
             */
            get: function () {
                return Mesh._NO_CAP;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "CAP_START", {
            /**
             * Mesh cap setting : one cap at the beginning of the mesh
             */
            get: function () {
                return Mesh._CAP_START;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "CAP_END", {
            /**
             * Mesh cap setting : one cap at the end of the mesh
             */
            get: function () {
                return Mesh._CAP_END;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh, "CAP_ALL", {
            /**
             * Mesh cap setting : two caps, one at the beginning  and one at the end of the mesh
             */
            get: function () {
                return Mesh._CAP_ALL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
            set: function (callback) {
                if (this._onBeforeDrawObserver) {
                    this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
                }
                this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         */
        Mesh.prototype.toString = function (fullDetails) {
            var ret = _super.prototype.toString.call(this, fullDetails);
            ret += ", n vertices: " + this.getTotalVertices();
            ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
            if (this.animations) {
                for (var i = 0; i < this.animations.length; i++) {
                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
                }
            }
            if (fullDetails) {
                ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
            }
            return ret;
        };
        Object.defineProperty(Mesh.prototype, "hasLODLevels", {
            get: function () {
                return this._LODLevels.length > 0;
            },
            enumerable: true,
            configurable: true
        });
        Mesh.prototype._sortLODLevels = function () {
            this._LODLevels.sort(function (a, b) {
                if (a.distance < b.distance) {
                    return 1;
                }
                if (a.distance > b.distance) {
                    return -1;
                }
                return 0;
            });
        };
        /**
         * Add a mesh as LOD level triggered at the given distance.
         * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
         * @param {number} distance The distance from the center of the object to show this level
         * @param {Mesh} mesh The mesh to be added as LOD level
         * @return {Mesh} This mesh (for chaining)
         */
        Mesh.prototype.addLODLevel = function (distance, mesh) {
            if (mesh && mesh._masterMesh) {
                BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
                return this;
            }
            var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
            this._LODLevels.push(level);
            if (mesh) {
                mesh._masterMesh = this;
            }
            this._sortLODLevels();
            return this;
        };
        /**
         * Returns the LOD level mesh at the passed distance or null if not found.
         * It is related to the method `addLODLevel(distance, mesh)`.
         * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
         */
        Mesh.prototype.getLODLevelAtDistance = function (distance) {
            for (var index = 0; index < this._LODLevels.length; index++) {
                var level = this._LODLevels[index];
                if (level.distance === distance) {
                    return level.mesh;
                }
            }
            return null;
        };
        /**
         * Remove a mesh from the LOD array
         * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
         * @param {Mesh} mesh The mesh to be removed.
         * @return {Mesh} This mesh (for chaining)
         */
        Mesh.prototype.removeLODLevel = function (mesh) {
            for (var index = 0; index < this._LODLevels.length; index++) {
                if (this._LODLevels[index].mesh === mesh) {
                    this._LODLevels.splice(index, 1);
                    if (mesh) {
                        mesh._masterMesh = null;
                    }
                }
            }
            this._sortLODLevels();
            return this;
        };
        /**
         * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
         * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
         */
        Mesh.prototype.getLOD = function (camera, boundingSphere) {
            if (!this._LODLevels || this._LODLevels.length === 0) {
                return this;
            }
            var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
            if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
                if (this.onLODLevelSelection) {
                    this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
                }
                return this;
            }
            for (var index = 0; index < this._LODLevels.length; index++) {
                var level = this._LODLevels[index];
                if (level.distance < distanceToCamera) {
                    if (level.mesh) {
                        level.mesh._preActivate();
                        level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
                    }
                    if (this.onLODLevelSelection) {
                        this.onLODLevelSelection(distanceToCamera, this, level.mesh);
                    }
                    return level.mesh;
                }
            }
            if (this.onLODLevelSelection) {
                this.onLODLevelSelection(distanceToCamera, this, this);
            }
            return this;
        };
        Object.defineProperty(Mesh.prototype, "geometry", {
            /**
             * Returns the mesh internal Geometry object.
             */
            get: function () {
                return this._geometry;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
         */
        Mesh.prototype.getTotalVertices = function () {
            if (!this._geometry) {
                return 0;
            }
            return this._geometry.getTotalVertices();
        };
        /**
         * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
         * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
         * Returns null if the mesh has no geometry or no vertex buffer.
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         */
        Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
            if (!this._geometry) {
                return null;
            }
            return this._geometry.getVerticesData(kind, copyWhenShared);
        };
        /**
         * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
         * Returns `undefined` if the mesh has no geometry.
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         */
        Mesh.prototype.getVertexBuffer = function (kind) {
            if (!this._geometry) {
                return undefined;
            }
            return this._geometry.getVertexBuffer(kind);
        };
        /**
         * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         */
        Mesh.prototype.isVerticesDataPresent = function (kind) {
            if (!this._geometry) {
                if (this._delayInfo) {
                    return this._delayInfo.indexOf(kind) !== -1;
                }
                return false;
            }
            return this._geometry.isVerticesDataPresent(kind);
        };
        /**
         * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         */
        Mesh.prototype.getVerticesDataKinds = function () {
            if (!this._geometry) {
                var result = [];
                if (this._delayInfo) {
                    this._delayInfo.forEach(function (kind, index, array) {
                        result.push(kind);
                    });
                }
                return result;
            }
            return this._geometry.getVerticesDataKinds();
        };
        /**
         * Returns a positive integer : the total number of indices in this mesh geometry.
         * Returns zero if the mesh has no geometry.
         */
        Mesh.prototype.getTotalIndices = function () {
            if (!this._geometry) {
                return 0;
            }
            return this._geometry.getTotalIndices();
        };
        /**
         * Returns an array of integers or a Int32Array populated with the mesh indices.
         * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
         * Returns an empty array if the mesh has no geometry.
         */
        Mesh.prototype.getIndices = function (copyWhenShared) {
            if (!this._geometry) {
                return [];
            }
            return this._geometry.getIndices(copyWhenShared);
        };
        Object.defineProperty(Mesh.prototype, "isBlocked", {
            get: function () {
                return this._masterMesh !== null && this._masterMesh !== undefined;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
         */
        Mesh.prototype.isReady = function () {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                return false;
            }
            return _super.prototype.isReady.call(this);
        };
        /**
         * Boolean : true if the mesh has been disposed.
         */
        Mesh.prototype.isDisposed = function () {
            return this._isDisposed;
        };
        Object.defineProperty(Mesh.prototype, "sideOrientation", {
            get: function () {
                return this._sideOrientation;
            },
            /**
             * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
             * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
             */
            set: function (sideO) {
                this._sideOrientation = sideO;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
            /**
             * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
             * This property is pertinent only for updatable parametric shapes.
             */
            get: function () {
                return this._areNormalsFrozen;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
         * It has no effect at all on other shapes.
         * It prevents the mesh normals from being recomputed on next `positions` array update.
         */
        Mesh.prototype.freezeNormals = function () {
            this._areNormalsFrozen = true;
        };
        /**
         * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
         * It has no effect at all on other shapes.
         * It reactivates the mesh normals computation if it was previously frozen.
         */
        Mesh.prototype.unfreezeNormals = function () {
            this._areNormalsFrozen = false;
        };
        Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
            /**
             * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
             */
            set: function (count) {
                this._overridenInstanceCount = count;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        Mesh.prototype._preActivate = function () {
            var sceneRenderId = this.getScene().getRenderId();
            if (this._preActivateId === sceneRenderId) {
                return;
            }
            this._preActivateId = sceneRenderId;
            this._visibleInstances = null;
        };
        Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
            if (this._visibleInstances) {
                this._visibleInstances.intermediateDefaultRenderId = renderId;
            }
        };
        Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
            if (!this._visibleInstances) {
                this._visibleInstances = {};
                this._visibleInstances.defaultRenderId = renderId;
                this._visibleInstances.selfDefaultRenderId = this._renderId;
            }
            if (!this._visibleInstances[renderId]) {
                this._visibleInstances[renderId] = new Array();
            }
            this._visibleInstances[renderId].push(instance);
        };
        /**
         * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
         * This means the mesh underlying bounding box and sphere are recomputed.
         */
        Mesh.prototype.refreshBoundingInfo = function () {
            if (this._boundingInfo.isLocked) {
                return;
            }
            var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (data) {
                var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
                this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
            }
            if (this.subMeshes) {
                for (var index = 0; index < this.subMeshes.length; index++) {
                    this.subMeshes[index].refreshBoundingInfo();
                }
            }
            this._updateBoundingInfo();
        };
        Mesh.prototype._createGlobalSubMesh = function () {
            var totalVertices = this.getTotalVertices();
            if (!totalVertices || !this.getIndices()) {
                return null;
            }
            this.releaseSubMeshes();
            return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
        };
        Mesh.prototype.subdivide = function (count) {
            if (count < 1) {
                return;
            }
            var totalIndices = this.getTotalIndices();
            var subdivisionSize = (totalIndices / count) | 0;
            var offset = 0;
            // Ensure that subdivisionSize is a multiple of 3
            while (subdivisionSize % 3 !== 0) {
                subdivisionSize++;
            }
            this.releaseSubMeshes();
            for (var index = 0; index < count; index++) {
                if (offset >= totalIndices) {
                    break;
                }
                BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
                offset += subdivisionSize;
            }
            this.synchronizeInstances();
        };
        /**
         * Sets the vertex data of the mesh geometry for the requested `kind`.
         * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
         * The `data` are either a numeric array either a Float32Array.
         * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
         * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
         * Note that a new underlying VertexBuffer object is created each call.
         * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
         *
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         */
        Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
            if (!this._geometry) {
                var vertexData = new BABYLON.VertexData();
                vertexData.set(data, kind);
                var scene = this.getScene();
                new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
            }
            else {
                this._geometry.setVerticesData(kind, data, updatable, stride);
            }
        };
        Mesh.prototype.setVerticesBuffer = function (buffer) {
            if (!this._geometry) {
                var scene = this.getScene();
                new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
            }
            this._geometry.setVerticesBuffer(buffer);
        };
        /**
         * Updates the existing vertex data of the mesh geometry for the requested `kind`.
         * If the mesh has no geometry, it is simply returned as it is.
         * The `data` are either a numeric array either a Float32Array.
         * No new underlying VertexBuffer object is created.
         * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
         * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
         *
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         */
        Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
            if (!this._geometry) {
                return;
            }
            if (!makeItUnique) {
                this._geometry.updateVerticesData(kind, data, updateExtends);
            }
            else {
                this.makeGeometryUnique();
                this.updateVerticesData(kind, data, updateExtends, false);
            }
        };
        /**
         * Deprecated since BabylonJS v2.3
         */
        Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
            BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
            if (!this._geometry) {
                return;
            }
            if (!makeItUnique) {
                this._geometry.updateVerticesDataDirectly(kind, data, offset);
            }
            else {
                this.makeGeometryUnique();
                this.updateVerticesDataDirectly(kind, data, offset, false);
            }
        };
        /**
         * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
         * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
         * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
         * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
         */
        Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
            if (computeNormals === void 0) { computeNormals = true; }
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            positionFunction(positions);
            this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
            if (computeNormals) {
                var indices = this.getIndices();
                var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                BABYLON.VertexData.ComputeNormals(positions, indices, normals);
                this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
            }
        };
        Mesh.prototype.makeGeometryUnique = function () {
            if (!this._geometry) {
                return;
            }
            var oldGeometry = this._geometry;
            var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
            oldGeometry.releaseForMesh(this, true);
            geometry.applyToMesh(this);
        };
        /**
         * Sets the mesh indices.
         * Expects an array populated with integers or a Int32Array.
         * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
         * This method creates a new index buffer each call.
         */
        Mesh.prototype.setIndices = function (indices, totalVertices) {
            if (!this._geometry) {
                var vertexData = new BABYLON.VertexData();
                vertexData.indices = indices;
                var scene = this.getScene();
                new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
            }
            else {
                this._geometry.setIndices(indices, totalVertices);
            }
        };
        /**
         * Invert the geometry to move from a right handed system to a left handed one.
         */
        Mesh.prototype.toLeftHanded = function () {
            if (!this._geometry) {
                return;
            }
            this._geometry.toLeftHanded();
        };
        Mesh.prototype._bind = function (subMesh, effect, fillMode) {
            var engine = this.getScene().getEngine();
            // Wireframe
            var indexToBind;
            if (this._unIndexed) {
                indexToBind = null;
            }
            else {
                switch (fillMode) {
                    case BABYLON.Material.PointFillMode:
                        indexToBind = null;
                        break;
                    case BABYLON.Material.WireFrameFillMode:
                        indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
                        break;
                    default:
                    case BABYLON.Material.TriangleFillMode:
                        indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
                        break;
                }
            }
            // VBOs
            engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
        };
        Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
            if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
                return;
            }
            this.onBeforeDrawObservable.notifyObservers(this);
            var engine = this.getScene().getEngine();
            // Draw order
            switch (fillMode) {
                case BABYLON.Material.PointFillMode:
                    engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
                    break;
                case BABYLON.Material.WireFrameFillMode:
                    if (this._unIndexed) {
                        engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
                    }
                    else {
                        engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
                    }
                    break;
                default:
                    if (this._unIndexed) {
                        engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
                    }
                    else {
                        engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
                    }
            }
        };
        /**
         * Registers for this mesh a javascript function called just before the rendering process.
         * This function is passed the current mesh and doesn't return anything.
         */
        Mesh.prototype.registerBeforeRender = function (func) {
            this.onBeforeRenderObservable.add(func);
        };
        /**
         * Disposes a previously registered javascript function called before the rendering.
         * This function is passed the current mesh and doesn't return anything.
         */
        Mesh.prototype.unregisterBeforeRender = function (func) {
            this.onBeforeRenderObservable.removeCallback(func);
        };
        /**
         * Registers for this mesh a javascript function called just after the rendering is complete.
         * This function is passed the current mesh and doesn't return anything.
         */
        Mesh.prototype.registerAfterRender = function (func) {
            this.onAfterRenderObservable.add(func);
        };
        /**
         * Disposes a previously registered javascript function called after the rendering.
         * This function is passed the current mesh and doesn't return anything.
         */
        Mesh.prototype.unregisterAfterRender = function (func) {
            this.onAfterRenderObservable.removeCallback(func);
        };
        Mesh.prototype._getInstancesRenderList = function (subMeshId) {
            var scene = this.getScene();
            this._batchCache.mustReturn = false;
            this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
            this._batchCache.visibleInstances[subMeshId] = null;
            if (this._visibleInstances) {
                var currentRenderId = scene.getRenderId();
                var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
                this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
                var selfRenderId = this._renderId;
                if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
                    this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
                    currentRenderId = Math.max(defaultRenderId, currentRenderId);
                    selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
                }
                if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
                    if (this._renderIdForInstances[subMeshId] === currentRenderId) {
                        this._batchCache.mustReturn = true;
                        return this._batchCache;
                    }
                    if (currentRenderId !== selfRenderId) {
                        this._batchCache.renderSelf[subMeshId] = false;
                    }
                }
                this._renderIdForInstances[subMeshId] = currentRenderId;
            }
            return this._batchCache;
        };
        Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
            var visibleInstances = batch.visibleInstances[subMesh._id];
            var matricesCount = visibleInstances.length + 1;
            var bufferSize = matricesCount * 16 * 4;
            var currentInstancesBufferSize = this._instancesBufferSize;
            var instancesBuffer = this._instancesBuffer;
            while (this._instancesBufferSize < bufferSize) {
                this._instancesBufferSize *= 2;
            }
            if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
                this._instancesData = new Float32Array(this._instancesBufferSize / 4);
            }
            var offset = 0;
            var instancesCount = 0;
            var world = this.getWorldMatrix();
            if (batch.renderSelf[subMesh._id]) {
                world.copyToArray(this._instancesData, offset);
                offset += 16;
                instancesCount++;
            }
            if (visibleInstances) {
                for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
                    var instance = visibleInstances[instanceIndex];
                    instance.getWorldMatrix().copyToArray(this._instancesData, offset);
                    offset += 16;
                    instancesCount++;
                }
            }
            if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
                if (instancesBuffer) {
                    instancesBuffer.dispose();
                }
                instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
                this._instancesBuffer = instancesBuffer;
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
            }
            else {
                instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
            }
            engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
            this._draw(subMesh, fillMode, instancesCount);
            engine.unbindInstanceAttributes();
        };
        Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
            var scene = this.getScene();
            var engine = scene.getEngine();
            if (hardwareInstancedRendering) {
                this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
            }
            else {
                if (batch.renderSelf[subMesh._id]) {
                    // Draw
                    if (onBeforeDraw) {
                        onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
                    }
                    this._draw(subMesh, fillMode, this._overridenInstanceCount);
                }
                if (batch.visibleInstances[subMesh._id]) {
                    for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
                        var instance = batch.visibleInstances[subMesh._id][instanceIndex];
                        // World
                        var world = instance.getWorldMatrix();
                        if (onBeforeDraw) {
                            onBeforeDraw(true, world, effectiveMaterial);
                        }
                        // Draw
                        this._draw(subMesh, fillMode);
                    }
                }
            }
        };
        /**
         * Triggers the draw call for the mesh.
         * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
         */
        Mesh.prototype.render = function (subMesh, enableAlphaMode) {
            var scene = this.getScene();
            // Managing instances
            var batch = this._getInstancesRenderList(subMesh._id);
            if (batch.mustReturn) {
                return;
            }
            // Checking geometry state
            if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
                return;
            }
            var callbackIndex;
            this.onBeforeRenderObservable.notifyObservers(this);
            var engine = scene.getEngine();
            var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
            // Material
            var effectiveMaterial = subMesh.getMaterial();
            if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
                return;
            }
            // Outline - step 1
            var savedDepthWrite = engine.getDepthWrite();
            if (this.renderOutline) {
                engine.setDepthWrite(false);
                scene.getOutlineRenderer().render(subMesh, batch);
                engine.setDepthWrite(savedDepthWrite);
            }
            effectiveMaterial._preBind();
            var effect = effectiveMaterial.getEffect();
            // Bind
            var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
            this._bind(subMesh, effect, fillMode);
            var world = this.getWorldMatrix();
            effectiveMaterial.bind(world, this);
            // Alpha mode
            if (enableAlphaMode) {
                engine.setAlphaMode(effectiveMaterial.alphaMode);
            }
            // Draw
            this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
            // Unbind
            effectiveMaterial.unbind();
            // Outline - step 2
            if (this.renderOutline && savedDepthWrite) {
                engine.setDepthWrite(true);
                engine.setColorWrite(false);
                scene.getOutlineRenderer().render(subMesh, batch);
                engine.setColorWrite(true);
            }
            // Overlay
            if (this.renderOverlay) {
                var currentMode = engine.getAlphaMode();
                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                scene.getOutlineRenderer().render(subMesh, batch, true);
                engine.setAlphaMode(currentMode);
            }
            this.onAfterRenderObservable.notifyObservers(this);
        };
        Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
            if (isInstance) {
                effectiveMaterial.bindOnlyWorldMatrix(world);
            }
        };
        /**
         * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
         */
        Mesh.prototype.getEmittedParticleSystems = function () {
            var results = new Array();
            for (var index = 0; index < this.getScene().particleSystems.length; index++) {
                var particleSystem = this.getScene().particleSystems[index];
                if (particleSystem.emitter === this) {
                    results.push(particleSystem);
                }
            }
            return results;
        };
        /**
         * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
         */
        Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
            var results = new Array();
            var descendants = this.getDescendants();
            descendants.push(this);
            for (var index = 0; index < this.getScene().particleSystems.length; index++) {
                var particleSystem = this.getScene().particleSystems[index];
                if (descendants.indexOf(particleSystem.emitter) !== -1) {
                    results.push(particleSystem);
                }
            }
            return results;
        };
        Mesh.prototype._checkDelayState = function () {
            var scene = this.getScene();
            if (this._geometry) {
                this._geometry.load(scene);
            }
            else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
                this._queueLoad(this, scene);
            }
        };
        Mesh.prototype._queueLoad = function (mesh, scene) {
            var _this = this;
            scene._addPendingData(mesh);
            var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
            BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
                if (data instanceof ArrayBuffer) {
                    _this._delayLoadingFunction(data, _this);
                }
                else {
                    _this._delayLoadingFunction(JSON.parse(data), _this);
                }
                _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
                scene._removePendingData(_this);
            }, function () { }, scene.database, getBinaryData);
        };
        /**
         * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
         */
        Mesh.prototype.isInFrustum = function (frustumPlanes) {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                return false;
            }
            if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
                return false;
            }
            this._checkDelayState();
            return true;
        };
        /**
         * Sets the mesh material by the material or multiMaterial `id` property.
         * The material `id` is a string identifying the material or the multiMaterial.
         * This method returns nothing.
         */
        Mesh.prototype.setMaterialByID = function (id) {
            var materials = this.getScene().materials;
            var index;
            for (index = 0; index < materials.length; index++) {
                if (materials[index].id === id) {
                    this.material = materials[index];
                    return;
                }
            }
            // Multi
            var multiMaterials = this.getScene().multiMaterials;
            for (index = 0; index < multiMaterials.length; index++) {
                if (multiMaterials[index].id === id) {
                    this.material = multiMaterials[index];
                    return;
                }
            }
        };
        /**
         * Returns as a new array populated with the mesh material and/or skeleton, if any.
         */
        Mesh.prototype.getAnimatables = function () {
            var results = [];
            if (this.material) {
                results.push(this.material);
            }
            if (this.skeleton) {
                results.push(this.skeleton);
            }
            return results;
        };
        /**
         * Modifies the mesh geometry according to the passed transformation matrix.
         * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
         * The mesh normals are modified accordingly the same transformation.
         * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
         * Note that, under the hood, this method sets a new VertexBuffer each call.
         */
        Mesh.prototype.bakeTransformIntoVertices = function (transform) {
            // Position
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                return;
            }
            var submeshes = this.subMeshes.splice(0);
            this._resetPointsArrayCache();
            var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var temp = [];
            var index;
            for (index = 0; index < data.length; index += 3) {
                BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
            }
            this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
            // Normals
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                return;
            }
            data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            temp = [];
            for (index = 0; index < data.length; index += 3) {
                BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
            }
            this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
            // flip faces?
            if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
                this.flipFaces();
            }
            // Restore submeshes
            this.releaseSubMeshes();
            this.subMeshes = submeshes;
        };
        /**
         * Modifies the mesh geometry according to its own current World Matrix.
         * The mesh World Matrix is then reset.
         * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
         * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
         * Note that, under the hood, this method sets a new VertexBuffer each call.
         */
        Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
            this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
            this.scaling.copyFromFloats(1, 1, 1);
            this.position.copyFromFloats(0, 0, 0);
            this.rotation.copyFromFloats(0, 0, 0);
            //only if quaternion is already set
            if (this.rotationQuaternion) {
                this.rotationQuaternion = BABYLON.Quaternion.Identity();
            }
            this._worldMatrix = BABYLON.Matrix.Identity();
        };
        // Cache
        Mesh.prototype._resetPointsArrayCache = function () {
            this._positions = null;
        };
        Mesh.prototype._generatePointsArray = function () {
            if (this._positions)
                return true;
            this._positions = [];
            var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!data) {
                return false;
            }
            for (var index = 0; index < data.length; index += 3) {
                this._positions.push(BABYLON.Vector3.FromArray(data, index));
            }
            return true;
        };
        /**
         * Returns a new Mesh object generated from the current mesh properties.
         * This method must not get confused with createInstance().
         * The parameter `name` is a string, the name given to the new mesh.
         * The optional parameter `newParent` can be any Node object (default `null`).
         * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
         * The parameter `clonePhysicsImpostor` (default `true`)  allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
         */
        Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
            if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
            return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
        };
        /**
         * Disposes the mesh.
         * This also frees the memory allocated under the hood to all the buffers used by WebGL.
         */
        Mesh.prototype.dispose = function (doNotRecurse) {
            if (this._geometry) {
                this._geometry.releaseForMesh(this, true);
            }
            // Instances
            if (this._instancesBuffer) {
                this._instancesBuffer.dispose();
                this._instancesBuffer = null;
            }
            while (this.instances.length) {
                this.instances[0].dispose();
            }
            // Highlight layers.
            var highlightLayers = this.getScene().highlightLayers;
            for (var i = 0; i < highlightLayers.length; i++) {
                var highlightLayer = highlightLayers[i];
                if (highlightLayer) {
                    highlightLayer.removeMesh(this);
                    highlightLayer.removeExcludedMesh(this);
                }
            }
            _super.prototype.dispose.call(this, doNotRecurse);
        };
        /**
         * Modifies the mesh geometry according to a displacement map.
         * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
         * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
         * This method returns nothing.
         * The parameter `url` is a string, the URL from the image file is to be downloaded.
         * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
         * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
         */
        Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
            var _this = this;
            var scene = this.getScene();
            var onload = function (img) {
                // Getting height map data
                var canvas = document.createElement("canvas");
                var context = canvas.getContext("2d");
                var heightMapWidth = img.width;
                var heightMapHeight = img.height;
                canvas.width = heightMapWidth;
                canvas.height = heightMapHeight;
                context.drawImage(img, 0, 0);
                // Create VertexData from map data
                //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
                var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
                _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
                //execute success callback, if set
                if (onSuccess) {
                    onSuccess(_this);
                }
            };
            BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
        };
        /**
         * Modifies the mesh geometry according to a displacementMap buffer.
         * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
         * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
         * This method returns nothing.
         * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
         * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
         * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
         */
        Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
                || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
                || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
                return;
            }
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var position = BABYLON.Vector3.Zero();
            var normal = BABYLON.Vector3.Zero();
            var uv = BABYLON.Vector2.Zero();
            for (var index = 0; index < positions.length; index += 3) {
                BABYLON.Vector3.FromArrayToRef(positions, index, position);
                BABYLON.Vector3.FromArrayToRef(normals, index, normal);
                BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
                // Compute height
                var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
                var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
                var pos = (u + v * heightMapWidth) * 4;
                var r = buffer[pos] / 255.0;
                var g = buffer[pos + 1] / 255.0;
                var b = buffer[pos + 2] / 255.0;
                var gradient = r * 0.3 + g * 0.59 + b * 0.11;
                normal.normalize();
                normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
                position = position.add(normal);
                position.toArray(positions, index);
            }
            BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
            this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
            this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
        };
        /**
         * Modify the mesh to get a flat shading rendering.
         * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
         * This method returns nothing.
         * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
         */
        Mesh.prototype.convertToFlatShadedMesh = function () {
            /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
            /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
            var kinds = this.getVerticesDataKinds();
            var vbs = [];
            var data = [];
            var newdata = [];
            var updatableNormals = false;
            var kindIndex;
            var kind;
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                var vertexBuffer = this.getVertexBuffer(kind);
                if (kind === BABYLON.VertexBuffer.NormalKind) {
                    updatableNormals = vertexBuffer.isUpdatable();
                    kinds.splice(kindIndex, 1);
                    kindIndex--;
                    continue;
                }
                vbs[kind] = vertexBuffer;
                data[kind] = vbs[kind].getData();
                newdata[kind] = [];
            }
            // Save previous submeshes
            var previousSubmeshes = this.subMeshes.slice(0);
            var indices = this.getIndices();
            var totalIndices = this.getTotalIndices();
            // Generating unique vertices per face
            var index;
            for (index = 0; index < totalIndices; index++) {
                var vertexIndex = indices[index];
                for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                    kind = kinds[kindIndex];
                    var stride = vbs[kind].getStrideSize();
                    for (var offset = 0; offset < stride; offset++) {
                        newdata[kind].push(data[kind][vertexIndex * stride + offset]);
                    }
                }
            }
            // Updating faces & normal
            var normals = [];
            var positions = newdata[BABYLON.VertexBuffer.PositionKind];
            for (index = 0; index < totalIndices; index += 3) {
                indices[index] = index;
                indices[index + 1] = index + 1;
                indices[index + 2] = index + 2;
                var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
                var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
                var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
                var p1p2 = p1.subtract(p2);
                var p3p2 = p3.subtract(p2);
                var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
                // Store same normals for every vertex
                for (var localIndex = 0; localIndex < 3; localIndex++) {
                    normals.push(normal.x);
                    normals.push(normal.y);
                    normals.push(normal.z);
                }
            }
            this.setIndices(indices);
            this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
            // Updating vertex buffers
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
            }
            // Updating submeshes
            this.releaseSubMeshes();
            for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
                var previousOne = previousSubmeshes[submeshIndex];
                var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
            }
            this.synchronizeInstances();
        };
        /**
         * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
         * In other words, more vertices, no more indices and a single bigger VBO.
         * This method returns nothing.
         * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
         *
         */
        Mesh.prototype.convertToUnIndexedMesh = function () {
            /// <summary>Remove indices by unfolding faces into buffers</summary>
            /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
            var kinds = this.getVerticesDataKinds();
            var vbs = [];
            var data = [];
            var newdata = [];
            var updatableNormals = false;
            var kindIndex;
            var kind;
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                var vertexBuffer = this.getVertexBuffer(kind);
                vbs[kind] = vertexBuffer;
                data[kind] = vbs[kind].getData();
                newdata[kind] = [];
            }
            // Save previous submeshes
            var previousSubmeshes = this.subMeshes.slice(0);
            var indices = this.getIndices();
            var totalIndices = this.getTotalIndices();
            // Generating unique vertices per face
            var index;
            for (index = 0; index < totalIndices; index++) {
                var vertexIndex = indices[index];
                for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                    kind = kinds[kindIndex];
                    var stride = vbs[kind].getStrideSize();
                    for (var offset = 0; offset < stride; offset++) {
                        newdata[kind].push(data[kind][vertexIndex * stride + offset]);
                    }
                }
            }
            // Updating indices
            for (index = 0; index < totalIndices; index += 3) {
                indices[index] = index;
                indices[index + 1] = index + 1;
                indices[index + 2] = index + 2;
            }
            this.setIndices(indices);
            // Updating vertex buffers
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
            }
            // Updating submeshes
            this.releaseSubMeshes();
            for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
                var previousOne = previousSubmeshes[submeshIndex];
                var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
            }
            this._unIndexed = true;
            this.synchronizeInstances();
        };
        /**
         * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
         * This method returns nothing.
         * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
         */
        Mesh.prototype.flipFaces = function (flipNormals) {
            if (flipNormals === void 0) { flipNormals = false; }
            var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
            var i;
            if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                for (i = 0; i < vertex_data.normals.length; i++) {
                    vertex_data.normals[i] *= -1;
                }
            }
            var temp;
            for (i = 0; i < vertex_data.indices.length; i += 3) {
                // reassign indices
                temp = vertex_data.indices[i + 1];
                vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
                vertex_data.indices[i + 2] = temp;
            }
            vertex_data.applyToMesh(this);
        };
        // Instances
        /**
         * Creates a new InstancedMesh object from the mesh model.
         * An instance shares the same properties and the same material than its model.
         * Only these properties of each instance can then be set individually :
         * - position
         * - rotation
         * - rotationQuaternion
         * - setPivotMatrix
         * - scaling
         * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
         * Warning : this method is not supported for Line mesh and LineSystem
         */
        Mesh.prototype.createInstance = function (name) {
            return new BABYLON.InstancedMesh(name, this);
        };
        /**
         * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
         * After this call, all the mesh instances have the same submeshes than the current mesh.
         * This method returns nothing.
         */
        Mesh.prototype.synchronizeInstances = function () {
            for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
                var instance = this.instances[instanceIndex];
                instance._syncSubMeshes();
            }
        };
        /**
         * Simplify the mesh according to the given array of settings.
         * Function will return immediately and will simplify async. It returns nothing.
         * @param settings a collection of simplification settings.
         * @param parallelProcessing should all levels calculate parallel or one after the other.
         * @param type the type of simplification to run.
         * @param successCallback optional success callback to be called after the simplification finished processing all settings.
         */
        Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
            if (parallelProcessing === void 0) { parallelProcessing = true; }
            if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
            this.getScene().simplificationQueue.addTask({
                settings: settings,
                parallelProcessing: parallelProcessing,
                mesh: this,
                simplificationType: simplificationType,
                successCallback: successCallback
            });
        };
        /**
         * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
         * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
         * This should be used together with the simplification to avoid disappearing triangles.
         * @param successCallback an optional success callback to be called after the optimization finished.
         */
        Mesh.prototype.optimizeIndices = function (successCallback) {
            var _this = this;
            var indices = this.getIndices();
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var vectorPositions = [];
            for (var pos = 0; pos < positions.length; pos = pos + 3) {
                vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
            }
            var dupes = [];
            BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
                var realPos = vectorPositions.length - 1 - iteration;
                var testedPosition = vectorPositions[realPos];
                for (var j = 0; j < realPos; ++j) {
                    var againstPosition = vectorPositions[j];
                    if (testedPosition.equals(againstPosition)) {
                        dupes[realPos] = j;
                        break;
                    }
                }
            }, function () {
                for (var i = 0; i < indices.length; ++i) {
                    indices[i] = dupes[indices[i]] || indices[i];
                }
                //indices are now reordered
                var originalSubMeshes = _this.subMeshes.slice(0);
                _this.setIndices(indices);
                _this.subMeshes = originalSubMeshes;
                if (successCallback) {
                    successCallback(_this);
                }
            });
        };
        // Statics
        /**
         * Returns a new Mesh object what is a deep copy of the passed mesh.
         * The parameter `parsedMesh` is the mesh to be copied.
         * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
         */
        Mesh.Parse = function (parsedMesh, scene, rootUrl) {
            var mesh = new Mesh(parsedMesh.name, scene);
            mesh.id = parsedMesh.id;
            BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
            mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
            if (parsedMesh.metadata !== undefined) {
                mesh.metadata = parsedMesh.metadata;
            }
            if (parsedMesh.rotationQuaternion) {
                mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
            }
            else if (parsedMesh.rotation) {
                mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
            }
            mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
            if (parsedMesh.localMatrix) {
                mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
            }
            else if (parsedMesh.pivotMatrix) {
                mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
            }
            mesh.setEnabled(parsedMesh.isEnabled);
            mesh.isVisible = parsedMesh.isVisible;
            mesh.infiniteDistance = parsedMesh.infiniteDistance;
            mesh.showBoundingBox = parsedMesh.showBoundingBox;
            mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
            if (parsedMesh.applyFog !== undefined) {
                mesh.applyFog = parsedMesh.applyFog;
            }
            if (parsedMesh.pickable !== undefined) {
                mesh.isPickable = parsedMesh.pickable;
            }
            if (parsedMesh.alphaIndex !== undefined) {
                mesh.alphaIndex = parsedMesh.alphaIndex;
            }
            mesh.receiveShadows = parsedMesh.receiveShadows;
            mesh.billboardMode = parsedMesh.billboardMode;
            if (parsedMesh.visibility !== undefined) {
                mesh.visibility = parsedMesh.visibility;
            }
            mesh.checkCollisions = parsedMesh.checkCollisions;
            if (parsedMesh.isBlocker !== undefined) {
                mesh.isBlocker = parsedMesh.isBlocker;
            }
            mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
            // freezeWorldMatrix
            if (parsedMesh.freezeWorldMatrix) {
                mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
            }
            // Parent
            if (parsedMesh.parentId) {
                mesh._waitingParentId = parsedMesh.parentId;
            }
            // Actions
            if (parsedMesh.actions !== undefined) {
                mesh._waitingActions = parsedMesh.actions;
            }
            // Overlay
            if (parsedMesh.overlayAlpha !== undefined) {
                mesh.overlayAlpha = parsedMesh.overlayAlpha;
            }
            if (parsedMesh.overlayColor !== undefined) {
                mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
            }
            if (parsedMesh.renderOverlay !== undefined) {
                mesh.renderOverlay = parsedMesh.renderOverlay;
            }
            // Geometry
            mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
            if (parsedMesh.delayLoadingFile) {
                mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
                mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
                if (parsedMesh._binaryInfo) {
                    mesh._binaryInfo = parsedMesh._binaryInfo;
                }
                mesh._delayInfo = [];
                if (parsedMesh.hasUVs) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
                }
                if (parsedMesh.hasUVs2) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (parsedMesh.hasUVs3) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
                }
                if (parsedMesh.hasUVs4) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
                }
                if (parsedMesh.hasUVs5) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
                }
                if (parsedMesh.hasUVs6) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
                }
                if (parsedMesh.hasColors) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
                }
                if (parsedMesh.hasMatricesIndices) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                }
                if (parsedMesh.hasMatricesWeights) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                }
                mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
                if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
                    mesh._checkDelayState();
                }
            }
            else {
                BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
            }
            // Material
            if (parsedMesh.materialId) {
                mesh.setMaterialByID(parsedMesh.materialId);
            }
            else {
                mesh.material = null;
            }
            // Skeleton
            if (parsedMesh.skeletonId > -1) {
                mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
                if (parsedMesh.numBoneInfluencers) {
                    mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
                }
            }
            // Animations
            if (parsedMesh.animations) {
                for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
                    var parsedAnimation = parsedMesh.animations[animationIndex];
                    mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
            }
            if (parsedMesh.autoAnimate) {
                scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
            }
            // Layer Mask
            if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
                mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
            }
            else {
                mesh.layerMask = 0x0FFFFFFF;
            }
            //(Deprecated) physics
            if (parsedMesh.physicsImpostor) {
                mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
                    mass: parsedMesh.physicsMass,
                    friction: parsedMesh.physicsFriction,
                    restitution: parsedMesh.physicsRestitution
                }, scene);
            }
            // Instances
            if (parsedMesh.instances) {
                for (var index = 0; index < parsedMesh.instances.length; index++) {
                    var parsedInstance = parsedMesh.instances[index];
                    var instance = mesh.createInstance(parsedInstance.name);
                    BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
                    instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
                    if (parsedInstance.parentId) {
                        instance._waitingParentId = parsedInstance.parentId;
                    }
                    if (parsedInstance.rotationQuaternion) {
                        instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
                    }
                    else if (parsedInstance.rotation) {
                        instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
                    }
                    instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
                    instance.checkCollisions = mesh.checkCollisions;
                    if (parsedMesh.animations) {
                        for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
                            parsedAnimation = parsedMesh.animations[animationIndex];
                            instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                        }
                        BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
                    }
                }
            }
            return mesh;
        };
        /**
         * Creates a ribbon mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The ribbon is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         *
         * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
         * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
         * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
         * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
         * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
         * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
         * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
            return BABYLON.MeshBuilder.CreateRibbon(name, {
                pathArray: pathArray,
                closeArray: closeArray,
                closePath: closePath,
                offset: offset,
                updatable: updatable,
                sideOrientation: sideOrientation,
                instance: instance
            }, scene);
        };
        /**
         * Creates a plane polygonal mesh.  By default, this is a disc.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
         * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
            var options = {
                radius: radius,
                tessellation: tessellation,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
        };
        /**
         * Creates a box mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `size` sets the size (float) of each box side (default 1).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
            var options = {
                size: size,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateBox(name, options, scene);
        };
        /**
         * Creates a sphere mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
         * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
            var options = {
                segments: segments,
                diameterX: diameter,
                diameterY: diameter,
                diameterZ: diameter,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
        };
        /**
         * Creates a cylinder or a cone mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
         * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
         * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
         * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
         * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
            if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
                if (scene !== undefined) {
                    sideOrientation = updatable || Mesh.DEFAULTSIDE;
                    updatable = scene;
                }
                scene = subdivisions;
                subdivisions = 1;
            }
            var options = {
                height: height,
                diameterTop: diameterTop,
                diameterBottom: diameterBottom,
                tessellation: tessellation,
                subdivisions: subdivisions,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
        };
        // Torus  (Code from SharpDX.org)
        /**
         * Creates a torus mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
         * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
         * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
            var options = {
                diameter: diameter,
                thickness: thickness,
                tessellation: tessellation,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
        };
        /**
         * Creates a torus knot mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
         * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
         * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
         * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
            var options = {
                radius: radius,
                tube: tube,
                radialSegments: radialSegments,
                tubularSegments: tubularSegments,
                p: p,
                q: q,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
        };
        /**
         * Creates a line mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
         * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
         * The parameter `points` is an array successive Vector3.
         * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * When updating an instance, remember that only point positions can change, not the number of points.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateLines = function (name, points, scene, updatable, instance) {
            var options = {
                points: points,
                updatable: updatable,
                instance: instance
            };
            return BABYLON.MeshBuilder.CreateLines(name, options, scene);
        };
        /**
         * Creates a dashed line mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
         * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
         * The parameter `points` is an array successive Vector3.
         * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
         * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
         * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
         * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * When updating an instance, remember that only point positions can change, not the number of points.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
            var options = {
                points: points,
                dashSize: dashSize,
                gapSize: gapSize,
                dashNb: dashNb,
                updatable: updatable,
                instance: instance
            };
            return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
        };
        /**
         * Creates an extruded shape mesh.
         * The extrusion is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         * Please consider using the same method from the MeshBuilder class instead.
         *
         * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
         * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
         * extruded along the Z axis.
         * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
         * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
         * The parameter `scale` (float, default 1) is the value to scale the shape.
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
         * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
            var options = {
                shape: shape,
                path: path,
                scale: scale,
                rotation: rotation,
                cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
                sideOrientation: sideOrientation,
                instance: instance,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
        };
        /**
         * Creates an custom extruded shape mesh.
         * The custom extrusion is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         * Please consider using the same method from the MeshBuilder class instead.
         *
         * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
         * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
         * extruded along the Z axis.
         * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
         * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
         * and the distance of this point from the begining of the path :
         * ```javascript
         * var rotationFunction = function(i, distance) {
         *     // do things
         *     return rotationValue; }
         * ```
         * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
         * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
         * and the distance of this point from the begining of the path :
         * ```javascript
         * var scaleFunction = function(i, distance) {
         *     // do things
         *    return scaleValue;}
         * ```
         * It must returns a float value that will be the scale value applied to the shape on each path point.
         * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
         * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
         * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
            var options = {
                shape: shape,
                path: path,
                scaleFunction: scaleFunction,
                rotationFunction: rotationFunction,
                ribbonCloseArray: ribbonCloseArray,
                ribbonClosePath: ribbonClosePath,
                cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
                sideOrientation: sideOrientation,
                instance: instance,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
        };
        /**
         * Creates lathe mesh.
         * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
         * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
         * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
         * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
            var options = {
                shape: shape,
                radius: radius,
                tessellation: tessellation,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
        };
        /**
         * Creates a plane mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
            var options = {
                size: size,
                width: size,
                height: size,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
        };
        /**
         * Creates a ground mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
         * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
            var options = {
                width: width,
                height: height,
                subdivisions: subdivisions,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateGround(name, options, scene);
        };
        /**
         * Creates a tiled ground mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
         * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
         * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
         * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
         * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
         * numbers of subdivisions on the ground width and height of each tile.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
            var options = {
                xmin: xmin,
                zmin: zmin,
                xmax: xmax,
                zmax: zmax,
                subdivisions: subdivisions,
                precision: precision,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
        };
        /**
         * Creates a ground mesh from a height map.
         * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `url` sets the URL of the height map image resource.
         * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
         * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
         * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
         * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
         * The parameter `onReady` is a javascript callback function that will be called  once the mesh is just built (the height map download can last some time).
         * This function is passed the newly built mesh :
         * ```javascript
         * function(mesh) { // do things
         *     return; }
         * ```
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
            var options = {
                width: width,
                height: height,
                subdivisions: subdivisions,
                minHeight: minHeight,
                maxHeight: maxHeight,
                updatable: updatable,
                onReady: onReady
            };
            return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
        };
        /**
         * Creates a tube mesh.
         * The tube is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
         * The parameter `radius` (positive float, default 1) sets the tube radius size.
         * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
         * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
         * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
         * It must return a radius value (positive float) :
         * ```javascript
         * var radiusFunction = function(i, distance) {
         *     // do things
         *     return radius; }
         * ```
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
            var options = {
                path: path,
                radius: radius,
                tessellation: tessellation,
                radiusFunction: radiusFunction,
                arc: 1,
                cap: cap,
                updatable: updatable,
                sideOrientation: sideOrientation,
                instance: instance
            };
            return BABYLON.MeshBuilder.CreateTube(name, options, scene);
        };
        /**
         * Creates a polyhedron mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
         *  to choose the wanted type.
         * The parameter `size` (positive float, default 1) sets the polygon size.
         * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
         * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
         * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
         * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
         * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
         * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreatePolyhedron = function (name, options, scene) {
            return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
        };
        /**
         * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
         * Please consider using the same method from the MeshBuilder class instead.
         * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
         * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
         * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
         * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        Mesh.CreateIcoSphere = function (name, options, scene) {
            return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
        };
        /**
         * Creates a decal mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
         * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
         * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
         * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
         * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
         */
        Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
            var options = {
                position: position,
                normal: normal,
                size: size,
                angle: angle
            };
            return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
        };
        // Skeletons
        /**
         * @returns original positions used for CPU skinning.  Useful for integrating Morphing with skeletons in same mesh.
         */
        Mesh.prototype.setPositionsForCPUSkinning = function () {
            var source;
            if (!this._sourcePositions) {
                source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                this._sourcePositions = new Float32Array(source);
                if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
                    this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
                }
            }
            return this._sourcePositions;
        };
        /**
         * @returns original normals used for CPU skinning.  Useful for integrating Morphing with skeletons in same mesh.
         */
        Mesh.prototype.setNormalsForCPUSkinning = function () {
            var source;
            if (!this._sourceNormals) {
                source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                this._sourceNormals = new Float32Array(source);
                if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
                    this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
                }
            }
            return this._sourceNormals;
        };
        /**
         * Update the vertex buffers by applying transformation from the bones
         * @param {skeleton} skeleton to apply
         */
        Mesh.prototype.applySkeleton = function (skeleton) {
            if (!this.geometry) {
                return;
            }
            if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
                return;
            }
            this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                return this;
            }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                return this;
            }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                return this;
            }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                return this;
            }
            if (!this._sourcePositions) {
                var submeshes = this.subMeshes.slice();
                this.setPositionsForCPUSkinning();
                this.subMeshes = submeshes;
            }
            if (!this._sourceNormals) {
                this.setNormalsForCPUSkinning();
            }
            // positionsData checks for not being Float32Array will only pass at most once
            var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!(positionsData instanceof Float32Array)) {
                positionsData = new Float32Array(positionsData);
            }
            // normalsData checks for not being Float32Array will only pass at most once
            var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            if (!(normalsData instanceof Float32Array)) {
                normalsData = new Float32Array(normalsData);
            }
            var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
            var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
            var needExtras = this.numBoneInfluencers > 4;
            var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
            var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
            var skeletonMatrices = skeleton.getTransformMatrices(this);
            var tempVector3 = BABYLON.Vector3.Zero();
            var finalMatrix = new BABYLON.Matrix();
            var tempMatrix = new BABYLON.Matrix();
            var matWeightIdx = 0;
            var inf;
            for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
                var weight;
                for (inf = 0; inf < 4; inf++) {
                    weight = matricesWeightsData[matWeightIdx + inf];
                    if (weight > 0) {
                        BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
                        finalMatrix.addToSelf(tempMatrix);
                    }
                    else
                        break;
                }
                if (needExtras) {
                    for (inf = 0; inf < 4; inf++) {
                        weight = matricesWeightsExtraData[matWeightIdx + inf];
                        if (weight > 0) {
                            BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
                            finalMatrix.addToSelf(tempMatrix);
                        }
                        else
                            break;
                    }
                }
                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
                tempVector3.toArray(positionsData, index);
                BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
                tempVector3.toArray(normalsData, index);
                finalMatrix.reset();
            }
            this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
            this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
            return this;
        };
        // Tools
        /**
         * Returns an object `{min:` Vector3`, max:` Vector3`}`
         * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
         */
        Mesh.MinMax = function (meshes) {
            var minVector = null;
            var maxVector = null;
            meshes.forEach(function (mesh, index, array) {
                var boundingBox = mesh.getBoundingInfo().boundingBox;
                if (!minVector) {
                    minVector = boundingBox.minimumWorld;
                    maxVector = boundingBox.maximumWorld;
                }
                else {
                    minVector.MinimizeInPlace(boundingBox.minimumWorld);
                    maxVector.MaximizeInPlace(boundingBox.maximumWorld);
                }
            });
            return {
                min: minVector,
                max: maxVector
            };
        };
        /**
         * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
         */
        Mesh.Center = function (meshesOrMinMaxVector) {
            var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
            return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
        };
        /**
         * Merge the array of meshes into a single mesh for performance reasons.
         * @param {Array<Mesh>} meshes - The vertices source.  They should all be of the same material.  Entries can empty
         * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
         * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
         * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh.  Meshes can then be merged into a Mesh sub-class.
         */
        Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
            if (disposeSource === void 0) { disposeSource = true; }
            var index;
            if (!allow32BitsIndices) {
                var totalVertices = 0;
                // Counting vertices
                for (index = 0; index < meshes.length; index++) {
                    if (meshes[index]) {
                        totalVertices += meshes[index].getTotalVertices();
                        if (totalVertices > 65536) {
                            BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
                            return null;
                        }
                    }
                }
            }
            // Merge
            var vertexData;
            var otherVertexData;
            var source;
            for (index = 0; index < meshes.length; index++) {
                if (meshes[index]) {
                    meshes[index].computeWorldMatrix(true);
                    otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
                    otherVertexData.transform(meshes[index].getWorldMatrix());
                    if (vertexData) {
                        vertexData.merge(otherVertexData);
                    }
                    else {
                        vertexData = otherVertexData;
                        source = meshes[index];
                    }
                }
            }
            if (!meshSubclass) {
                meshSubclass = new Mesh(source.name + "_merged", source.getScene());
            }
            vertexData.applyToMesh(meshSubclass);
            // Setting properties
            meshSubclass.material = source.material;
            meshSubclass.checkCollisions = source.checkCollisions;
            // Cleaning
            if (disposeSource) {
                for (index = 0; index < meshes.length; index++) {
                    if (meshes[index]) {
                        meshes[index].dispose();
                    }
                }
            }
            return meshSubclass;
        };
        // Consts
        Mesh._FRONTSIDE = 0;
        Mesh._BACKSIDE = 1;
        Mesh._DOUBLESIDE = 2;
        Mesh._DEFAULTSIDE = 0;
        Mesh._NO_CAP = 0;
        Mesh._CAP_START = 1;
        Mesh._CAP_END = 2;
        Mesh._CAP_ALL = 3;
        return Mesh;
    }(BABYLON.AbstractMesh));
    BABYLON.Mesh = Mesh;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.mesh.js.map
 
var BABYLON;
(function (BABYLON) {
    var SubMesh = (function () {
        function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
            if (createBoundingBox === void 0) { createBoundingBox = true; }
            this.materialIndex = materialIndex;
            this.verticesStart = verticesStart;
            this.verticesCount = verticesCount;
            this.indexStart = indexStart;
            this.indexCount = indexCount;
            this._renderId = 0;
            this._mesh = mesh;
            this._renderingMesh = renderingMesh || mesh;
            mesh.subMeshes.push(this);
            this._trianglePlanes = [];
            this._id = mesh.subMeshes.length - 1;
            if (createBoundingBox) {
                this.refreshBoundingInfo();
                mesh.computeWorldMatrix(true);
            }
        }
        Object.defineProperty(SubMesh.prototype, "IsGlobal", {
            get: function () {
                return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
            },
            enumerable: true,
            configurable: true
        });
        SubMesh.prototype.getBoundingInfo = function () {
            if (this.IsGlobal) {
                return this._mesh.getBoundingInfo();
            }
            return this._boundingInfo;
        };
        SubMesh.prototype.getMesh = function () {
            return this._mesh;
        };
        SubMesh.prototype.getRenderingMesh = function () {
            return this._renderingMesh;
        };
        SubMesh.prototype.getMaterial = function () {
            var rootMaterial = this._renderingMesh.material;
            if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
                var multiMaterial = rootMaterial;
                return multiMaterial.getSubMaterial(this.materialIndex);
            }
            if (!rootMaterial) {
                return this._mesh.getScene().defaultMaterial;
            }
            return rootMaterial;
        };
        // Methods
        SubMesh.prototype.refreshBoundingInfo = function () {
            this._lastColliderWorldVertices = null;
            if (this.IsGlobal) {
                return;
            }
            var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!data) {
                this._boundingInfo = this._mesh._boundingInfo;
                return;
            }
            var indices = this._renderingMesh.getIndices();
            var extend;
            //is this the only submesh?
            if (this.indexStart === 0 && this.indexCount === indices.length) {
                //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
                extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
            }
            else {
                extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
            }
            this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
        };
        SubMesh.prototype._checkCollision = function (collider) {
            return this.getBoundingInfo()._checkCollision(collider);
        };
        SubMesh.prototype.updateBoundingInfo = function (world) {
            if (!this.getBoundingInfo()) {
                this.refreshBoundingInfo();
            }
            this.getBoundingInfo().update(world);
        };
        SubMesh.prototype.isInFrustum = function (frustumPlanes) {
            return this.getBoundingInfo().isInFrustum(frustumPlanes);
        };
        SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
        };
        SubMesh.prototype.render = function (enableAlphaMode) {
            this._renderingMesh.render(this, enableAlphaMode);
        };
        SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
            if (!this._linesIndexBuffer) {
                var linesIndices = [];
                for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
                    linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
                }
                this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
                this.linesIndexCount = linesIndices.length;
            }
            return this._linesIndexBuffer;
        };
        SubMesh.prototype.canIntersects = function (ray) {
            return ray.intersectsBox(this.getBoundingInfo().boundingBox);
        };
        SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
            var intersectInfo = null;
            // LineMesh first as it's also a Mesh...
            if (this._mesh instanceof BABYLON.LinesMesh) {
                var lineMesh = this._mesh;
                // Line test
                for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
                    var p0 = positions[indices[index]];
                    var p1 = positions[indices[index + 1]];
                    var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
                    if (length < 0) {
                        continue;
                    }
                    if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
                        intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
                        if (fastCheck) {
                            break;
                        }
                    }
                }
            }
            else {
                // Triangles test
                for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
                    var p0 = positions[indices[index]];
                    var p1 = positions[indices[index + 1]];
                    var p2 = positions[indices[index + 2]];
                    var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
                    if (currentIntersectInfo) {
                        if (currentIntersectInfo.distance < 0) {
                            continue;
                        }
                        if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
                            intersectInfo = currentIntersectInfo;
                            intersectInfo.faceId = index / 3;
                            if (fastCheck) {
                                break;
                            }
                        }
                    }
                }
            }
            return intersectInfo;
        };
        // Clone    
        SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
            var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
            if (!this.IsGlobal) {
                result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
            }
            return result;
        };
        // Dispose
        SubMesh.prototype.dispose = function () {
            if (this._linesIndexBuffer) {
                this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
                this._linesIndexBuffer = null;
            }
            // Remove from mesh
            var index = this._mesh.subMeshes.indexOf(this);
            this._mesh.subMeshes.splice(index, 1);
        };
        // Statics
        SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
            var minVertexIndex = Number.MAX_VALUE;
            var maxVertexIndex = -Number.MAX_VALUE;
            renderingMesh = renderingMesh || mesh;
            var indices = renderingMesh.getIndices();
            for (var index = startIndex; index < startIndex + indexCount; index++) {
                var vertexIndex = indices[index];
                if (vertexIndex < minVertexIndex)
                    minVertexIndex = vertexIndex;
                if (vertexIndex > maxVertexIndex)
                    maxVertexIndex = vertexIndex;
            }
            return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
        };
        return SubMesh;
    }());
    BABYLON.SubMesh = SubMesh;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.subMesh.js.map
 
var BABYLON;
(function (BABYLON) {
    var MeshBuilder = (function () {
        function MeshBuilder() {
        }
        MeshBuilder.updateSideOrientation = function (orientation, scene) {
            if (orientation == BABYLON.Mesh.DOUBLESIDE) {
                return BABYLON.Mesh.DOUBLESIDE;
            }
            if (orientation === undefined || orientation === null) {
                return BABYLON.Mesh.FRONTSIDE;
            }
            return orientation;
        };
        /**
         * Creates a box mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
         * The parameter `size` sets the size (float) of each box side (default 1).
         * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
         * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
         * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateBox = function (name, options, scene) {
            var box = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateBox(options);
            vertexData.applyToMesh(box, options.updatable);
            return box;
        };
        /**
         * Creates a sphere mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
         * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
         * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
         * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
         * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
         * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateSphere = function (name, options, scene) {
            var sphere = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateSphere(options);
            vertexData.applyToMesh(sphere, options.updatable);
            return sphere;
        };
        /**
         * Creates a plane polygonal mesh.  By default, this is a disc.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
         * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
         * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
         * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateDisc = function (name, options, scene) {
            var disc = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateDisc(options);
            vertexData.applyToMesh(disc, options.updatable);
            return disc;
        };
        /**
         * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
         * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
         * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
         * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
         * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateIcoSphere = function (name, options, scene) {
            var sphere = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
            vertexData.applyToMesh(sphere, options.updatable);
            return sphere;
        };
        ;
        /**
         * Creates a ribbon mesh.
         * The ribbon is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         *
         * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
         * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
         * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
         * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
         * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
         * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
         * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateRibbon = function (name, options, scene) {
            var pathArray = options.pathArray;
            var closeArray = options.closeArray;
            var closePath = options.closePath;
            var offset = options.offset;
            var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var instance = options.instance;
            var updatable = options.updatable;
            if (instance) {
                // positionFunction : ribbon case
                // only pathArray and sideOrientation parameters are taken into account for positions update
                BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
                BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
                var positionFunction = function (positions) {
                    var minlg = pathArray[0].length;
                    var i = 0;
                    var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
                    for (var si = 1; si <= ns; si++) {
                        for (var p = 0; p < pathArray.length; p++) {
                            var path = pathArray[p];
                            var l = path.length;
                            minlg = (minlg < l) ? minlg : l;
                            var j = 0;
                            while (j < minlg) {
                                positions[i] = path[j].x;
                                positions[i + 1] = path[j].y;
                                positions[i + 2] = path[j].z;
                                if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
                                    BABYLON.Tmp.Vector3[0].x = path[j].x;
                                }
                                if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
                                    BABYLON.Tmp.Vector3[1].x = path[j].x;
                                }
                                if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
                                    BABYLON.Tmp.Vector3[0].y = path[j].y;
                                }
                                if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
                                    BABYLON.Tmp.Vector3[1].y = path[j].y;
                                }
                                if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
                                    BABYLON.Tmp.Vector3[0].z = path[j].z;
                                }
                                if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
                                    BABYLON.Tmp.Vector3[1].z = path[j].z;
                                }
                                j++;
                                i += 3;
                            }
                            if (instance._closePath) {
                                positions[i] = path[0].x;
                                positions[i + 1] = path[0].y;
                                positions[i + 2] = path[0].z;
                                i += 3;
                            }
                        }
                    }
                };
                var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                positionFunction(positions);
                instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
                instance._boundingInfo.update(instance._worldMatrix);
                instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
                if (!(instance.areNormalsFrozen)) {
                    var indices = instance.getIndices();
                    var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                    BABYLON.VertexData.ComputeNormals(positions, indices, normals);
                    if (instance._closePath) {
                        var indexFirst = 0;
                        var indexLast = 0;
                        for (var p = 0; p < pathArray.length; p++) {
                            indexFirst = instance._idx[p] * 3;
                            if (p + 1 < pathArray.length) {
                                indexLast = (instance._idx[p + 1] - 1) * 3;
                            }
                            else {
                                indexLast = normals.length - 3;
                            }
                            normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
                            normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
                            normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
                            normals[indexLast] = normals[indexFirst];
                            normals[indexLast + 1] = normals[indexFirst + 1];
                            normals[indexLast + 2] = normals[indexFirst + 2];
                        }
                    }
                    instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
                }
                return instance;
            }
            else {
                var ribbon = new BABYLON.Mesh(name, scene);
                ribbon.sideOrientation = sideOrientation;
                var vertexData = BABYLON.VertexData.CreateRibbon(options);
                if (closePath) {
                    ribbon._idx = vertexData._idx;
                }
                ribbon._closePath = closePath;
                ribbon._closeArray = closeArray;
                vertexData.applyToMesh(ribbon, updatable);
                return ribbon;
            }
        };
        /**
         * Creates a cylinder or a cone mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
         * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
         * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
         * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
         * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
         * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
         * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
         * The parameter `enclose`  (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
         * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
         * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
         * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
         * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
         * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
         * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
         * If `enclose` is false, a ring surface is one element.
         * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
         * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateCylinder = function (name, options, scene) {
            var cylinder = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateCylinder(options);
            vertexData.applyToMesh(cylinder, options.updatable);
            return cylinder;
        };
        /**
         * Creates a torus mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
         * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
         * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
         * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateTorus = function (name, options, scene) {
            var torus = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateTorus(options);
            vertexData.applyToMesh(torus, options.updatable);
            return torus;
        };
        /**
         * Creates a torus knot mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
         * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
         * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
         * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
         * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateTorusKnot = function (name, options, scene) {
            var torusKnot = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
            vertexData.applyToMesh(torusKnot, options.updatable);
            return torusKnot;
        };
        /**
         * Creates a line system mesh.
         * A line system is a pool of many lines gathered in a single mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
         * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
         * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
         * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
         * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
         * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateLineSystem = function (name, options, scene) {
            var instance = options.instance;
            var lines = options.lines;
            if (instance) {
                var positionFunction = function (positions) {
                    var i = 0;
                    for (var l = 0; l < lines.length; l++) {
                        var points = lines[l];
                        for (var p = 0; p < points.length; p++) {
                            positions[i] = points[p].x;
                            positions[i + 1] = points[p].y;
                            positions[i + 2] = points[p].z;
                            i += 3;
                        }
                    }
                };
                instance.updateMeshPositions(positionFunction, false);
                return instance;
            }
            // line system creation
            var lineSystem = new BABYLON.LinesMesh(name, scene);
            var vertexData = BABYLON.VertexData.CreateLineSystem(options);
            vertexData.applyToMesh(lineSystem, options.updatable);
            return lineSystem;
        };
        /**
         * Creates a line mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
         * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
         * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
         * The parameter `points` is an array successive Vector3.
         * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * When updating an instance, remember that only point positions can change, not the number of points.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateLines = function (name, options, scene) {
            var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
            return lines;
        };
        /**
         * Creates a dashed line mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
         * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
         * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
         * The parameter `points` is an array successive Vector3.
         * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
         * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
         * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
         * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * When updating an instance, remember that only point positions can change, not the number of points.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateDashedLines = function (name, options, scene) {
            var points = options.points;
            var instance = options.instance;
            var gapSize = options.gapSize;
            var dashNb = options.dashNb;
            var dashSize = options.dashSize;
            if (instance) {
                var positionFunction = function (positions) {
                    var curvect = BABYLON.Vector3.Zero();
                    var nbSeg = positions.length / 6;
                    var lg = 0;
                    var nb = 0;
                    var shft = 0;
                    var dashshft = 0;
                    var curshft = 0;
                    var p = 0;
                    var i = 0;
                    var j = 0;
                    for (i = 0; i < points.length - 1; i++) {
                        points[i + 1].subtractToRef(points[i], curvect);
                        lg += curvect.length();
                    }
                    shft = lg / nbSeg;
                    dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
                    for (i = 0; i < points.length - 1; i++) {
                        points[i + 1].subtractToRef(points[i], curvect);
                        nb = Math.floor(curvect.length() / shft);
                        curvect.normalize();
                        j = 0;
                        while (j < nb && p < positions.length) {
                            curshft = shft * j;
                            positions[p] = points[i].x + curshft * curvect.x;
                            positions[p + 1] = points[i].y + curshft * curvect.y;
                            positions[p + 2] = points[i].z + curshft * curvect.z;
                            positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
                            positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
                            positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
                            p += 6;
                            j++;
                        }
                    }
                    while (p < positions.length) {
                        positions[p] = points[i].x;
                        positions[p + 1] = points[i].y;
                        positions[p + 2] = points[i].z;
                        p += 3;
                    }
                };
                instance.updateMeshPositions(positionFunction, false);
                return instance;
            }
            // dashed lines creation
            var dashedLines = new BABYLON.LinesMesh(name, scene);
            var vertexData = BABYLON.VertexData.CreateDashedLines(options);
            vertexData.applyToMesh(dashedLines, options.updatable);
            dashedLines.dashSize = dashSize;
            dashedLines.gapSize = gapSize;
            return dashedLines;
        };
        /**
         * Creates an extruded shape mesh.
         * The extrusion is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
         *
         * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
         * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
         * extruded along the Z axis.
         * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
         * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
         * The parameter `scale` (float, default 1) is the value to scale the shape.
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
         * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.ExtrudeShape = function (name, options, scene) {
            var path = options.path;
            var shape = options.shape;
            var scale = options.scale || 1;
            var rotation = options.rotation || 0;
            var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
            var updatable = options.updatable;
            var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var instance = options.instance;
            var invertUV = options.invertUV || false;
            return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
        };
        /**
         * Creates an custom extruded shape mesh.
         * The custom extrusion is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
         *
         * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
         * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
         * extruded along the Z axis.
         * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
         * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
         * and the distance of this point from the begining of the path :
         * ```javascript
         * var rotationFunction = function(i, distance) {
         *     // do things
         *     return rotationValue; }
         * ```
         * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
         * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
         * and the distance of this point from the begining of the path :
         * ```javascript
         * var scaleFunction = function(i, distance) {
         *     // do things
         *     return scaleValue;}
         * ```
         * It must returns a float value that will be the scale value applied to the shape on each path point.
         * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
         * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
         * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
            var path = options.path;
            var shape = options.shape;
            var scaleFunction = options.scaleFunction || (function () { return 1; });
            var rotationFunction = options.rotationFunction || (function () { return 0; });
            var ribbonCloseArray = options.ribbonCloseArray || false;
            var ribbonClosePath = options.ribbonClosePath || false;
            var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
            var updatable = options.updatable;
            var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var instance = options.instance;
            var invertUV = options.invertUV || false;
            return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
        };
        /**
         * Creates lathe mesh.
         * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
         *
         * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
         * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
         * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
         * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
         * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
         * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateLathe = function (name, options, scene) {
            var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var closed = (options.closed === undefined) ? true : options.closed;
            var shape = options.shape;
            var radius = options.radius || 1;
            var tessellation = options.tessellation || 64;
            var updatable = options.updatable;
            var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var cap = options.cap || BABYLON.Mesh.NO_CAP;
            var pi2 = Math.PI * 2;
            var paths = new Array();
            var invertUV = options.invertUV || false;
            var i = 0;
            var p = 0;
            var step = pi2 / tessellation * arc;
            var rotated;
            var path = new Array();
            ;
            for (i = 0; i <= tessellation; i++) {
                var path = [];
                if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
                    path.push(new BABYLON.Vector3(0, shape[0].y, 0));
                    path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
                }
                for (p = 0; p < shape.length; p++) {
                    rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
                    path.push(rotated);
                }
                if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
                    path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
                    path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
                }
                paths.push(path);
            }
            // lathe ribbon
            var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
            return lathe;
        };
        /**
         * Creates a plane mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
         * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
         * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
         * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreatePlane = function (name, options, scene) {
            var plane = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreatePlane(options);
            vertexData.applyToMesh(plane, options.updatable);
            if (options.sourcePlane) {
                plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
                var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
                var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
                plane.rotate(vectorProduct, product);
            }
            return plane;
        };
        /**
         * Creates a ground mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
         * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
         * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateGround = function (name, options, scene) {
            var ground = new BABYLON.GroundMesh(name, scene);
            ground._setReady(false);
            ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
            ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
            ground._width = options.width || 1;
            ground._height = options.height || 1;
            ground._maxX = ground._width / 2;
            ground._maxZ = ground._height / 2;
            ground._minX = -ground._maxX;
            ground._minZ = -ground._maxZ;
            var vertexData = BABYLON.VertexData.CreateGround(options);
            vertexData.applyToMesh(ground, options.updatable);
            ground._setReady(true);
            return ground;
        };
        /**
         * Creates a tiled ground mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
         * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
         * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
         * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
         * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
         * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
         * numbers of subdivisions on the ground width and height of each tile.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateTiledGround = function (name, options, scene) {
            var tiledGround = new BABYLON.Mesh(name, scene);
            var vertexData = BABYLON.VertexData.CreateTiledGround(options);
            vertexData.applyToMesh(tiledGround, options.updatable);
            return tiledGround;
        };
        /**
         * Creates a ground mesh from a height map.
         * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
         * The parameter `url` sets the URL of the height map image resource.
         * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
         * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
         * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
         * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
         * The parameter `onReady` is a javascript callback function that will be called  once the mesh is just built (the height map download can last some time).
         * This function is passed the newly built mesh :
         * ```javascript
         * function(mesh) { // do things
         *     return; }
         * ```
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
            var width = options.width || 10.0;
            var height = options.height || 10.0;
            var subdivisions = options.subdivisions || 1 | 0;
            var minHeight = options.minHeight || 0.0;
            var maxHeight = options.maxHeight || 10.0;
            var updatable = options.updatable;
            var onReady = options.onReady;
            var ground = new BABYLON.GroundMesh(name, scene);
            ground._subdivisionsX = subdivisions;
            ground._subdivisionsY = subdivisions;
            ground._width = width;
            ground._height = height;
            ground._maxX = ground._width / 2.0;
            ground._maxZ = ground._height / 2.0;
            ground._minX = -ground._maxX;
            ground._minZ = -ground._maxZ;
            ground._setReady(false);
            var onload = function (img) {
                // Getting height map data
                var canvas = document.createElement("canvas");
                var context = canvas.getContext("2d");
                var bufferWidth = img.width;
                var bufferHeight = img.height;
                canvas.width = bufferWidth;
                canvas.height = bufferHeight;
                context.drawImage(img, 0, 0);
                // Create VertexData from map data
                // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
                var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
                var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
                    width: width, height: height,
                    subdivisions: subdivisions,
                    minHeight: minHeight, maxHeight: maxHeight,
                    buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
                });
                vertexData.applyToMesh(ground, updatable);
                ground._setReady(true);
                //execute ready callback, if set
                if (onReady) {
                    onReady(ground);
                }
            };
            BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
            return ground;
        };
        /**
         * Creates a tube mesh.
         * The tube is a parametric shape :  http://doc.babylonjs.com/tutorials/Parametric_Shapes.  It has no predefined shape. Its final shape will depend on the input parameters.
         *
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
         * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
         * The parameter `radius` (positive float, default 1) sets the tube radius size.
         * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
         * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
         * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
         * It must return a radius value (positive float) :
         * ```javascript
         * var radiusFunction = function(i, distance) {
         *     // do things
         *     return radius; }
         * ```
         * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
         * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreateTube = function (name, options, scene) {
            var path = options.path;
            var radius = options.radius || 1.0;
            var tessellation = options.tessellation || 64 | 0;
            var radiusFunction = options.radiusFunction;
            var cap = options.cap || BABYLON.Mesh.NO_CAP;
            var invertUV = options.invertUV || false;
            var updatable = options.updatable;
            var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var instance = options.instance;
            options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
            // tube geometry
            var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
                var tangents = path3D.getTangents();
                var normals = path3D.getNormals();
                var distances = path3D.getDistances();
                var pi2 = Math.PI * 2;
                var step = pi2 / tessellation * arc;
                var returnRadius = function () { return radius; };
                var radiusFunctionFinal = radiusFunction || returnRadius;
                var circlePath;
                var rad;
                var normal;
                var rotated;
                var rotationMatrix = BABYLON.Tmp.Matrix[0];
                var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
                for (var i = 0; i < path.length; i++) {
                    rad = radiusFunctionFinal(i, distances[i]); // current radius
                    circlePath = Array(); // current circle array
                    normal = normals[i]; // current normal
                    for (var t = 0; t < tessellation; t++) {
                        BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
                        rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
                        BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
                        rotated.scaleInPlace(rad).addInPlace(path[i]);
                        circlePath[t] = rotated;
                    }
                    circlePaths[index] = circlePath;
                    index++;
                }
                // cap
                var capPath = function (nbPoints, pathIndex) {
                    var pointCap = Array();
                    for (var i = 0; i < nbPoints; i++) {
                        pointCap.push(path[pathIndex]);
                    }
                    return pointCap;
                };
                switch (cap) {
                    case BABYLON.Mesh.NO_CAP:
                        break;
                    case BABYLON.Mesh.CAP_START:
                        circlePaths[0] = capPath(tessellation, 0);
                        circlePaths[1] = circlePaths[2].slice(0);
                        break;
                    case BABYLON.Mesh.CAP_END:
                        circlePaths[index] = circlePaths[index - 1].slice(0);
                        circlePaths[index + 1] = capPath(tessellation, path.length - 1);
                        break;
                    case BABYLON.Mesh.CAP_ALL:
                        circlePaths[0] = capPath(tessellation, 0);
                        circlePaths[1] = circlePaths[2].slice(0);
                        circlePaths[index] = circlePaths[index - 1].slice(0);
                        circlePaths[index + 1] = capPath(tessellation, path.length - 1);
                        break;
                    default:
                        break;
                }
                return circlePaths;
            };
            var path3D;
            var pathArray;
            if (instance) {
                var arc = options.arc || instance.arc;
                path3D = (instance.path3D).update(path);
                pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
                instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
                instance.path3D = path3D;
                instance.pathArray = pathArray;
                instance.arc = arc;
                return instance;
            }
            // tube creation
            path3D = new BABYLON.Path3D(path);
            var newPathArray = new Array();
            cap = (cap < 0 || cap > 3) ? 0 : cap;
            pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
            var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
            tube.pathArray = pathArray;
            tube.path3D = path3D;
            tube.tessellation = tessellation;
            tube.cap = cap;
            tube.arc = options.arc;
            return tube;
        };
        /**
         * Creates a polyhedron mesh.
         *
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
         * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
         *  to choose the wanted type.
         * The parameter `size` (positive float, default 1) sets the polygon size.
         * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
         * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
         * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
         * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
         * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
         * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
         * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         */
        MeshBuilder.CreatePolyhedron = function (name, options, scene) {
            var polyhedron = new BABYLON.Mesh(name, scene);
            options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
            var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
            vertexData.applyToMesh(polyhedron, options.updatable);
            return polyhedron;
        };
        /**
         * Creates a decal mesh.
         * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
         * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
         * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
         * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
         * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
         * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
         */
        MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
            var indices = sourceMesh.getIndices();
            var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var position = options.position || BABYLON.Vector3.Zero();
            var normal = options.normal || BABYLON.Vector3.Up();
            var size = options.size || new BABYLON.Vector3(1, 1, 1);
            var angle = options.angle || 0;
            // Getting correct rotation
            if (!normal) {
                var target = new BABYLON.Vector3(0, 0, 1);
                var camera = sourceMesh.getScene().activeCamera;
                var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
                normal = camera.globalPosition.subtract(cameraWorldTarget);
            }
            var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
            var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
            var pitch = Math.atan2(normal.y, len);
            // Matrix
            var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
            var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
            var meshWorldMatrix = sourceMesh.getWorldMatrix();
            var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
            var vertexData = new BABYLON.VertexData();
            vertexData.indices = [];
            vertexData.positions = [];
            vertexData.normals = [];
            vertexData.uvs = [];
            var currentVertexDataIndex = 0;
            var extractDecalVector3 = function (indexId) {
                var vertexId = indices[indexId];
                var result = new BABYLON.PositionNormalVertex();
                result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
                // Send vector to decal local world
                result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
                // Get normal
                result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
                return result;
            }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
            var clip = function (vertices, axis) {
                if (vertices.length === 0) {
                    return vertices;
                }
                var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
                var clipVertices = function (v0, v1) {
                    var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
                    return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
                };
                var result = new Array();
                for (var index = 0; index < vertices.length; index += 3) {
                    var v1Out;
                    var v2Out;
                    var v3Out;
                    var total = 0;
                    var nV1, nV2, nV3, nV4;
                    var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
                    var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
                    var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
                    v1Out = d1 > 0;
                    v2Out = d2 > 0;
                    v3Out = d3 > 0;
                    total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
                    switch (total) {
                        case 0:
                            result.push(vertices[index]);
                            result.push(vertices[index + 1]);
                            result.push(vertices[index + 2]);
                            break;
                        case 1:
                            if (v1Out) {
                                nV1 = vertices[index + 1];
                                nV2 = vertices[index + 2];
                                nV3 = clipVertices(vertices[index], nV1);
                                nV4 = clipVertices(vertices[index], nV2);
                            }
                            if (v2Out) {
                                nV1 = vertices[index];
                                nV2 = vertices[index + 2];
                                nV3 = clipVertices(vertices[index + 1], nV1);
                                nV4 = clipVertices(vertices[index + 1], nV2);
                                result.push(nV3);
                                result.push(nV2.clone());
                                result.push(nV1.clone());
                                result.push(nV2.clone());
                                result.push(nV3.clone());
                                result.push(nV4);
                                break;
                            }
                            if (v3Out) {
                                nV1 = vertices[index];
                                nV2 = vertices[index + 1];
                                nV3 = clipVertices(vertices[index + 2], nV1);
                                nV4 = clipVertices(vertices[index + 2], nV2);
                            }
                            result.push(nV1.clone());
                            result.push(nV2.clone());
                            result.push(nV3);
                            result.push(nV4);
                            result.push(nV3.clone());
                            result.push(nV2.clone());
                            break;
                        case 2:
                            if (!v1Out) {
                                nV1 = vertices[index].clone();
                                nV2 = clipVertices(nV1, vertices[index + 1]);
                                nV3 = clipVertices(nV1, vertices[index + 2]);
                                result.push(nV1);
                                result.push(nV2);
                                result.push(nV3);
                            }
                            if (!v2Out) {
                                nV1 = vertices[index + 1].clone();
                                nV2 = clipVertices(nV1, vertices[index + 2]);
                                nV3 = clipVertices(nV1, vertices[index]);
                                result.push(nV1);
                                result.push(nV2);
                                result.push(nV3);
                            }
                            if (!v3Out) {
                                nV1 = vertices[index + 2].clone();
                                nV2 = clipVertices(nV1, vertices[index]);
                                nV3 = clipVertices(nV1, vertices[index + 1]);
                                result.push(nV1);
                                result.push(nV2);
                                result.push(nV3);
                            }
                            break;
                        case 3:
                            break;
                    }
                }
                return result;
            };
            for (var index = 0; index < indices.length; index += 3) {
                var faceVertices = new Array();
                faceVertices.push(extractDecalVector3(index));
                faceVertices.push(extractDecalVector3(index + 1));
                faceVertices.push(extractDecalVector3(index + 2));
                // Clip
                faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
                if (faceVertices.length === 0) {
                    continue;
                }
                // Add UVs and get back to world
                for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
                    var vertex = faceVertices[vIndex];
                    //TODO check for Int32Array
                    vertexData.indices.push(currentVertexDataIndex);
                    vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
                    vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
                    vertexData.uvs.push(0.5 + vertex.position.x / size.x);
                    vertexData.uvs.push(0.5 + vertex.position.y / size.y);
                    currentVertexDataIndex++;
                }
            }
            // Return mesh
            var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
            vertexData.applyToMesh(decal);
            decal.position = position.clone();
            decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
            return decal;
        };
        // Privates
        MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
            // extrusion geometry
            var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
                var tangents = path3D.getTangents();
                var normals = path3D.getNormals();
                var binormals = path3D.getBinormals();
                var distances = path3D.getDistances();
                var angle = 0;
                var returnScale = function () { return scale; };
                var returnRotation = function () { return rotation; };
                var rotate = custom ? rotateFunction : returnRotation;
                var scl = custom ? scaleFunction : returnScale;
                var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
                var rotationMatrix = BABYLON.Tmp.Matrix[0];
                for (var i = 0; i < curve.length; i++) {
                    var shapePath = new Array();
                    var angleStep = rotate(i, distances[i]);
                    var scaleRatio = scl(i, distances[i]);
                    for (var p = 0; p < shape.length; p++) {
                        BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
                        var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
                        var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
                        BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
                        rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
                        shapePath[p] = rotated;
                    }
                    shapePaths[index] = shapePath;
                    angle += angleStep;
                    index++;
                }
                // cap
                var capPath = function (shapePath) {
                    var pointCap = Array();
                    var barycenter = BABYLON.Vector3.Zero();
                    var i;
                    for (i = 0; i < shapePath.length; i++) {
                        barycenter.addInPlace(shapePath[i]);
                    }
                    barycenter.scaleInPlace(1 / shapePath.length);
                    for (i = 0; i < shapePath.length; i++) {
                        pointCap.push(barycenter);
                    }
                    return pointCap;
                };
                switch (cap) {
                    case BABYLON.Mesh.NO_CAP:
                        break;
                    case BABYLON.Mesh.CAP_START:
                        shapePaths[0] = capPath(shapePaths[2]);
                        shapePaths[1] = shapePaths[2].slice(0);
                        break;
                    case BABYLON.Mesh.CAP_END:
                        shapePaths[index] = shapePaths[index - 1];
                        shapePaths[index + 1] = capPath(shapePaths[index - 1]);
                        break;
                    case BABYLON.Mesh.CAP_ALL:
                        shapePaths[0] = capPath(shapePaths[2]);
                        shapePaths[1] = shapePaths[2].slice(0);
                        shapePaths[index] = shapePaths[index - 1];
                        shapePaths[index + 1] = capPath(shapePaths[index - 1]);
                        break;
                    default:
                        break;
                }
                return shapePaths;
            };
            var path3D;
            var pathArray;
            if (instance) {
                path3D = (instance.path3D).update(curve);
                pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
                instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
                return instance;
            }
            // extruded shape creation
            path3D = new BABYLON.Path3D(curve);
            var newShapePaths = new Array();
            cap = (cap < 0 || cap > 3) ? 0 : cap;
            pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
            var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
            extrudedGeneric.pathArray = pathArray;
            extrudedGeneric.path3D = path3D;
            extrudedGeneric.cap = cap;
            return extrudedGeneric;
        };
        return MeshBuilder;
    }());
    BABYLON.MeshBuilder = MeshBuilder;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.meshBuilder.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var BaseTexture = (function () {
        function BaseTexture(scene) {
            this.hasAlpha = false;
            this.getAlphaFromRGB = false;
            this.level = 1;
            this.coordinatesIndex = 0;
            this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            this.anisotropicFilteringLevel = 4;
            this.isCube = false;
            this.isRenderTarget = false;
            this.animations = new Array();
            /**
            * An event triggered when the texture is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this._scene = scene;
            this._scene.textures.push(this);
            this._uid = null;
        }
        Object.defineProperty(BaseTexture.prototype, "uid", {
            get: function () {
                if (!this._uid) {
                    this._uid = BABYLON.Tools.RandomId();
                }
                return this._uid;
            },
            enumerable: true,
            configurable: true
        });
        BaseTexture.prototype.toString = function () {
            return this.name;
        };
        Object.defineProperty(BaseTexture.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        BaseTexture.prototype.getScene = function () {
            return this._scene;
        };
        BaseTexture.prototype.getTextureMatrix = function () {
            return null;
        };
        BaseTexture.prototype.getReflectionTextureMatrix = function () {
            return null;
        };
        BaseTexture.prototype.getInternalTexture = function () {
            return this._texture;
        };
        BaseTexture.prototype.isReady = function () {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return true;
            }
            if (this._texture) {
                return this._texture.isReady;
            }
            return false;
        };
        BaseTexture.prototype.getSize = function () {
            if (this._texture._width) {
                return new BABYLON.Size(this._texture._width, this._texture._height);
            }
            if (this._texture._size) {
                return new BABYLON.Size(this._texture._size, this._texture._size);
            }
            return BABYLON.Size.Zero();
        };
        BaseTexture.prototype.getBaseSize = function () {
            if (!this.isReady() || !this._texture)
                return BABYLON.Size.Zero();
            if (this._texture._size) {
                return new BABYLON.Size(this._texture._size, this._texture._size);
            }
            return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
        };
        BaseTexture.prototype.scale = function (ratio) {
        };
        Object.defineProperty(BaseTexture.prototype, "canRescale", {
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
            for (var index = 0; index < texturesCache.length; index++) {
                var texturesCacheEntry = texturesCache[index];
                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
                    texturesCache.splice(index, 1);
                    return;
                }
            }
        };
        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
            for (var index = 0; index < texturesCache.length; index++) {
                var texturesCacheEntry = texturesCache[index];
                if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
                        texturesCacheEntry.references++;
                        return texturesCacheEntry;
                    }
                }
            }
            return null;
        };
        BaseTexture.prototype.delayLoad = function () {
        };
        BaseTexture.prototype.clone = function () {
            return null;
        };
        BaseTexture.prototype.releaseInternalTexture = function () {
            if (this._texture) {
                this._scene.getEngine().releaseInternalTexture(this._texture);
                delete this._texture;
            }
        };
        BaseTexture.prototype.dispose = function () {
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            var index = this._scene.textures.indexOf(this);
            if (index >= 0) {
                this._scene.textures.splice(index, 1);
            }
            if (this._texture === undefined) {
                return;
            }
            // Release
            this.releaseInternalTexture();
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        BaseTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            return serializationObject;
        };
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "name", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "hasAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "level", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "coordinatesIndex", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "coordinatesMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "wrapU", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "wrapV", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "isCube", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "isRenderTarget", void 0);
        return BaseTexture;
    }());
    BABYLON.BaseTexture = BaseTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.baseTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Texture = (function (_super) {
        __extends(Texture, _super);
        function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
            var _this = this;
            if (noMipmap === void 0) { noMipmap = false; }
            if (invertY === void 0) { invertY = true; }
            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (buffer === void 0) { buffer = null; }
            if (deleteBuffer === void 0) { deleteBuffer = false; }
            _super.call(this, scene);
            this.uOffset = 0;
            this.vOffset = 0;
            this.uScale = 1.0;
            this.vScale = 1.0;
            this.uAng = 0;
            this.vAng = 0;
            this.wAng = 0;
            this.name = url;
            this.url = url;
            this._noMipmap = noMipmap;
            this._invertY = invertY;
            this._samplingMode = samplingMode;
            this._buffer = buffer;
            this._deleteBuffer = deleteBuffer;
            if (!url) {
                return;
            }
            this._texture = this._getFromCache(url, noMipmap, samplingMode);
            var load = function () {
                if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
                    _this.onLoadObservable.notifyObservers(true);
                }
                if (onLoad) {
                    onLoad();
                }
            };
            if (!this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
                    if (deleteBuffer) {
                        delete this._buffer;
                    }
                }
                else {
                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                    this._delayedOnLoad = load;
                    this._delayedOnError = onError;
                }
            }
            else {
                if (this._texture.isReady) {
                    BABYLON.Tools.SetImmediate(function () { return load(); });
                }
                else {
                    this._texture.onLoadedCallbacks.push(load);
                }
            }
        }
        Object.defineProperty(Texture.prototype, "noMipmap", {
            get: function () {
                return this._noMipmap;
            },
            enumerable: true,
            configurable: true
        });
        Texture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
            if (!this._texture) {
                this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
                if (this._deleteBuffer) {
                    delete this._buffer;
                }
            }
        };
        Texture.prototype.updateSamplingMode = function (samplingMode) {
            if (!this._texture) {
                return;
            }
            this._samplingMode = samplingMode;
            this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
        };
        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
            x *= this.uScale;
            y *= this.vScale;
            x -= 0.5 * this.uScale;
            y -= 0.5 * this.vScale;
            z -= 0.5;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
            t.x += 0.5 * this.uScale + this.uOffset;
            t.y += 0.5 * this.vScale + this.vOffset;
            t.z += 0.5;
        };
        Texture.prototype.getTextureMatrix = function () {
            if (this.uOffset === this._cachedUOffset &&
                this.vOffset === this._cachedVOffset &&
                this.uScale === this._cachedUScale &&
                this.vScale === this._cachedVScale &&
                this.uAng === this._cachedUAng &&
                this.vAng === this._cachedVAng &&
                this.wAng === this._cachedWAng) {
                return this._cachedTextureMatrix;
            }
            this._cachedUOffset = this.uOffset;
            this._cachedVOffset = this.vOffset;
            this._cachedUScale = this.uScale;
            this._cachedVScale = this.vScale;
            this._cachedUAng = this.uAng;
            this._cachedVAng = this.vAng;
            this._cachedWAng = this.wAng;
            if (!this._cachedTextureMatrix) {
                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
                this._rowGenerationMatrix = new BABYLON.Matrix();
                this._t0 = BABYLON.Vector3.Zero();
                this._t1 = BABYLON.Vector3.Zero();
                this._t2 = BABYLON.Vector3.Zero();
            }
            BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
            this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
            this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
            this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
            this._t1.subtractInPlace(this._t0);
            this._t2.subtractInPlace(this._t0);
            BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
            this._cachedTextureMatrix.m[0] = this._t1.x;
            this._cachedTextureMatrix.m[1] = this._t1.y;
            this._cachedTextureMatrix.m[2] = this._t1.z;
            this._cachedTextureMatrix.m[4] = this._t2.x;
            this._cachedTextureMatrix.m[5] = this._t2.y;
            this._cachedTextureMatrix.m[6] = this._t2.z;
            this._cachedTextureMatrix.m[8] = this._t0.x;
            this._cachedTextureMatrix.m[9] = this._t0.y;
            this._cachedTextureMatrix.m[10] = this._t0.z;
            return this._cachedTextureMatrix;
        };
        Texture.prototype.getReflectionTextureMatrix = function () {
            if (this.uOffset === this._cachedUOffset &&
                this.vOffset === this._cachedVOffset &&
                this.uScale === this._cachedUScale &&
                this.vScale === this._cachedVScale &&
                this.coordinatesMode === this._cachedCoordinatesMode) {
                return this._cachedTextureMatrix;
            }
            if (!this._cachedTextureMatrix) {
                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
                this._projectionModeMatrix = BABYLON.Matrix.Zero();
            }
            this._cachedCoordinatesMode = this.coordinatesMode;
            switch (this.coordinatesMode) {
                case Texture.PLANAR_MODE:
                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
                    this._cachedTextureMatrix[0] = this.uScale;
                    this._cachedTextureMatrix[5] = this.vScale;
                    this._cachedTextureMatrix[12] = this.uOffset;
                    this._cachedTextureMatrix[13] = this.vOffset;
                    break;
                case Texture.PROJECTION_MODE:
                    BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
                    this._projectionModeMatrix.m[0] = 0.5;
                    this._projectionModeMatrix.m[5] = -0.5;
                    this._projectionModeMatrix.m[10] = 0.0;
                    this._projectionModeMatrix.m[12] = 0.5;
                    this._projectionModeMatrix.m[13] = 0.5;
                    this._projectionModeMatrix.m[14] = 1.0;
                    this._projectionModeMatrix.m[15] = 1.0;
                    this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
                    break;
                default:
                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
                    break;
            }
            return this._cachedTextureMatrix;
        };
        Texture.prototype.clone = function () {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () {
                return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
            }, this);
        };
        Object.defineProperty(Texture.prototype, "onLoadObservable", {
            get: function () {
                if (!this._onLoadObservarble) {
                    this._onLoadObservarble = new BABYLON.Observable();
                }
                return this._onLoadObservarble;
            },
            enumerable: true,
            configurable: true
        });
        // Statics
        Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
        };
        Texture.Parse = function (parsedTexture, scene, rootUrl) {
            if (parsedTexture.customType) {
                var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
                return customTexture.Parse(parsedTexture, scene, rootUrl);
            }
            if (parsedTexture.isCube) {
                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
            }
            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
                return null;
            }
            var texture = BABYLON.SerializationHelper.Parse(function () {
                if (parsedTexture.mirrorPlane) {
                    var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
                    mirrorTexture._waitingRenderList = parsedTexture.renderList;
                    mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
                    return mirrorTexture;
                }
                else if (parsedTexture.isRenderTarget) {
                    var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
                    renderTargetTexture._waitingRenderList = parsedTexture.renderList;
                    return renderTargetTexture;
                }
                else {
                    var texture;
                    if (parsedTexture.base64String) {
                        texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
                    }
                    else {
                        texture = new Texture(rootUrl + parsedTexture.name, scene);
                    }
                    return texture;
                }
            }, parsedTexture, scene);
            // Animations
            if (parsedTexture.animations) {
                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
                    var parsedAnimation = parsedTexture.animations[animationIndex];
                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
            }
            return texture;
        };
        Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
            if (deleteBuffer === void 0) { deleteBuffer = false; }
            if (noMipmap === void 0) { noMipmap = false; }
            if (invertY === void 0) { invertY = true; }
            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (name.substr(0, 5) !== "data:") {
                name = "data:" + name;
            }
            return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
        };
        // Constants
        Texture.NEAREST_SAMPLINGMODE = 1;
        Texture.BILINEAR_SAMPLINGMODE = 2;
        Texture.TRILINEAR_SAMPLINGMODE = 3;
        Texture.EXPLICIT_MODE = 0;
        Texture.SPHERICAL_MODE = 1;
        Texture.PLANAR_MODE = 2;
        Texture.CUBIC_MODE = 3;
        Texture.PROJECTION_MODE = 4;
        Texture.SKYBOX_MODE = 5;
        Texture.INVCUBIC_MODE = 6;
        Texture.EQUIRECTANGULAR_MODE = 7;
        Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
        Texture.CLAMP_ADDRESSMODE = 0;
        Texture.WRAP_ADDRESSMODE = 1;
        Texture.MIRROR_ADDRESSMODE = 2;
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "url", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uScale", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vScale", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uAng", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vAng", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "wAng", void 0);
        return Texture;
    }(BABYLON.BaseTexture));
    BABYLON.Texture = Texture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.texture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var CubeTexture = (function (_super) {
        __extends(CubeTexture, _super);
        function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            _super.call(this, scene);
            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
            this.name = rootUrl;
            this.url = rootUrl;
            this._noMipmap = noMipmap;
            this.hasAlpha = false;
            if (!rootUrl && !files) {
                return;
            }
            this._texture = this._getFromCache(rootUrl, noMipmap);
            if (!files) {
                if (!extensions) {
                    extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
                }
                files = [];
                for (var index = 0; index < extensions.length; index++) {
                    files.push(rootUrl + extensions[index]);
                }
                this._extensions = extensions;
            }
            this._files = files;
            if (!this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
                }
                else {
                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                }
            }
            else if (onLoad) {
                if (this._texture.isReady) {
                    BABYLON.Tools.SetImmediate(function () { return onLoad(); });
                }
                else {
                    this._texture.onLoadedCallbacks.push(onLoad);
                }
            }
            this.isCube = true;
            this._textureMatrix = BABYLON.Matrix.Identity();
        }
        CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
            return new CubeTexture("", scene, null, noMipmap, files);
        };
        // Methods
        CubeTexture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, this._noMipmap);
            if (!this._texture) {
                this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
            }
        };
        CubeTexture.prototype.getReflectionTextureMatrix = function () {
            return this._textureMatrix;
        };
        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
            var texture = BABYLON.SerializationHelper.Parse(function () {
                return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
            }, parsedTexture, scene);
            // Animations
            if (parsedTexture.animations) {
                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
                    var parsedAnimation = parsedTexture.animations[animationIndex];
                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
            }
            return texture;
        };
        CubeTexture.prototype.clone = function () {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () {
                return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
            }, this);
        };
        return CubeTexture;
    }(BABYLON.BaseTexture));
    BABYLON.CubeTexture = CubeTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.cubeTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var RenderTargetTexture = (function (_super) {
        __extends(RenderTargetTexture, _super);
        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (isCube === void 0) { isCube = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
            if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
            _super.call(this, null, scene, !generateMipMaps);
            this.isCube = isCube;
            /**
            * Use this list to define the list of mesh you want to render.
            */
            this.renderList = new Array();
            this.renderParticles = true;
            this.renderSprites = false;
            this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
            // Events
            /**
            * An event triggered when the texture is unbind.
            * @type {BABYLON.Observable}
            */
            this.onAfterUnbindObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the texture
            * @type {BABYLON.Observable}
            */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the texture
            * @type {BABYLON.Observable}
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after the texture clear
            * @type {BABYLON.Observable}
            */
            this.onClearObservable = new BABYLON.Observable();
            this._currentRefreshId = -1;
            this._refreshRate = 1;
            this.name = name;
            this.isRenderTarget = true;
            this._size = size;
            this._generateMipMaps = generateMipMaps;
            this._doNotChangeAspectRatio = doNotChangeAspectRatio;
            if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
                this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            }
            if (isCube) {
                this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
                    generateMipMaps: generateMipMaps,
                    samplingMode: samplingMode,
                    generateDepthBuffer: generateDepthBuffer,
                    generateStencilBuffer: generateStencilBuffer
                });
                this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
                this._textureMatrix = BABYLON.Matrix.Identity();
            }
            else {
                this._texture = scene.getEngine().createRenderTargetTexture(size, {
                    generateMipMaps: generateMipMaps,
                    type: type,
                    samplingMode: samplingMode,
                    generateDepthBuffer: generateDepthBuffer,
                    generateStencilBuffer: generateStencilBuffer
                });
            }
            // Rendering groups
            this._renderingManager = new BABYLON.RenderingManager(scene);
        }
        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
            get: function () {
                return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
            get: function () {
                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
            get: function () {
                return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
            set: function (callback) {
                if (this._onAfterUnbindObserver) {
                    this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
                }
                this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
            set: function (callback) {
                if (this._onClearObserver) {
                    this.onClearObservable.remove(this._onClearObserver);
                }
                this._onClearObserver = this.onClearObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        RenderTargetTexture.prototype.resetRefreshCounter = function () {
            this._currentRefreshId = -1;
        };
        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
            get: function () {
                return this._refreshRate;
            },
            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
            set: function (value) {
                this._refreshRate = value;
                this.resetRefreshCounter();
            },
            enumerable: true,
            configurable: true
        });
        RenderTargetTexture.prototype._shouldRender = function () {
            if (this._currentRefreshId === -1) {
                this._currentRefreshId = 1;
                return true;
            }
            if (this.refreshRate === this._currentRefreshId) {
                this._currentRefreshId = 1;
                return true;
            }
            this._currentRefreshId++;
            return false;
        };
        RenderTargetTexture.prototype.isReady = function () {
            if (!this.getScene().renderTargetsEnabled) {
                return false;
            }
            return _super.prototype.isReady.call(this);
        };
        RenderTargetTexture.prototype.getRenderSize = function () {
            return this._size;
        };
        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
            get: function () {
                return true;
            },
            enumerable: true,
            configurable: true
        });
        RenderTargetTexture.prototype.scale = function (ratio) {
            var newSize = this._size * ratio;
            this.resize(newSize, this._generateMipMaps);
        };
        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
            if (this.isCube) {
                return this._textureMatrix;
            }
            return _super.prototype.getReflectionTextureMatrix.call(this);
        };
        RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
            this.releaseInternalTexture();
            if (this.isCube) {
                this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
            }
            else {
                this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
            }
        };
        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
            var scene = this.getScene();
            if (this.useCameraPostProcesses !== undefined) {
                useCameraPostProcess = this.useCameraPostProcesses;
            }
            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
                scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
            }
            if (this._waitingRenderList) {
                this.renderList = [];
                for (var index = 0; index < this._waitingRenderList.length; index++) {
                    var id = this._waitingRenderList[index];
                    this.renderList.push(scene.getMeshByID(id));
                }
                delete this._waitingRenderList;
            }
            // Is predicate defined?
            if (this.renderListPredicate) {
                this.renderList.splice(0); // Clear previous renderList
                var sceneMeshes = this.getScene().meshes;
                for (var index = 0; index < sceneMeshes.length; index++) {
                    var mesh = sceneMeshes[index];
                    if (this.renderListPredicate(mesh)) {
                        this.renderList.push(mesh);
                    }
                }
            }
            if (this.renderList && this.renderList.length === 0) {
                return;
            }
            // Prepare renderingManager
            this._renderingManager.reset();
            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
            var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
            var sceneRenderId = scene.getRenderId();
            for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
                var mesh = currentRenderList[meshIndex];
                if (mesh) {
                    if (!mesh.isReady()) {
                        // Reset _currentRefreshId
                        this.resetRefreshCounter();
                        continue;
                    }
                    mesh._preActivateForIntermediateRendering(sceneRenderId);
                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
                        mesh._activate(sceneRenderId);
                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
                            var subMesh = mesh.subMeshes[subIndex];
                            scene._activeIndices.addCount(subMesh.indexCount, false);
                            this._renderingManager.dispatch(subMesh);
                        }
                    }
                }
            }
            if (this.isCube) {
                for (var face = 0; face < 6; face++) {
                    this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
                    scene.incrementRenderId();
                    scene.resetCachedMaterial();
                }
            }
            else {
                this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
            }
            this.onAfterUnbindObservable.notifyObservers(this);
            if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
                scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
            }
            scene.resetCachedMaterial();
        };
        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
            var scene = this.getScene();
            var engine = scene.getEngine();
            // Bind
            if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
                if (this.isCube) {
                    engine.bindFramebuffer(this._texture, faceIndex);
                }
                else {
                    engine.bindFramebuffer(this._texture);
                }
            }
            this.onBeforeRenderObservable.notifyObservers(faceIndex);
            // Clear
            if (this.onClearObservable.hasObservers()) {
                this.onClearObservable.notifyObservers(engine);
            }
            else {
                engine.clear(scene.clearColor, true, true, true);
            }
            if (!this._doNotChangeAspectRatio) {
                scene.updateTransformMatrix(true);
            }
            // Render
            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
            if (useCameraPostProcess) {
                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
            }
            if (!this._doNotChangeAspectRatio) {
                scene.updateTransformMatrix(true);
            }
            this.onAfterRenderObservable.notifyObservers(faceIndex);
            // Dump ?
            if (dumpForDebug) {
                BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
            }
            // Unbind
            if (!this.isCube || faceIndex === 5) {
                if (this.isCube) {
                    if (faceIndex === 5) {
                        engine.generateMipMapsForCubemap(this._texture);
                    }
                }
                engine.unBindFramebuffer(this._texture, this.isCube);
            }
        };
        /**
         * Overrides the default sort function applied in the renderging group to prepare the meshes.
         * This allowed control for front to back rendering or reversly depending of the special needs.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
         * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
         * @param transparentSortCompareFn The transparent queue comparison function use to sort.
         */
        RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         */
        RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
            this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
        };
        RenderTargetTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // RenderTarget Texture
            newTexture.coordinatesMode = this.coordinatesMode;
            newTexture.renderList = this.renderList.slice(0);
            return newTexture;
        };
        RenderTargetTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.renderTargetSize = this.getRenderSize();
            serializationObject.renderList = [];
            for (var index = 0; index < this.renderList.length; index++) {
                serializationObject.renderList.push(this.renderList[index].id);
            }
            return serializationObject;
        };
        RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
        RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
        return RenderTargetTexture;
    }(BABYLON.Texture));
    BABYLON.RenderTargetTexture = RenderTargetTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.renderTargetTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var ProceduralTexture = (function (_super) {
        __extends(ProceduralTexture, _super);
        function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (isCube === void 0) { isCube = false; }
            _super.call(this, null, scene, !generateMipMaps);
            this.isCube = isCube;
            this.isEnabled = true;
            this._currentRefreshId = -1;
            this._refreshRate = 1;
            this._vertexBuffers = {};
            this._uniforms = new Array();
            this._samplers = new Array();
            this._textures = new Array();
            this._floats = new Array();
            this._floatsArrays = {};
            this._colors3 = new Array();
            this._colors4 = new Array();
            this._vectors2 = new Array();
            this._vectors3 = new Array();
            this._matrices = new Array();
            this._fallbackTextureUsed = false;
            scene._proceduralTextures.push(this);
            this.name = name;
            this.isRenderTarget = true;
            this._size = size;
            this._generateMipMaps = generateMipMaps;
            this.setFragment(fragment);
            this._fallbackTexture = fallbackTexture;
            var engine = scene.getEngine();
            if (isCube) {
                this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
                this.setFloat("face", 0);
            }
            else {
                this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
            }
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
        }
        ProceduralTexture.prototype.reset = function () {
            if (this._effect === undefined) {
                return;
            }
            var engine = this.getScene().getEngine();
            engine._releaseEffect(this._effect);
        };
        ProceduralTexture.prototype.isReady = function () {
            var _this = this;
            var engine = this.getScene().getEngine();
            var shaders;
            if (!this._fragment) {
                return false;
            }
            if (this._fallbackTextureUsed) {
                return true;
            }
            if (this._fragment.fragmentElement !== undefined) {
                shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
            }
            else {
                shaders = { vertex: "procedural", fragment: this._fragment };
            }
            this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
                _this.releaseInternalTexture();
                if (_this._fallbackTexture) {
                    _this._texture = _this._fallbackTexture._texture;
                    _this._texture.references++;
                }
                _this._fallbackTextureUsed = true;
            });
            return this._effect.isReady();
        };
        ProceduralTexture.prototype.resetRefreshCounter = function () {
            this._currentRefreshId = -1;
        };
        ProceduralTexture.prototype.setFragment = function (fragment) {
            this._fragment = fragment;
        };
        Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
            get: function () {
                return this._refreshRate;
            },
            // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
            set: function (value) {
                this._refreshRate = value;
                this.resetRefreshCounter();
            },
            enumerable: true,
            configurable: true
        });
        ProceduralTexture.prototype._shouldRender = function () {
            if (!this.isEnabled || !this.isReady() || !this._texture) {
                return false;
            }
            if (this._fallbackTextureUsed) {
                return false;
            }
            if (this._currentRefreshId === -1) {
                this._currentRefreshId = 1;
                return true;
            }
            if (this.refreshRate === this._currentRefreshId) {
                this._currentRefreshId = 1;
                return true;
            }
            this._currentRefreshId++;
            return false;
        };
        ProceduralTexture.prototype.getRenderSize = function () {
            return this._size;
        };
        ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
            if (this._fallbackTextureUsed) {
                return;
            }
            this.releaseInternalTexture();
            this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
        };
        ProceduralTexture.prototype._checkUniform = function (uniformName) {
            if (this._uniforms.indexOf(uniformName) === -1) {
                this._uniforms.push(uniformName);
            }
        };
        ProceduralTexture.prototype.setTexture = function (name, texture) {
            if (this._samplers.indexOf(name) === -1) {
                this._samplers.push(name);
            }
            this._textures[name] = texture;
            return this;
        };
        ProceduralTexture.prototype.setFloat = function (name, value) {
            this._checkUniform(name);
            this._floats[name] = value;
            return this;
        };
        ProceduralTexture.prototype.setFloats = function (name, value) {
            this._checkUniform(name);
            this._floatsArrays[name] = value;
            return this;
        };
        ProceduralTexture.prototype.setColor3 = function (name, value) {
            this._checkUniform(name);
            this._colors3[name] = value;
            return this;
        };
        ProceduralTexture.prototype.setColor4 = function (name, value) {
            this._checkUniform(name);
            this._colors4[name] = value;
            return this;
        };
        ProceduralTexture.prototype.setVector2 = function (name, value) {
            this._checkUniform(name);
            this._vectors2[name] = value;
            return this;
        };
        ProceduralTexture.prototype.setVector3 = function (name, value) {
            this._checkUniform(name);
            this._vectors3[name] = value;
            return this;
        };
        ProceduralTexture.prototype.setMatrix = function (name, value) {
            this._checkUniform(name);
            this._matrices[name] = value;
            return this;
        };
        ProceduralTexture.prototype.render = function (useCameraPostProcess) {
            var scene = this.getScene();
            var engine = scene.getEngine();
            // Render
            engine.enableEffect(this._effect);
            engine.setState(false);
            // Texture
            for (var name in this._textures) {
                this._effect.setTexture(name, this._textures[name]);
            }
            // Float    
            for (name in this._floats) {
                this._effect.setFloat(name, this._floats[name]);
            }
            // Floats   
            for (name in this._floatsArrays) {
                this._effect.setArray(name, this._floatsArrays[name]);
            }
            // Color3        
            for (name in this._colors3) {
                this._effect.setColor3(name, this._colors3[name]);
            }
            // Color4      
            for (name in this._colors4) {
                var color = this._colors4[name];
                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
            }
            // Vector2        
            for (name in this._vectors2) {
                this._effect.setVector2(name, this._vectors2[name]);
            }
            // Vector3        
            for (name in this._vectors3) {
                this._effect.setVector3(name, this._vectors3[name]);
            }
            // Matrix      
            for (name in this._matrices) {
                this._effect.setMatrix(name, this._matrices[name]);
            }
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
            if (this.isCube) {
                for (var face = 0; face < 6; face++) {
                    engine.bindFramebuffer(this._texture, face);
                    this._effect.setFloat("face", face);
                    // Clear
                    engine.clear(scene.clearColor, true, true, true);
                    // Draw order
                    engine.draw(true, 0, 6);
                    // Mipmaps
                    if (face === 5) {
                        engine.generateMipMapsForCubemap(this._texture);
                    }
                }
            }
            else {
                engine.bindFramebuffer(this._texture);
                // Clear
                engine.clear(scene.clearColor, true, true, true);
                // Draw order
                engine.draw(true, 0, 6);
            }
            // Unbind
            engine.unBindFramebuffer(this._texture, this.isCube);
            if (this.onGenerated) {
                this.onGenerated();
            }
        };
        ProceduralTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // RenderTarget Texture
            newTexture.coordinatesMode = this.coordinatesMode;
            return newTexture;
        };
        ProceduralTexture.prototype.dispose = function () {
            var index = this.getScene()._proceduralTextures.indexOf(this);
            if (index >= 0) {
                this.getScene()._proceduralTextures.splice(index, 1);
            }
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
                this._indexBuffer = null;
            }
            _super.prototype.dispose.call(this);
        };
        return ProceduralTexture;
    }(BABYLON.Texture));
    BABYLON.ProceduralTexture = ProceduralTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.proceduralTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var MirrorTexture = (function (_super) {
        __extends(MirrorTexture, _super);
        function MirrorTexture(name, size, scene, generateMipMaps) {
            var _this = this;
            _super.call(this, name, size, scene, generateMipMaps, true);
            this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
            this._transformMatrix = BABYLON.Matrix.Zero();
            this._mirrorMatrix = BABYLON.Matrix.Zero();
            this.onBeforeRenderObservable.add(function () {
                BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
                _this._savedViewMatrix = scene.getViewMatrix();
                _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
                scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
                scene.clipPlane = _this.mirrorPlane;
                scene.getEngine().cullBackFaces = false;
                scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
            });
            this.onAfterRenderObservable.add(function () {
                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
                scene.getEngine().cullBackFaces = true;
                scene._mirroredCameraPosition = null;
                delete scene.clipPlane;
            });
        }
        MirrorTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // Mirror Texture
            newTexture.mirrorPlane = this.mirrorPlane.clone();
            newTexture.renderList = this.renderList.slice(0);
            return newTexture;
        };
        MirrorTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.mirrorPlane = this.mirrorPlane.asArray();
            return serializationObject;
        };
        return MirrorTexture;
    }(BABYLON.RenderTargetTexture));
    BABYLON.MirrorTexture = MirrorTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.mirrorTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
    * Creates a refraction texture used by refraction channel of the standard material.
    * @param name the texture name
    * @param size size of the underlying texture
    * @param scene root scene
    */
    var RefractionTexture = (function (_super) {
        __extends(RefractionTexture, _super);
        function RefractionTexture(name, size, scene, generateMipMaps) {
            var _this = this;
            _super.call(this, name, size, scene, generateMipMaps, true);
            this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
            this.depth = 2.0;
            this.onBeforeRenderObservable.add(function () {
                scene.clipPlane = _this.refractionPlane;
            });
            this.onAfterRenderObservable.add(function () {
                delete scene.clipPlane;
            });
        }
        RefractionTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // Refraction Texture
            newTexture.refractionPlane = this.refractionPlane.clone();
            newTexture.renderList = this.renderList.slice(0);
            newTexture.depth = this.depth;
            return newTexture;
        };
        RefractionTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.mirrorPlane = this.refractionPlane.asArray();
            serializationObject.depth = this.depth;
            return serializationObject;
        };
        return RefractionTexture;
    }(BABYLON.RenderTargetTexture));
    BABYLON.RefractionTexture = RefractionTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.refractionTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var DynamicTexture = (function (_super) {
        __extends(DynamicTexture, _super);
        function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            _super.call(this, null, scene, !generateMipMaps);
            this.name = name;
            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._generateMipMaps = generateMipMaps;
            if (options.getContext) {
                this._canvas = options;
                this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
            }
            else {
                this._canvas = document.createElement("canvas");
                if (options.width) {
                    this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
                }
                else {
                    this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
                }
            }
            var textureSize = this.getSize();
            this._canvas.width = textureSize.width;
            this._canvas.height = textureSize.height;
            this._context = this._canvas.getContext("2d");
        }
        Object.defineProperty(DynamicTexture.prototype, "canRescale", {
            get: function () {
                return true;
            },
            enumerable: true,
            configurable: true
        });
        DynamicTexture.prototype.scale = function (ratio) {
            var textureSize = this.getSize();
            textureSize.width *= ratio;
            textureSize.height *= ratio;
            this._canvas.width = textureSize.width;
            this._canvas.height = textureSize.height;
            this.releaseInternalTexture();
            this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
        };
        DynamicTexture.prototype.getContext = function () {
            return this._context;
        };
        DynamicTexture.prototype.clear = function () {
            var size = this.getSize();
            this._context.fillRect(0, 0, size.width, size.height);
        };
        DynamicTexture.prototype.update = function (invertY) {
            this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
        };
        DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
            if (update === void 0) { update = true; }
            var size = this.getSize();
            if (clearColor) {
                this._context.fillStyle = clearColor;
                this._context.fillRect(0, 0, size.width, size.height);
            }
            this._context.font = font;
            if (x === null) {
                var textSize = this._context.measureText(text);
                x = (size.width - textSize.width) / 2;
            }
            this._context.fillStyle = color;
            this._context.fillText(text, x, y);
            if (update) {
                this.update(invertY);
            }
        };
        DynamicTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // Dynamic Texture
            newTexture.wrapU = this.wrapU;
            newTexture.wrapV = this.wrapV;
            return newTexture;
        };
        return DynamicTexture;
    }(BABYLON.Texture));
    BABYLON.DynamicTexture = DynamicTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.dynamicTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var VideoTexture = (function (_super) {
        __extends(VideoTexture, _super);
        /**
         * Creates a video texture.
         * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
         * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
         * @param {BABYLON.Scene} scene is obviously the current scene.
         * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
         * @param {boolean} invertY is false by default but can be used to invert video on Y axis
         * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
         */
        function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
            var _this = this;
            if (generateMipMaps === void 0) { generateMipMaps = false; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            _super.call(this, null, scene, !generateMipMaps, invertY);
            this._autoLaunch = true;
            var urls;
            this.name = name;
            if (urlsOrVideo instanceof HTMLVideoElement) {
                this.video = urlsOrVideo;
            }
            else {
                urls = urlsOrVideo;
                this.video = document.createElement("video");
                this.video.autoplay = false;
                this.video.loop = true;
            }
            this._generateMipMaps = generateMipMaps;
            this._samplingMode = samplingMode;
            if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
                this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
                this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            }
            else {
                this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                this._generateMipMaps = false;
            }
            if (urls) {
                this.video.addEventListener("canplaythrough", function () {
                    _this._createTexture();
                });
                urls.forEach(function (url) {
                    var source = document.createElement("source");
                    source.src = url;
                    _this.video.appendChild(source);
                });
            }
            else {
                this._createTexture();
            }
            this._lastUpdate = BABYLON.Tools.Now;
        }
        VideoTexture.prototype._createTexture = function () {
            this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
            this._texture.isReady = true;
        };
        VideoTexture.prototype.update = function () {
            if (this._autoLaunch) {
                this._autoLaunch = false;
                this.video.play();
            }
            var now = BABYLON.Tools.Now;
            if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
                return false;
            }
            this._lastUpdate = now;
            this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
            return true;
        };
        return VideoTexture;
    }(BABYLON.Texture));
    BABYLON.VideoTexture = VideoTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.videoTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var CustomProceduralTexture = (function (_super) {
        __extends(CustomProceduralTexture, _super);
        function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
            _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
            this._animate = true;
            this._time = 0;
            this._texturePath = texturePath;
            //Try to load json
            this.loadJson(texturePath);
            this.refreshRate = 1;
        }
        CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
            var _this = this;
            var that = this;
            function noConfigFile() {
                BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
                try {
                    that.setFragment(that._texturePath);
                }
                catch (ex) {
                    BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
                }
            }
            var configFileUrl = jsonUrl + "/config.json";
            var xhr = new XMLHttpRequest();
            xhr.open("GET", configFileUrl, true);
            xhr.addEventListener("load", function () {
                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
                    try {
                        _this._config = JSON.parse(xhr.response);
                        _this.updateShaderUniforms();
                        _this.updateTextures();
                        _this.setFragment(_this._texturePath + "/custom");
                        _this._animate = _this._config.animate;
                        _this.refreshRate = _this._config.refreshrate;
                    }
                    catch (ex) {
                        noConfigFile();
                    }
                }
                else {
                    noConfigFile();
                }
            }, false);
            xhr.addEventListener("error", function () {
                noConfigFile();
            }, false);
            try {
                xhr.send();
            }
            catch (ex) {
                BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
            }
        };
        CustomProceduralTexture.prototype.isReady = function () {
            if (!_super.prototype.isReady.call(this)) {
                return false;
            }
            for (var name in this._textures) {
                var texture = this._textures[name];
                if (!texture.isReady()) {
                    return false;
                }
            }
            return true;
        };
        CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
            if (this._animate) {
                this._time += this.getScene().getAnimationRatio() * 0.03;
                this.updateShaderUniforms();
            }
            _super.prototype.render.call(this, useCameraPostProcess);
        };
        CustomProceduralTexture.prototype.updateTextures = function () {
            for (var i = 0; i < this._config.sampler2Ds.length; i++) {
                this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
            }
        };
        CustomProceduralTexture.prototype.updateShaderUniforms = function () {
            if (this._config) {
                for (var j = 0; j < this._config.uniforms.length; j++) {
                    var uniform = this._config.uniforms[j];
                    switch (uniform.type) {
                        case "float":
                            this.setFloat(uniform.name, uniform.value);
                            break;
                        case "color3":
                            this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
                            break;
                        case "color4":
                            this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
                            break;
                        case "vector2":
                            this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
                            break;
                        case "vector3":
                            this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
                            break;
                    }
                }
            }
            this.setFloat("time", this._time);
        };
        Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
            get: function () {
                return this._animate;
            },
            set: function (value) {
                this._animate = value;
            },
            enumerable: true,
            configurable: true
        });
        return CustomProceduralTexture;
    }(BABYLON.ProceduralTexture));
    BABYLON.CustomProceduralTexture = CustomProceduralTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.customProceduralTexture.js.map
 
var BABYLON;
(function (BABYLON) {
    var EffectFallbacks = (function () {
        function EffectFallbacks() {
            this._defines = {};
            this._currentRank = 32;
            this._maxRank = -1;
        }
        EffectFallbacks.prototype.addFallback = function (rank, define) {
            if (!this._defines[rank]) {
                if (rank < this._currentRank) {
                    this._currentRank = rank;
                }
                if (rank > this._maxRank) {
                    this._maxRank = rank;
                }
                this._defines[rank] = new Array();
            }
            this._defines[rank].push(define);
        };
        EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
            this._meshRank = rank;
            this._mesh = mesh;
            if (rank > this._maxRank) {
                this._maxRank = rank;
            }
        };
        Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
            get: function () {
                return this._currentRank <= this._maxRank;
            },
            enumerable: true,
            configurable: true
        });
        EffectFallbacks.prototype.reduce = function (currentDefines) {
            var currentFallbacks = this._defines[this._currentRank];
            for (var index = 0; index < currentFallbacks.length; index++) {
                currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
            }
            if (this._mesh && this._currentRank === this._meshRank) {
                this._mesh.computeBonesUsingShaders = false;
                currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
                BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
            }
            this._currentRank++;
            return currentDefines;
        };
        return EffectFallbacks;
    }());
    BABYLON.EffectFallbacks = EffectFallbacks;
    var Effect = (function () {
        function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
            var _this = this;
            this._isReady = false;
            this._compilationError = "";
            this._valueCache = {};
            this._engine = engine;
            this.name = baseName;
            this.defines = defines;
            this._uniformsNames = uniformsNames.concat(samplers);
            this._samplers = samplers;
            this._attributesNames = attributesNames;
            this.onError = onError;
            this.onCompiled = onCompiled;
            this._indexParameters = indexParameters;
            var vertexSource;
            var fragmentSource;
            if (baseName.vertexElement) {
                vertexSource = document.getElementById(baseName.vertexElement);
                if (!vertexSource) {
                    vertexSource = baseName.vertexElement;
                }
            }
            else {
                vertexSource = baseName.vertex || baseName;
            }
            if (baseName.fragmentElement) {
                fragmentSource = document.getElementById(baseName.fragmentElement);
                if (!fragmentSource) {
                    fragmentSource = baseName.fragmentElement;
                }
            }
            else {
                fragmentSource = baseName.fragment || baseName;
            }
            this._loadVertexShader(vertexSource, function (vertexCode) {
                _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
                    _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
                        _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
                            _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
                        });
                    });
                });
            });
        }
        // Properties
        Effect.prototype.isReady = function () {
            return this._isReady;
        };
        Effect.prototype.getProgram = function () {
            return this._program;
        };
        Effect.prototype.getAttributesNames = function () {
            return this._attributesNames;
        };
        Effect.prototype.getAttributeLocation = function (index) {
            return this._attributes[index];
        };
        Effect.prototype.getAttributeLocationByName = function (name) {
            var index = this._attributesNames.indexOf(name);
            return this._attributes[index];
        };
        Effect.prototype.getAttributesCount = function () {
            return this._attributes.length;
        };
        Effect.prototype.getUniformIndex = function (uniformName) {
            return this._uniformsNames.indexOf(uniformName);
        };
        Effect.prototype.getUniform = function (uniformName) {
            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
        };
        Effect.prototype.getSamplers = function () {
            return this._samplers;
        };
        Effect.prototype.getCompilationError = function () {
            return this._compilationError;
        };
        Effect.prototype.getVertexShaderSource = function () {
            return this._engine.getVertexShaderSource(this._program);
        };
        Effect.prototype.getFragmentShaderSource = function () {
            return this._engine.getFragmentShaderSource(this._program);
        };
        // Methods
        Effect.prototype._loadVertexShader = function (vertex, callback) {
            // DOM element ?
            if (vertex instanceof HTMLElement) {
                var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
                callback(vertexCode);
                return;
            }
            // Base64 encoded ?
            if (vertex.substr(0, 7) === "base64:") {
                var vertexBinary = window.atob(vertex.substr(7));
                callback(vertexBinary);
                return;
            }
            // Is in local store ?
            if (Effect.ShadersStore[vertex + "VertexShader"]) {
                callback(Effect.ShadersStore[vertex + "VertexShader"]);
                return;
            }
            var vertexShaderUrl;
            if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
                vertexShaderUrl = vertex;
            }
            else {
                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
            }
            // Vertex shader
            BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
        };
        Effect.prototype._loadFragmentShader = function (fragment, callback) {
            // DOM element ?
            if (fragment instanceof HTMLElement) {
                var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
                callback(fragmentCode);
                return;
            }
            // Base64 encoded ?
            if (fragment.substr(0, 7) === "base64:") {
                var fragmentBinary = window.atob(fragment.substr(7));
                callback(fragmentBinary);
                return;
            }
            // Is in local store ?
            if (Effect.ShadersStore[fragment + "PixelShader"]) {
                callback(Effect.ShadersStore[fragment + "PixelShader"]);
                return;
            }
            if (Effect.ShadersStore[fragment + "FragmentShader"]) {
                callback(Effect.ShadersStore[fragment + "FragmentShader"]);
                return;
            }
            var fragmentShaderUrl;
            if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
                fragmentShaderUrl = fragment;
            }
            else {
                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
            }
            // Fragment shader
            BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
        };
        Effect.prototype._dumpShadersName = function () {
            if (this.name.vertexElement) {
                BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
                BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
            }
            else if (this.name.vertex) {
                BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
                BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
            }
            else {
                BABYLON.Tools.Error("Vertex shader:" + this.name);
                BABYLON.Tools.Error("Fragment shader:" + this.name);
            }
        };
        Effect.prototype._processIncludes = function (sourceCode, callback) {
            var _this = this;
            var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
            var match = regex.exec(sourceCode);
            var returnValue = new String(sourceCode);
            while (match != null) {
                var includeFile = match[1];
                if (Effect.IncludesShadersStore[includeFile]) {
                    // Substitution
                    var includeContent = Effect.IncludesShadersStore[includeFile];
                    if (match[2]) {
                        var splits = match[3].split(",");
                        for (var index = 0; index < splits.length; index += 2) {
                            var source = new RegExp(splits[index], "g");
                            var dest = splits[index + 1];
                            includeContent = includeContent.replace(source, dest);
                        }
                    }
                    if (match[4]) {
                        var indexString = match[5];
                        if (indexString.indexOf("..") !== -1) {
                            var indexSplits = indexString.split("..");
                            var minIndex = parseInt(indexSplits[0]);
                            var maxIndex = parseInt(indexSplits[1]);
                            var sourceIncludeContent = includeContent.slice(0);
                            includeContent = "";
                            if (isNaN(maxIndex)) {
                                maxIndex = this._indexParameters[indexSplits[1]];
                            }
                            for (var i = minIndex; i <= maxIndex; i++) {
                                includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
                            }
                        }
                        else {
                            includeContent = includeContent.replace(/\{X\}/g, indexString);
                        }
                    }
                    // Replace
                    returnValue = returnValue.replace(match[0], includeContent);
                }
                else {
                    var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
                    BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
                        Effect.IncludesShadersStore[includeFile] = fileContent;
                        _this._processIncludes(returnValue, callback);
                    });
                    return;
                }
                match = regex.exec(sourceCode);
            }
            callback(returnValue);
        };
        Effect.prototype._processPrecision = function (source) {
            if (source.indexOf("precision highp float") === -1) {
                if (!this._engine.getCaps().highPrecisionShaderSupported) {
                    source = "precision mediump float;\n" + source;
                }
                else {
                    source = "precision highp float;\n" + source;
                }
            }
            else {
                if (!this._engine.getCaps().highPrecisionShaderSupported) {
                    source = source.replace("precision highp float", "precision mediump float");
                }
            }
            return source;
        };
        Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
            try {
                var engine = this._engine;
                // Precision
                vertexSourceCode = this._processPrecision(vertexSourceCode);
                fragmentSourceCode = this._processPrecision(fragmentSourceCode);
                this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
                this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
                this._attributes = engine.getAttributes(this._program, attributesNames);
                var index;
                for (index = 0; index < this._samplers.length; index++) {
                    var sampler = this.getUniform(this._samplers[index]);
                    if (sampler == null) {
                        this._samplers.splice(index, 1);
                        index--;
                    }
                }
                engine.bindSamplers(this);
                this._compilationError = "";
                this._isReady = true;
                if (this.onCompiled) {
                    this.onCompiled(this);
                }
            }
            catch (e) {
                this._compilationError = e.message;
                // Let's go through fallbacks then
                BABYLON.Tools.Error("Unable to compile effect: ");
                BABYLON.Tools.Error("Defines: " + defines);
                BABYLON.Tools.Error("Error: " + this._compilationError);
                this._dumpShadersName();
                if (fallbacks && fallbacks.isMoreFallbacks) {
                    BABYLON.Tools.Error("Trying next fallback.");
                    defines = fallbacks.reduce(defines);
                    this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
                }
                else {
                    if (this.onError) {
                        this.onError(this, this._compilationError);
                    }
                }
            }
        };
        Object.defineProperty(Effect.prototype, "isSupported", {
            get: function () {
                return this._compilationError === "";
            },
            enumerable: true,
            configurable: true
        });
        Effect.prototype._bindTexture = function (channel, texture) {
            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
        };
        Effect.prototype.setTexture = function (channel, texture) {
            this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
        };
        Effect.prototype.setTextureArray = function (channel, textures) {
            if (this._samplers.indexOf(channel + "Ex") === -1) {
                var initialPos = this._samplers.indexOf(channel);
                for (var index = 1; index < textures.length; index++) {
                    this._samplers.splice(initialPos + index, 0, channel + "Ex");
                }
            }
            this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
        };
        Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
        };
        Effect.prototype._cacheMatrix = function (uniformName, matrix) {
            var changed = false;
            var cache = this._valueCache[uniformName];
            if (!cache || !(cache instanceof BABYLON.Matrix)) {
                changed = true;
                cache = new BABYLON.Matrix();
            }
            var tm = cache.m;
            var om = matrix.m;
            for (var index = 0; index < 16; index++) {
                if (tm[index] !== om[index]) {
                    tm[index] = om[index];
                    changed = true;
                }
            }
            this._valueCache[uniformName] = cache;
            return changed;
        };
        Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
            var cache = this._valueCache[uniformName];
            if (!cache) {
                cache = [x, y];
                this._valueCache[uniformName] = cache;
                return true;
            }
            var changed = false;
            if (cache[0] !== x) {
                cache[0] = x;
                changed = true;
            }
            if (cache[1] !== y) {
                cache[1] = y;
                changed = true;
            }
            return changed;
        };
        Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
            var cache = this._valueCache[uniformName];
            if (!cache) {
                cache = [x, y, z];
                this._valueCache[uniformName] = cache;
                return true;
            }
            var changed = false;
            if (cache[0] !== x) {
                cache[0] = x;
                changed = true;
            }
            if (cache[1] !== y) {
                cache[1] = y;
                changed = true;
            }
            if (cache[2] !== z) {
                cache[2] = z;
                changed = true;
            }
            return changed;
        };
        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
            var cache = this._valueCache[uniformName];
            if (!cache) {
                cache = [x, y, z, w];
                this._valueCache[uniformName] = cache;
                return true;
            }
            var changed = false;
            if (cache[0] !== x) {
                cache[0] = x;
                changed = true;
            }
            if (cache[1] !== y) {
                cache[1] = y;
                changed = true;
            }
            if (cache[2] !== z) {
                cache[2] = z;
                changed = true;
            }
            if (cache[3] !== w) {
                cache[3] = w;
                changed = true;
            }
            return changed;
        };
        Effect.prototype.setIntArray = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setIntArray2 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray2(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setIntArray3 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray3(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setIntArray4 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray4(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setFloatArray = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setFloatArray2 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray2(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setFloatArray3 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray3(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setFloatArray4 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray4(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setArray = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setArray2 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray2(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setArray3 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray3(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setArray4 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray4(this.getUniform(uniformName), array);
            return this;
        };
        Effect.prototype.setMatrices = function (uniformName, matrices) {
            this._valueCache[uniformName] = null;
            this._engine.setMatrices(this.getUniform(uniformName), matrices);
            return this;
        };
        Effect.prototype.setMatrix = function (uniformName, matrix) {
            if (this._cacheMatrix(uniformName, matrix)) {
                this._engine.setMatrix(this.getUniform(uniformName), matrix);
            }
            return this;
        };
        Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
            this._valueCache[uniformName] = null;
            this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
            return this;
        };
        Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
            this._valueCache[uniformName] = null;
            this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
            return this;
        };
        Effect.prototype.setFloat = function (uniformName, value) {
            var cache = this._valueCache[uniformName];
            if (cache !== undefined && cache === value)
                return this;
            this._valueCache[uniformName] = value;
            this._engine.setFloat(this.getUniform(uniformName), value);
            return this;
        };
        Effect.prototype.setBool = function (uniformName, bool) {
            var cache = this._valueCache[uniformName];
            if (cache !== undefined && cache === bool)
                return this;
            this._valueCache[uniformName] = bool;
            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
            return this;
        };
        Effect.prototype.setVector2 = function (uniformName, vector2) {
            if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
                this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
            }
            return this;
        };
        Effect.prototype.setFloat2 = function (uniformName, x, y) {
            if (this._cacheFloat2(uniformName, x, y)) {
                this._engine.setFloat2(this.getUniform(uniformName), x, y);
            }
            return this;
        };
        Effect.prototype.setVector3 = function (uniformName, vector3) {
            if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
                this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
            }
            return this;
        };
        Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
            if (this._cacheFloat3(uniformName, x, y, z)) {
                this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
            }
            return this;
        };
        Effect.prototype.setVector4 = function (uniformName, vector4) {
            if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
                this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
            }
            return this;
        };
        Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
            if (this._cacheFloat4(uniformName, x, y, z, w)) {
                this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
            }
            return this;
        };
        Effect.prototype.setColor3 = function (uniformName, color3) {
            if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
                this._engine.setColor3(this.getUniform(uniformName), color3);
            }
            return this;
        };
        Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
            if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
                this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
            }
            return this;
        };
        // Statics
        Effect.ShadersStore = {};
        Effect.IncludesShadersStore = {};
        return Effect;
    }());
    BABYLON.Effect = Effect;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.effect.js.map
 
var BABYLON;
(function (BABYLON) {
    var MaterialHelper = (function () {
        function MaterialHelper() {
        }
        MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            var lightIndex = 0;
            var needNormals = false;
            var needRebuild = false;
            var needShadows = false;
            var lightmapMode = false;
            for (var index = 0; index < scene.lights.length; index++) {
                var light = scene.lights[index];
                if (!light.isEnabled()) {
                    continue;
                }
                // Excluded check
                if (light._excludedMeshesIds.length > 0) {
                    for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
                        var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
                        if (excludedMesh) {
                            light.excludedMeshes.push(excludedMesh);
                        }
                    }
                    light._excludedMeshesIds = [];
                }
                // Included check
                if (light._includedOnlyMeshesIds.length > 0) {
                    for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
                        var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
                        if (includedOnlyMesh) {
                            light.includedOnlyMeshes.push(includedOnlyMesh);
                        }
                    }
                    light._includedOnlyMeshesIds = [];
                }
                if (!light.canAffectMesh(mesh)) {
                    continue;
                }
                needNormals = true;
                if (defines["LIGHT" + lightIndex] === undefined) {
                    needRebuild = true;
                }
                defines["LIGHT" + lightIndex] = true;
                var type;
                if (light instanceof BABYLON.SpotLight) {
                    type = "SPOTLIGHT" + lightIndex;
                }
                else if (light instanceof BABYLON.HemisphericLight) {
                    type = "HEMILIGHT" + lightIndex;
                }
                else if (light instanceof BABYLON.PointLight) {
                    type = "POINTLIGHT" + lightIndex;
                }
                else {
                    type = "DIRLIGHT" + lightIndex;
                }
                if (defines[type] === undefined) {
                    needRebuild = true;
                }
                defines[type] = true;
                // Specular
                if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
                    defines["SPECULARTERM"] = true;
                }
                // Shadows
                if (scene.shadowsEnabled) {
                    var shadowGenerator = light.getShadowGenerator();
                    if (mesh && mesh.receiveShadows && shadowGenerator) {
                        if (defines["SHADOW" + lightIndex] === undefined) {
                            needRebuild = true;
                        }
                        defines["SHADOW" + lightIndex] = true;
                        defines["SHADOWS"] = true;
                        if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
                            if (defines["SHADOWVSM" + lightIndex] === undefined) {
                                needRebuild = true;
                            }
                            defines["SHADOWVSM" + lightIndex] = true;
                        }
                        if (shadowGenerator.usePoissonSampling) {
                            if (defines["SHADOWPCF" + lightIndex] === undefined) {
                                needRebuild = true;
                            }
                            defines["SHADOWPCF" + lightIndex] = true;
                        }
                        needShadows = true;
                    }
                }
                if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
                    lightmapMode = true;
                    if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
                        needRebuild = true;
                    }
                    if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
                        needRebuild = true;
                    }
                    defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
                    if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
                        defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
                    }
                }
                lightIndex++;
                if (lightIndex === maxSimultaneousLights)
                    break;
            }
            var caps = scene.getEngine().getCaps();
            if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
                if (defines["SHADOWFULLFLOAT"] === undefined) {
                    needRebuild = true;
                }
                defines["SHADOWFULLFLOAT"] = true;
            }
            if (defines["LIGHTMAPEXCLUDED"] === undefined) {
                needRebuild = true;
            }
            if (lightmapMode) {
                defines["LIGHTMAPEXCLUDED"] = true;
            }
            if (needRebuild) {
                defines.rebuild();
            }
            return needNormals;
        };
        MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
                if (!defines["LIGHT" + lightIndex]) {
                    break;
                }
                uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
                samplersList.push("shadowSampler" + lightIndex);
            }
        };
        MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
                if (!defines["LIGHT" + lightIndex]) {
                    break;
                }
                if (lightIndex > 0) {
                    fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
                }
                if (defines["SHADOW" + lightIndex]) {
                    fallbacks.addFallback(0, "SHADOW" + lightIndex);
                }
                if (defines["SHADOWPCF" + lightIndex]) {
                    fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
                }
                if (defines["SHADOWVSM" + lightIndex]) {
                    fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
                }
            }
        };
        MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
            if (defines["NUM_BONE_INFLUENCERS"] > 0) {
                fallbacks.addCPUSkinningFallback(0, mesh);
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (defines["NUM_BONE_INFLUENCERS"] > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
            }
        };
        MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
            if (defines["INSTANCES"]) {
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
        };
        // Bindings
        MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
            var shadowGenerator = light.getShadowGenerator();
            if (mesh.receiveShadows && shadowGenerator) {
                if (!light.needCube()) {
                    effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
                }
                else {
                    if (!depthValuesAlreadySet) {
                        depthValuesAlreadySet = true;
                        effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
                    }
                }
                effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
                effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
            }
            return depthValuesAlreadySet;
        };
        MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
            if (light instanceof BABYLON.PointLight) {
                // Point Light
                light.transferToEffect(effect, "vLightData" + lightIndex);
            }
            else if (light instanceof BABYLON.DirectionalLight) {
                // Directional Light
                light.transferToEffect(effect, "vLightData" + lightIndex);
            }
            else if (light instanceof BABYLON.SpotLight) {
                // Spot Light
                light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
            }
            else if (light instanceof BABYLON.HemisphericLight) {
                // Hemispheric Light
                light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
            }
        };
        MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            var lightIndex = 0;
            var depthValuesAlreadySet = false;
            for (var index = 0; index < scene.lights.length; index++) {
                var light = scene.lights[index];
                if (!light.isEnabled()) {
                    continue;
                }
                if (!light.canAffectMesh(mesh)) {
                    continue;
                }
                MaterialHelper.BindLightProperties(light, effect, lightIndex);
                light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
                effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
                if (defines["SPECULARTERM"]) {
                    light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
                    effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
                }
                // Shadows
                if (scene.shadowsEnabled) {
                    depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
                }
                lightIndex++;
                if (lightIndex === maxSimultaneousLights)
                    break;
            }
        };
        MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
                effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
                effect.setColor3("vFogColor", scene.fogColor);
            }
        };
        MaterialHelper.BindBonesParameters = function (mesh, effect) {
            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
                var matrices = mesh.skeleton.getTransformMatrices(mesh);
                if (matrices) {
                    effect.setMatrices("mBones", matrices);
                }
            }
        };
        MaterialHelper.BindLogDepth = function (defines, effect, scene) {
            if (defines["LOGARITHMICDEPTH"]) {
                effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
            }
        };
        MaterialHelper.BindClipPlane = function (effect, scene) {
            if (scene.clipPlane) {
                var clipPlane = scene.clipPlane;
                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
            }
        };
        return MaterialHelper;
    }());
    BABYLON.MaterialHelper = MaterialHelper;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.materialHelper.js.map
 
var BABYLON;
(function (BABYLON) {
    var FresnelParameters = (function () {
        function FresnelParameters() {
            this.isEnabled = true;
            this.leftColor = BABYLON.Color3.White();
            this.rightColor = BABYLON.Color3.Black();
            this.bias = 0;
            this.power = 1;
        }
        FresnelParameters.prototype.clone = function () {
            var newFresnelParameters = new FresnelParameters();
            BABYLON.Tools.DeepCopy(this, newFresnelParameters);
            return newFresnelParameters;
        };
        FresnelParameters.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.isEnabled = this.isEnabled;
            serializationObject.leftColor = this.leftColor;
            serializationObject.rightColor = this.rightColor;
            serializationObject.bias = this.bias;
            serializationObject.power = this.power;
            return serializationObject;
        };
        FresnelParameters.Parse = function (parsedFresnelParameters) {
            var fresnelParameters = new FresnelParameters();
            fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
            fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
            fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
            fresnelParameters.bias = parsedFresnelParameters.bias;
            fresnelParameters.power = parsedFresnelParameters.power || 1.0;
            return fresnelParameters;
        };
        return FresnelParameters;
    }());
    BABYLON.FresnelParameters = FresnelParameters;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.fresnelParameters.js.map
 
 
var BABYLON;
(function (BABYLON) {
    var MaterialDefines = (function () {
        function MaterialDefines() {
        }
        MaterialDefines.prototype.rebuild = function () {
            if (this._keys) {
                delete this._keys;
            }
            this._keys = Object.keys(this);
        };
        MaterialDefines.prototype.isEqual = function (other) {
            if (this._keys.length !== other._keys.length) {
                return false;
            }
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                if (this[prop] !== other[prop]) {
                    return false;
                }
            }
            return true;
        };
        MaterialDefines.prototype.cloneTo = function (other) {
            if (this._keys.length !== other._keys.length) {
                other._keys = this._keys.slice(0);
            }
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                other[prop] = this[prop];
            }
        };
        MaterialDefines.prototype.reset = function () {
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                if (typeof (this[prop]) === "number") {
                    this[prop] = 0;
                }
                else {
                    this[prop] = false;
                }
            }
        };
        MaterialDefines.prototype.toString = function () {
            var result = "";
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                if (typeof (this[prop]) === "number") {
                    result += "#define " + prop + " " + this[prop] + "\n";
                }
                else if (this[prop]) {
                    result += "#define " + prop + "\n";
                }
            }
            return result;
        };
        return MaterialDefines;
    }());
    BABYLON.MaterialDefines = MaterialDefines;
    var Material = (function () {
        function Material(name, scene, doNotAdd) {
            this.checkReadyOnEveryCall = false;
            this.checkReadyOnlyOnce = false;
            this.state = "";
            this.alpha = 1.0;
            this.backFaceCulling = true;
            this.doNotSerialize = false;
            /**
            * An event triggered when the material is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
            * An event triggered when the material is bound.
            * @type {BABYLON.Observable}
            */
            this.onBindObservable = new BABYLON.Observable();
            /**
            * An event triggered when the material is unbound.
            * @type {BABYLON.Observable}
            */
            this.onUnBindObservable = new BABYLON.Observable();
            this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
            this.disableDepthWrite = false;
            this.fogEnabled = true;
            this.pointSize = 1.0;
            this.zOffset = 0;
            this._wasPreviouslyReady = false;
            this._fillMode = Material.TriangleFillMode;
            this.name = name;
            this.id = name;
            this._scene = scene;
            if (scene.useRightHandedSystem) {
                this.sideOrientation = Material.ClockWiseSideOrientation;
            }
            else {
                this.sideOrientation = Material.CounterClockWiseSideOrientation;
            }
            if (!doNotAdd) {
                scene.materials.push(this);
            }
        }
        Object.defineProperty(Material, "TriangleFillMode", {
            get: function () {
                return Material._TriangleFillMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "WireFrameFillMode", {
            get: function () {
                return Material._WireFrameFillMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "PointFillMode", {
            get: function () {
                return Material._PointFillMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "ClockWiseSideOrientation", {
            get: function () {
                return Material._ClockWiseSideOrientation;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
            get: function () {
                return Material._CounterClockWiseSideOrientation;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "onBind", {
            set: function (callback) {
                if (this._onBindObserver) {
                    this.onBindObservable.remove(this._onBindObserver);
                }
                this._onBindObserver = this.onBindObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "wireframe", {
            get: function () {
                return this._fillMode === Material.WireFrameFillMode;
            },
            set: function (value) {
                this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "pointsCloud", {
            get: function () {
                return this._fillMode === Material.PointFillMode;
            },
            set: function (value) {
                this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "fillMode", {
            get: function () {
                return this._fillMode;
            },
            set: function (value) {
                this._fillMode = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         * subclasses should override adding information pertainent to themselves
         */
        Material.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            if (fullDetails) {
            }
            return ret;
        };
        Object.defineProperty(Material.prototype, "isFrozen", {
            get: function () {
                return this.checkReadyOnlyOnce;
            },
            enumerable: true,
            configurable: true
        });
        Material.prototype.freeze = function () {
            this.checkReadyOnlyOnce = true;
        };
        Material.prototype.unfreeze = function () {
            this.checkReadyOnlyOnce = false;
        };
        Material.prototype.isReady = function (mesh, useInstances) {
            return true;
        };
        Material.prototype.getEffect = function () {
            return this._effect;
        };
        Material.prototype.getScene = function () {
            return this._scene;
        };
        Material.prototype.needAlphaBlending = function () {
            return (this.alpha < 1.0);
        };
        Material.prototype.needAlphaTesting = function () {
            return false;
        };
        Material.prototype.getAlphaTestTexture = function () {
            return null;
        };
        Material.prototype.markDirty = function () {
            this._wasPreviouslyReady = false;
        };
        Material.prototype._preBind = function () {
            var engine = this._scene.getEngine();
            var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
            engine.enableEffect(this._effect);
            engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
        };
        Material.prototype.bind = function (world, mesh) {
            this._scene._cachedMaterial = this;
            this.onBindObservable.notifyObservers(mesh);
            if (this.disableDepthWrite) {
                var engine = this._scene.getEngine();
                this._cachedDepthWriteState = engine.getDepthWrite();
                engine.setDepthWrite(false);
            }
        };
        Material.prototype.bindOnlyWorldMatrix = function (world) {
        };
        Material.prototype.unbind = function () {
            this.onUnBindObservable.notifyObservers(this);
            if (this.disableDepthWrite) {
                var engine = this._scene.getEngine();
                engine.setDepthWrite(this._cachedDepthWriteState);
            }
        };
        Material.prototype.clone = function (name) {
            return null;
        };
        Material.prototype.getBindedMeshes = function () {
            var result = new Array();
            for (var index = 0; index < this._scene.meshes.length; index++) {
                var mesh = this._scene.meshes[index];
                if (mesh.material === this) {
                    result.push(mesh);
                }
            }
            return result;
        };
        Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            var index = this._scene.materials.indexOf(this);
            if (index >= 0) {
                this._scene.materials.splice(index, 1);
            }
            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
            if (forceDisposeEffect && this._effect) {
                this._scene.getEngine()._releaseEffect(this._effect);
                this._effect = null;
            }
            // Remove from meshes
            for (index = 0; index < this._scene.meshes.length; index++) {
                var mesh = this._scene.meshes[index];
                if (mesh.material === this) {
                    mesh.material = null;
                }
            }
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onBindObservable.clear();
            this.onUnBindObservable.clear();
        };
        Material.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
            multiMaterial.id = parsedMultiMaterial.id;
            BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
            for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
                var subMatId = parsedMultiMaterial.materials[matIndex];
                if (subMatId) {
                    multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
                }
                else {
                    multiMaterial.subMaterials.push(null);
                }
            }
            return multiMaterial;
        };
        Material.Parse = function (parsedMaterial, scene, rootUrl) {
            if (!parsedMaterial.customType) {
                return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
            }
            var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
            return materialType.Parse(parsedMaterial, scene, rootUrl);
            ;
        };
        Material._TriangleFillMode = 0;
        Material._WireFrameFillMode = 1;
        Material._PointFillMode = 2;
        Material._ClockWiseSideOrientation = 0;
        Material._CounterClockWiseSideOrientation = 1;
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "id", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "name", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "checkReadyOnEveryCall", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "checkReadyOnlyOnce", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "state", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "alpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "backFaceCulling", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "sideOrientation", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "alphaMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "disableDepthWrite", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "fogEnabled", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "pointSize", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "zOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "wireframe", null);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "pointsCloud", null);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "fillMode", null);
        return Material;
    }());
    BABYLON.Material = Material;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.material.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var StandardMaterialDefines = (function (_super) {
        __extends(StandardMaterialDefines, _super);
        function StandardMaterialDefines() {
            _super.call(this);
            this.DIFFUSE = false;
            this.AMBIENT = false;
            this.OPACITY = false;
            this.OPACITYRGB = false;
            this.REFLECTION = false;
            this.EMISSIVE = false;
            this.SPECULAR = false;
            this.BUMP = false;
            this.PARALLAX = false;
            this.PARALLAXOCCLUSION = false;
            this.SPECULAROVERALPHA = false;
            this.CLIPPLANE = false;
            this.ALPHATEST = false;
            this.ALPHAFROMDIFFUSE = false;
            this.POINTSIZE = false;
            this.FOG = false;
            this.SPECULARTERM = false;
            this.DIFFUSEFRESNEL = false;
            this.OPACITYFRESNEL = false;
            this.REFLECTIONFRESNEL = false;
            this.REFRACTIONFRESNEL = false;
            this.EMISSIVEFRESNEL = false;
            this.FRESNEL = false;
            this.NORMAL = false;
            this.UV1 = false;
            this.UV2 = false;
            this.VERTEXCOLOR = false;
            this.VERTEXALPHA = false;
            this.NUM_BONE_INFLUENCERS = 0;
            this.BonesPerMesh = 0;
            this.INSTANCES = false;
            this.GLOSSINESS = false;
            this.ROUGHNESS = false;
            this.EMISSIVEASILLUMINATION = false;
            this.LINKEMISSIVEWITHDIFFUSE = false;
            this.REFLECTIONFRESNELFROMSPECULAR = false;
            this.LIGHTMAP = false;
            this.USELIGHTMAPASSHADOWMAP = false;
            this.REFLECTIONMAP_3D = false;
            this.REFLECTIONMAP_SPHERICAL = false;
            this.REFLECTIONMAP_PLANAR = false;
            this.REFLECTIONMAP_CUBIC = false;
            this.REFLECTIONMAP_PROJECTION = false;
            this.REFLECTIONMAP_SKYBOX = false;
            this.REFLECTIONMAP_EXPLICIT = false;
            this.REFLECTIONMAP_EQUIRECTANGULAR = false;
            this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
            this.INVERTCUBICMAP = false;
            this.LOGARITHMICDEPTH = false;
            this.REFRACTION = false;
            this.REFRACTIONMAP_3D = false;
            this.REFLECTIONOVERALPHA = false;
            this.INVERTNORMALMAPX = false;
            this.INVERTNORMALMAPY = false;
            this.SHADOWFULLFLOAT = false;
            this.CAMERACOLORGRADING = false;
            this.CAMERACOLORCURVES = false;
            this.rebuild();
        }
        return StandardMaterialDefines;
    }(BABYLON.MaterialDefines));
    var StandardMaterial = (function (_super) {
        __extends(StandardMaterial, _super);
        function StandardMaterial(name, scene) {
            var _this = this;
            _super.call(this, name, scene);
            this.ambientColor = new BABYLON.Color3(0, 0, 0);
            this.diffuseColor = new BABYLON.Color3(1, 1, 1);
            this.specularColor = new BABYLON.Color3(1, 1, 1);
            this.emissiveColor = new BABYLON.Color3(0, 0, 0);
            this.specularPower = 64;
            this.useAlphaFromDiffuseTexture = false;
            this.useEmissiveAsIllumination = false;
            this.linkEmissiveWithDiffuse = false;
            this.useReflectionFresnelFromSpecular = false;
            this.useSpecularOverAlpha = false;
            this.useReflectionOverAlpha = false;
            this.disableLighting = false;
            this.useParallax = false;
            this.useParallaxOcclusion = false;
            this.parallaxScaleBias = 0.05;
            this.roughness = 0;
            this.indexOfRefraction = 0.98;
            this.invertRefractionY = true;
            this.useLightmapAsShadowmap = false;
            this.useGlossinessFromSpecularMapAlpha = false;
            this.maxSimultaneousLights = 4;
            /**
             * If sets to true, x component of normal map value will invert (x = 1.0 - x).
             */
            this.invertNormalMapX = false;
            /**
             * If sets to true, y component of normal map value will invert (y = 1.0 - y).
             */
            this.invertNormalMapY = false;
            /**
             * Color Grading 2D Lookup Texture.
             * This allows special effects like sepia, black and white to sixties rendering style.
             */
            this.cameraColorGradingTexture = null;
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            this.cameraColorCurves = null;
            this._renderTargets = new BABYLON.SmartArray(16);
            this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
            this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
            this._defines = new StandardMaterialDefines();
            this._cachedDefines = new StandardMaterialDefines();
            this._cachedDefines.BonesPerMesh = -1;
            this.getRenderTargetTextures = function () {
                _this._renderTargets.reset();
                if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this.reflectionTexture);
                }
                if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this.refractionTexture);
                }
                return _this._renderTargets;
            };
        }
        Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
            get: function () {
                return this._useLogarithmicDepth;
            },
            set: function (value) {
                this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
            },
            enumerable: true,
            configurable: true
        });
        StandardMaterial.prototype.needAlphaBlending = function () {
            return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
        };
        StandardMaterial.prototype.needAlphaTesting = function () {
            return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
        };
        StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
            return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
        };
        StandardMaterial.prototype.getAlphaTestTexture = function () {
            return this.diffuseTexture;
        };
        // Methods   
        StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
            if (!mesh) {
                return true;
            }
            if (this._defines.INSTANCES !== useInstances) {
                return false;
            }
            if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
                return true;
            }
            return false;
        };
        StandardMaterial.prototype.isReady = function (mesh, useInstances) {
            if (this.isFrozen) {
                if (this._wasPreviouslyReady) {
                    return true;
                }
            }
            var scene = this.getScene();
            var engine = scene.getEngine();
            var needUVs = false;
            var needNormals = false;
            this._defines.reset();
            // Lights
            if (scene.lightsEnabled && !this.disableLighting) {
                needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
            }
            if (!this.checkReadyOnEveryCall) {
                if (this._renderId === scene.getRenderId()) {
                    if (this._checkCache(scene, mesh, useInstances)) {
                        return true;
                    }
                }
            }
            // Textures
            if (scene.texturesEnabled) {
                if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
                    if (!this.diffuseTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.DIFFUSE = true;
                    }
                }
                if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
                    if (!this.ambientTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.AMBIENT = true;
                    }
                }
                if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
                    if (!this.opacityTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.OPACITY = true;
                        if (this.opacityTexture.getAlphaFromRGB) {
                            this._defines.OPACITYRGB = true;
                        }
                    }
                }
                if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
                    if (!this.reflectionTexture.isReady()) {
                        return false;
                    }
                    else {
                        needNormals = true;
                        this._defines.REFLECTION = true;
                        if (this.roughness > 0) {
                            this._defines.ROUGHNESS = true;
                        }
                        if (this.useReflectionOverAlpha) {
                            this._defines.REFLECTIONOVERALPHA = true;
                        }
                        if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
                            this._defines.INVERTCUBICMAP = true;
                        }
                        this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
                        switch (this.reflectionTexture.coordinatesMode) {
                            case BABYLON.Texture.CUBIC_MODE:
                            case BABYLON.Texture.INVCUBIC_MODE:
                                this._defines.REFLECTIONMAP_CUBIC = true;
                                break;
                            case BABYLON.Texture.EXPLICIT_MODE:
                                this._defines.REFLECTIONMAP_EXPLICIT = true;
                                break;
                            case BABYLON.Texture.PLANAR_MODE:
                                this._defines.REFLECTIONMAP_PLANAR = true;
                                break;
                            case BABYLON.Texture.PROJECTION_MODE:
                                this._defines.REFLECTIONMAP_PROJECTION = true;
                                break;
                            case BABYLON.Texture.SKYBOX_MODE:
                                this._defines.REFLECTIONMAP_SKYBOX = true;
                                break;
                            case BABYLON.Texture.SPHERICAL_MODE:
                                this._defines.REFLECTIONMAP_SPHERICAL = true;
                                break;
                            case BABYLON.Texture.EQUIRECTANGULAR_MODE:
                                this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
                                break;
                            case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
                                this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
                                break;
                        }
                    }
                }
                if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
                    if (!this.emissiveTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.EMISSIVE = true;
                    }
                }
                if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
                    if (!this.lightmapTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.LIGHTMAP = true;
                        this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
                    }
                }
                if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
                    if (!this.specularTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.SPECULAR = true;
                        this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
                    }
                }
                if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
                    if (!this.bumpTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.BUMP = true;
                        if (this.useParallax) {
                            this._defines.PARALLAX = true;
                            if (this.useParallaxOcclusion) {
                                this._defines.PARALLAXOCCLUSION = true;
                            }
                        }
                        if (this.invertNormalMapX) {
                            this._defines.INVERTNORMALMAPX = true;
                        }
                        if (this.invertNormalMapY) {
                            this._defines.INVERTNORMALMAPY = true;
                        }
                    }
                }
                if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
                    if (!this.refractionTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.REFRACTION = true;
                        this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
                    }
                }
                if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
                    if (!this.cameraColorGradingTexture.isReady()) {
                        return false;
                    }
                    else {
                        this._defines.CAMERACOLORGRADING = true;
                    }
                }
            }
            // Effect
            if (scene.clipPlane) {
                this._defines.CLIPPLANE = true;
            }
            if (engine.getAlphaTesting()) {
                this._defines.ALPHATEST = true;
            }
            if (this._shouldUseAlphaFromDiffuseTexture()) {
                this._defines.ALPHAFROMDIFFUSE = true;
            }
            if (this.useEmissiveAsIllumination) {
                this._defines.EMISSIVEASILLUMINATION = true;
            }
            if (this.linkEmissiveWithDiffuse) {
                this._defines.LINKEMISSIVEWITHDIFFUSE = true;
            }
            if (this.useLogarithmicDepth) {
                this._defines.LOGARITHMICDEPTH = true;
            }
            if (this.cameraColorCurves) {
                this._defines.CAMERACOLORCURVES = true;
            }
            // Point size
            if (this.pointsCloud || scene.forcePointsCloud) {
                this._defines.POINTSIZE = true;
            }
            // Fog
            if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
                this._defines.FOG = true;
            }
            if (StandardMaterial.FresnelEnabled) {
                // Fresnel
                if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
                    this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
                    this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
                    this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
                    this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
                    if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
                        this._defines.DIFFUSEFRESNEL = true;
                    }
                    if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
                        this._defines.OPACITYFRESNEL = true;
                    }
                    if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
                        this._defines.REFLECTIONFRESNEL = true;
                        if (this.useReflectionFresnelFromSpecular) {
                            this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
                        }
                    }
                    if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
                        this._defines.REFRACTIONFRESNEL = true;
                    }
                    if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
                        this._defines.EMISSIVEFRESNEL = true;
                    }
                    needNormals = true;
                    this._defines.FRESNEL = true;
                }
            }
            if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
                this._defines.SPECULAROVERALPHA = true;
            }
            // Attribs
            if (mesh) {
                if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                    this._defines.NORMAL = true;
                }
                if (needUVs) {
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                        this._defines.UV1 = true;
                    }
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                        this._defines.UV2 = true;
                    }
                }
                if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                    this._defines.VERTEXCOLOR = true;
                    if (mesh.hasVertexAlpha) {
                        this._defines.VERTEXALPHA = true;
                    }
                }
                if (mesh.useBones && mesh.computeBonesUsingShaders) {
                    this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
                    this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
                }
                // Instances
                if (useInstances) {
                    this._defines.INSTANCES = true;
                }
            }
            // Get correct effect      
            if (!this._defines.isEqual(this._cachedDefines)) {
                this._defines.cloneTo(this._cachedDefines);
                scene.resetCachedMaterial();
                // Fallbacks
                var fallbacks = new BABYLON.EffectFallbacks();
                if (this._defines.REFLECTION) {
                    fallbacks.addFallback(0, "REFLECTION");
                }
                if (this._defines.SPECULAR) {
                    fallbacks.addFallback(0, "SPECULAR");
                }
                if (this._defines.BUMP) {
                    fallbacks.addFallback(0, "BUMP");
                }
                if (this._defines.PARALLAX) {
                    fallbacks.addFallback(1, "PARALLAX");
                }
                if (this._defines.PARALLAXOCCLUSION) {
                    fallbacks.addFallback(0, "PARALLAXOCCLUSION");
                }
                if (this._defines.SPECULAROVERALPHA) {
                    fallbacks.addFallback(0, "SPECULAROVERALPHA");
                }
                if (this._defines.FOG) {
                    fallbacks.addFallback(1, "FOG");
                }
                if (this._defines.POINTSIZE) {
                    fallbacks.addFallback(0, "POINTSIZE");
                }
                if (this._defines.LOGARITHMICDEPTH) {
                    fallbacks.addFallback(0, "LOGARITHMICDEPTH");
                }
                BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
                if (this._defines.SPECULARTERM) {
                    fallbacks.addFallback(0, "SPECULARTERM");
                }
                if (this._defines.DIFFUSEFRESNEL) {
                    fallbacks.addFallback(1, "DIFFUSEFRESNEL");
                }
                if (this._defines.OPACITYFRESNEL) {
                    fallbacks.addFallback(2, "OPACITYFRESNEL");
                }
                if (this._defines.REFLECTIONFRESNEL) {
                    fallbacks.addFallback(3, "REFLECTIONFRESNEL");
                }
                if (this._defines.EMISSIVEFRESNEL) {
                    fallbacks.addFallback(4, "EMISSIVEFRESNEL");
                }
                if (this._defines.FRESNEL) {
                    fallbacks.addFallback(4, "FRESNEL");
                }
                //Attributes
                var attribs = [BABYLON.VertexBuffer.PositionKind];
                if (this._defines.NORMAL) {
                    attribs.push(BABYLON.VertexBuffer.NormalKind);
                }
                if (this._defines.UV1) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                }
                if (this._defines.UV2) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (this._defines.VERTEXCOLOR) {
                    attribs.push(BABYLON.VertexBuffer.ColorKind);
                }
                BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
                BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
                var shaderName = "default";
                var join = this._defines.toString();
                var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
                    "vFogInfos", "vFogColor", "pointSize",
                    "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
                    "mBones",
                    "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
                    "depthValues",
                    "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
                    "logarithmicDepthConstant"
                ];
                var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
                if (this._defines.CAMERACOLORCURVES) {
                    BABYLON.ColorCurves.PrepareUniforms(uniforms);
                }
                if (this._defines.CAMERACOLORGRADING) {
                    BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
                }
                BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
                this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
            }
            if (!this._effect.isReady()) {
                return false;
            }
            this._renderId = scene.getRenderId();
            this._wasPreviouslyReady = true;
            if (mesh) {
                if (!mesh._materialDefines) {
                    mesh._materialDefines = new StandardMaterialDefines();
                }
                this._defines.cloneTo(mesh._materialDefines);
            }
            return true;
        };
        StandardMaterial.prototype.unbind = function () {
            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
                this._effect.setTexture("reflection2DSampler", null);
            }
            if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
                this._effect.setTexture("refraction2DSampler", null);
            }
            _super.prototype.unbind.call(this);
        };
        StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
            this._effect.setMatrix("world", world);
        };
        StandardMaterial.prototype.bind = function (world, mesh) {
            var scene = this.getScene();
            // Matrices        
            this.bindOnlyWorldMatrix(world);
            // Bones
            BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
            if (scene.getCachedMaterial() !== this) {
                this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
                if (StandardMaterial.FresnelEnabled) {
                    // Fresnel
                    if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
                        this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
                        this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
                    }
                    if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
                        this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
                    }
                    if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
                        this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
                        this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
                    }
                    if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
                        this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
                        this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
                    }
                    if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
                        this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
                        this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
                    }
                }
                // Textures     
                if (scene.texturesEnabled) {
                    if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
                        this._effect.setTexture("diffuseSampler", this.diffuseTexture);
                        this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
                        this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
                    }
                    if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
                        this._effect.setTexture("ambientSampler", this.ambientTexture);
                        this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
                        this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
                    }
                    if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
                        this._effect.setTexture("opacitySampler", this.opacityTexture);
                        this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
                        this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
                    }
                    if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
                        if (this.reflectionTexture.isCube) {
                            this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
                        }
                        else {
                            this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
                        }
                        this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
                        this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
                    }
                    if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
                        this._effect.setTexture("emissiveSampler", this.emissiveTexture);
                        this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
                        this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
                    }
                    if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
                        this._effect.setTexture("lightmapSampler", this.lightmapTexture);
                        this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
                        this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
                    }
                    if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
                        this._effect.setTexture("specularSampler", this.specularTexture);
                        this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
                        this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
                    }
                    if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
                        this._effect.setTexture("bumpSampler", this.bumpTexture);
                        this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
                        this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
                    }
                    if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
                        var depth = 1.0;
                        if (this.refractionTexture.isCube) {
                            this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
                        }
                        else {
                            this._effect.setTexture("refraction2DSampler", this.refractionTexture);
                            this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
                            if (this.refractionTexture.depth) {
                                depth = this.refractionTexture.depth;
                            }
                        }
                        this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
                    }
                    if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
                        BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
                    }
                }
                // Clip plane
                BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
                // Point size
                if (this.pointsCloud) {
                    this._effect.setFloat("pointSize", this.pointSize);
                }
                // Colors
                scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
                this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
                this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
                if (this._defines.SPECULARTERM) {
                    this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
                }
                this._effect.setColor3("vEmissiveColor", this.emissiveColor);
            }
            if (scene.getCachedMaterial() !== this || !this.isFrozen) {
                // Diffuse
                this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
                // Lights
                if (scene.lightsEnabled && !this.disableLighting) {
                    BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
                }
                // View
                if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
                    this._effect.setMatrix("view", scene.getViewMatrix());
                }
                // Fog
                BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
                // Log. depth
                BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
                // Color Curves
                if (this.cameraColorCurves) {
                    BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
                }
            }
            _super.prototype.bind.call(this, world, mesh);
        };
        StandardMaterial.prototype.getAnimatables = function () {
            var results = [];
            if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
                results.push(this.diffuseTexture);
            }
            if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
                results.push(this.ambientTexture);
            }
            if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
                results.push(this.opacityTexture);
            }
            if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
                results.push(this.reflectionTexture);
            }
            if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
                results.push(this.emissiveTexture);
            }
            if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
                results.push(this.specularTexture);
            }
            if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
                results.push(this.bumpTexture);
            }
            if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
                results.push(this.lightmapTexture);
            }
            if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
                results.push(this.refractionTexture);
            }
            if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
                results.push(this.cameraColorGradingTexture);
            }
            return results;
        };
        StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeTextures) {
                if (this.diffuseTexture) {
                    this.diffuseTexture.dispose();
                }
                if (this.ambientTexture) {
                    this.ambientTexture.dispose();
                }
                if (this.opacityTexture) {
                    this.opacityTexture.dispose();
                }
                if (this.reflectionTexture) {
                    this.reflectionTexture.dispose();
                }
                if (this.emissiveTexture) {
                    this.emissiveTexture.dispose();
                }
                if (this.specularTexture) {
                    this.specularTexture.dispose();
                }
                if (this.bumpTexture) {
                    this.bumpTexture.dispose();
                }
                if (this.lightmapTexture) {
                    this.lightmapTexture.dispose();
                }
                if (this.refractionTexture) {
                    this.refractionTexture.dispose();
                }
                if (this.cameraColorGradingTexture) {
                    this.cameraColorGradingTexture.dispose();
                }
            }
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        StandardMaterial.prototype.clone = function (name) {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
        };
        StandardMaterial.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        // Statics
        StandardMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        // Flags used to enable or disable a type of texture for all Standard Materials
        StandardMaterial.DiffuseTextureEnabled = true;
        StandardMaterial.AmbientTextureEnabled = true;
        StandardMaterial.OpacityTextureEnabled = true;
        StandardMaterial.ReflectionTextureEnabled = true;
        StandardMaterial.EmissiveTextureEnabled = true;
        StandardMaterial.SpecularTextureEnabled = true;
        StandardMaterial.BumpTextureEnabled = true;
        StandardMaterial.FresnelEnabled = true;
        StandardMaterial.LightmapTextureEnabled = true;
        StandardMaterial.RefractionTextureEnabled = true;
        StandardMaterial.ColorGradingTextureEnabled = true;
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "diffuseTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "ambientTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "opacityTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "reflectionTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "emissiveTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "specularTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "bumpTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "lightmapTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "refractionTexture", void 0);
        __decorate([
            BABYLON.serializeAsColor3("ambient")
        ], StandardMaterial.prototype, "ambientColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("diffuse")
        ], StandardMaterial.prototype, "diffuseColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("specular")
        ], StandardMaterial.prototype, "specularColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("emissive")
        ], StandardMaterial.prototype, "emissiveColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "specularPower", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "disableLighting", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useParallax", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "roughness", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "indexOfRefraction", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "invertRefractionY", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "invertNormalMapX", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "invertNormalMapY", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
        __decorate([
            BABYLON.serializeAsColorCurves()
        ], StandardMaterial.prototype, "cameraColorCurves", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useLogarithmicDepth", null);
        return StandardMaterial;
    }(BABYLON.Material));
    BABYLON.StandardMaterial = StandardMaterial;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.standardMaterial.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var MultiMaterial = (function (_super) {
        __extends(MultiMaterial, _super);
        function MultiMaterial(name, scene) {
            _super.call(this, name, scene, true);
            this.subMaterials = new Array();
            scene.multiMaterials.push(this);
        }
        // Properties
        MultiMaterial.prototype.getSubMaterial = function (index) {
            if (index < 0 || index >= this.subMaterials.length) {
                return this.getScene().defaultMaterial;
            }
            return this.subMaterials[index];
        };
        // Methods
        MultiMaterial.prototype.isReady = function (mesh) {
            for (var index = 0; index < this.subMaterials.length; index++) {
                var subMaterial = this.subMaterials[index];
                if (subMaterial) {
                    if (!this.subMaterials[index].isReady(mesh)) {
                        return false;
                    }
                }
            }
            return true;
        };
        MultiMaterial.prototype.clone = function (name, cloneChildren) {
            var newMultiMaterial = new MultiMaterial(name, this.getScene());
            for (var index = 0; index < this.subMaterials.length; index++) {
                var subMaterial = null;
                if (cloneChildren) {
                    subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
                }
                else {
                    subMaterial = this.subMaterials[index];
                }
                newMultiMaterial.subMaterials.push(subMaterial);
            }
            return newMultiMaterial;
        };
        MultiMaterial.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.id = this.id;
            serializationObject.tags = BABYLON.Tags.GetTags(this);
            serializationObject.materials = [];
            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
                var subMat = this.subMaterials[matIndex];
                if (subMat) {
                    serializationObject.materials.push(subMat.id);
                }
                else {
                    serializationObject.materials.push(null);
                }
            }
            return serializationObject;
        };
        return MultiMaterial;
    }(BABYLON.Material));
    BABYLON.MultiMaterial = MultiMaterial;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.multiMaterial.js.map
 
var BABYLON;
(function (BABYLON) {
    var SceneLoader = (function () {
        function SceneLoader() {
        }
        Object.defineProperty(SceneLoader, "NO_LOGGING", {
            get: function () {
                return 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
            get: function () {
                return 1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
            get: function () {
                return 2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
            get: function () {
                return 3;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
            get: function () {
                return SceneLoader._ForceFullSceneLoadingForIncremental;
            },
            set: function (value) {
                SceneLoader._ForceFullSceneLoadingForIncremental = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
            get: function () {
                return SceneLoader._ShowLoadingScreen;
            },
            set: function (value) {
                SceneLoader._ShowLoadingScreen = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "loggingLevel", {
            get: function () {
                return SceneLoader._loggingLevel;
            },
            set: function (value) {
                SceneLoader._loggingLevel = value;
            },
            enumerable: true,
            configurable: true
        });
        SceneLoader._getDefaultPlugin = function () {
            return SceneLoader._registeredPlugins[".babylon"];
        };
        SceneLoader._getPluginForExtension = function (extension) {
            var registeredPlugin = SceneLoader._registeredPlugins[extension];
            if (registeredPlugin) {
                return registeredPlugin;
            }
            return SceneLoader._getDefaultPlugin();
        };
        SceneLoader._getPluginForFilename = function (sceneFilename) {
            if (sceneFilename.name) {
                sceneFilename = sceneFilename.name;
            }
            var dotPosition = sceneFilename.lastIndexOf(".");
            var queryStringPosition = sceneFilename.indexOf("?");
            if (queryStringPosition === -1) {
                queryStringPosition = sceneFilename.length;
            }
            var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
            return SceneLoader._getPluginForExtension(extension);
        };
        // use babylon file loader directly if sceneFilename is prefixed with "data:"
        SceneLoader._getDirectLoad = function (sceneFilename) {
            if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
                return sceneFilename.substr(5);
            }
            return null;
        };
        // Public functions
        SceneLoader.GetPluginForExtension = function (extension) {
            return SceneLoader._getPluginForExtension(extension).plugin;
        };
        SceneLoader.RegisterPlugin = function (plugin) {
            if (typeof plugin.extensions === "string") {
                var extension = plugin.extensions;
                SceneLoader._registeredPlugins[extension.toLowerCase()] = {
                    plugin: plugin,
                    isBinary: false
                };
            }
            else {
                var extensions = plugin.extensions;
                Object.keys(extensions).forEach(function (extension) {
                    SceneLoader._registeredPlugins[extension.toLowerCase()] = {
                        plugin: plugin,
                        isBinary: extensions[extension].isBinary
                    };
                });
            }
        };
        SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
                BABYLON.Tools.Error("Wrong sceneFilename parameter");
                return;
            }
            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
                BABYLON.Tools.Error("Wrong sceneFilename parameter");
                return;
            }
            var directLoad = SceneLoader._getDirectLoad(sceneFilename);
            var loadingToken = {};
            scene._addPendingData(loadingToken);
            var manifestChecked = function (success) {
                scene.database = database;
                var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
                var plugin = registeredPlugin.plugin;
                var useArrayBuffer = registeredPlugin.isBinary;
                var importMeshFromData = function (data) {
                    var meshes = [];
                    var particleSystems = [];
                    var skeletons = [];
                    try {
                        if (plugin.importMesh) {
                            var syncedPlugin = plugin;
                            if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
                                if (onerror) {
                                    onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
                                }
                                scene._removePendingData(loadingToken);
                                return;
                            }
                            if (onsuccess) {
                                scene.importedMeshesFiles.push(rootUrl + sceneFilename);
                                onsuccess(meshes, particleSystems, skeletons);
                                scene._removePendingData(loadingToken);
                            }
                        }
                        else {
                            var asyncedPlugin = plugin;
                            asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
                                if (onsuccess) {
                                    scene.importedMeshesFiles.push(rootUrl + sceneFilename);
                                    onsuccess(meshes, particleSystems, skeletons);
                                    scene._removePendingData(loadingToken);
                                }
                            }, function () {
                                if (onerror) {
                                    onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
                                }
                                scene._removePendingData(loadingToken);
                            });
                        }
                    }
                    catch (e) {
                        if (onerror) {
                            onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
                        }
                        scene._removePendingData(loadingToken);
                    }
                };
                if (directLoad) {
                    importMeshFromData(directLoad);
                    return;
                }
                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
                    importMeshFromData(data);
                }, progressCallBack, database, useArrayBuffer);
            };
            if (scene.getEngine().enableOfflineSupport && !directLoad) {
                // Checking if a manifest file has been set for this scene and if offline mode has been requested
                var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
            }
            else {
                // If the scene is a data stream or offline support is not enabled, it's a direct load
                manifestChecked(true);
            }
        };
        /**
        * Load a scene
        * @param rootUrl a string that defines the root url for scene and resources
        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
        * @param engine is the instance of BABYLON.Engine to use to create the scene
        */
        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
            SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
        };
        /**
        * Append a scene
        * @param rootUrl a string that defines the root url for scene and resources
        * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
        * @param scene is the instance of BABYLON.Scene to append to
        */
        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
            if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
                BABYLON.Tools.Error("Wrong sceneFilename parameter");
                return;
            }
            var directLoad = SceneLoader._getDirectLoad(sceneFilename);
            var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
            var plugin = registeredPlugin.plugin;
            var useArrayBuffer = registeredPlugin.isBinary;
            var database;
            var loadingToken = {};
            scene._addPendingData(loadingToken);
            if (SceneLoader.ShowLoadingScreen) {
                scene.getEngine().displayLoadingUI();
            }
            var loadSceneFromData = function (data) {
                scene.database = database;
                if (plugin.load) {
                    var syncedPlugin = plugin;
                    if (!syncedPlugin.load(scene, data, rootUrl)) {
                        if (onerror) {
                            onerror(scene);
                        }
                        scene._removePendingData(loadingToken);
                        scene.getEngine().hideLoadingUI();
                        return;
                    }
                    if (onsuccess) {
                        onsuccess(scene);
                    }
                    scene._removePendingData(loadingToken);
                }
                else {
                    var asyncedPlugin = plugin;
                    asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
                        if (onsuccess) {
                            onsuccess(scene);
                        }
                        scene._removePendingData(loadingToken);
                    }, function () {
                        if (onerror) {
                            onerror(scene);
                        }
                        scene._removePendingData(loadingToken);
                        scene.getEngine().hideLoadingUI();
                    });
                }
                if (SceneLoader.ShowLoadingScreen) {
                    scene.executeWhenReady(function () {
                        scene.getEngine().hideLoadingUI();
                    });
                }
            };
            var manifestChecked = function (success) {
                BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
            };
            if (directLoad) {
                loadSceneFromData(directLoad);
                return;
            }
            if (rootUrl.indexOf("file:") === -1) {
                if (scene.getEngine().enableOfflineSupport) {
                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
                    database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
                }
                else {
                    manifestChecked(true);
                }
            }
            else {
                BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
            }
        };
        // Flags
        SceneLoader._ForceFullSceneLoadingForIncremental = false;
        SceneLoader._ShowLoadingScreen = true;
        SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
        // Members
        SceneLoader._registeredPlugins = {};
        return SceneLoader;
    }());
    BABYLON.SceneLoader = SceneLoader;
    ;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.sceneLoader.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var parseMaterialById = function (id, parsedData, scene, rootUrl) {
            for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
                var parsedMaterial = parsedData.materials[index];
                if (parsedMaterial.id === id) {
                    return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
                }
            }
            return null;
        };
        var isDescendantOf = function (mesh, names, hierarchyIds) {
            names = (names instanceof Array) ? names : [names];
            for (var i in names) {
                if (mesh.name === names[i]) {
                    hierarchyIds.push(mesh.id);
                    return true;
                }
            }
            if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
                hierarchyIds.push(mesh.id);
                return true;
            }
            return false;
        };
        var logOperation = function (operation, producer) {
            return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
        };
        BABYLON.SceneLoader.RegisterPlugin({
            extensions: ".babylon",
            importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
                // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
                // when SceneLoader.debugLogging = true (default), or exception encountered.
                // Everything stored in var log instead of writing separate lines to support only writing in exception,
                // and avoid problems with multiple concurrent .babylon loads.
                var log = "importMesh has failed JSON parse";
                try {
                    var parsedData = JSON.parse(data);
                    log = "";
                    var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
                    var loadedSkeletonsIds = [];
                    var loadedMaterialsIds = [];
                    var hierarchyIds = [];
                    var index;
                    var cache;
                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
                        var parsedMesh = parsedData.meshes[index];
                        if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
                            if (meshesNames instanceof Array) {
                                // Remove found mesh name from list.
                                delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
                            }
                            //Geometry?
                            if (parsedMesh.geometryId) {
                                //does the file contain geometries?
                                if (parsedData.geometries) {
                                    //find the correct geometry and add it to the scene
                                    var found = false;
                                    ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
                                        if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
                                            return;
                                        }
                                        else {
                                            parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
                                                if (parsedGeometryData.id === parsedMesh.geometryId) {
                                                    switch (geometryType) {
                                                        case "boxes":
                                                            BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "spheres":
                                                            BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "cylinders":
                                                            BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "toruses":
                                                            BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "grounds":
                                                            BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "planes":
                                                            BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "torusKnots":
                                                            BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "vertexData":
                                                            BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
                                                            break;
                                                    }
                                                    found = true;
                                                }
                                            });
                                        }
                                    });
                                    if (!found) {
                                        BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
                                    }
                                }
                            }
                            // Material ?
                            if (parsedMesh.materialId) {
                                var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
                                if (!materialFound && parsedData.multiMaterials) {
                                    for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
                                        var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
                                        if (parsedMultiMaterial.id === parsedMesh.materialId) {
                                            for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
                                                var subMatId = parsedMultiMaterial.materials[matIndex];
                                                loadedMaterialsIds.push(subMatId);
                                                var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
                                                log += "\n\tMaterial " + mat.toString(fullDetails);
                                            }
                                            loadedMaterialsIds.push(parsedMultiMaterial.id);
                                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
                                            materialFound = true;
                                            log += "\n\tMulti-Material " + mmat.toString(fullDetails);
                                            break;
                                        }
                                    }
                                }
                                if (!materialFound) {
                                    loadedMaterialsIds.push(parsedMesh.materialId);
                                    var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
                                    if (!mat) {
                                        BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
                                    }
                                    else {
                                        log += "\n\tMaterial " + mat.toString(fullDetails);
                                    }
                                }
                            }
                            // Skeleton ?
                            if (parsedMesh.skeletonId > -1 && scene.skeletons) {
                                var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
                                if (!skeletonAlreadyLoaded) {
                                    for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
                                        var parsedSkeleton = parsedData.skeletons[skeletonIndex];
                                        if (parsedSkeleton.id === parsedMesh.skeletonId) {
                                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
                                            skeletons.push(skeleton);
                                            loadedSkeletonsIds.push(parsedSkeleton.id);
                                            log += "\n\tSkeleton " + skeleton.toString(fullDetails);
                                        }
                                    }
                                }
                            }
                            var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
                            meshes.push(mesh);
                            log += "\n\tMesh " + mesh.toString(fullDetails);
                        }
                    }
                    // Connecting parents
                    var currentMesh;
                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                        currentMesh = scene.meshes[index];
                        if (currentMesh._waitingParentId) {
                            currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
                            currentMesh._waitingParentId = undefined;
                        }
                    }
                    // freeze and compute world matrix application
                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                        currentMesh = scene.meshes[index];
                        if (currentMesh._waitingFreezeWorldMatrix) {
                            currentMesh.freezeWorldMatrix();
                            currentMesh._waitingFreezeWorldMatrix = undefined;
                        }
                        else {
                            currentMesh.computeWorldMatrix(true);
                        }
                    }
                    // Particles
                    if (parsedData.particleSystems) {
                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
                            var parsedParticleSystem = parsedData.particleSystems[index];
                            if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
                                particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
                            }
                        }
                    }
                    return true;
                }
                catch (err) {
                    BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
                    log = null;
                    throw err;
                }
                finally {
                    if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
                        BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
                    }
                }
            },
            load: function (scene, data, rootUrl) {
                // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
                // when SceneLoader.debugLogging = true (default), or exception encountered.
                // Everything stored in var log instead of writing separate lines to support only writing in exception,
                // and avoid problems with multiple concurrent .babylon loads.
                var log = "importScene has failed JSON parse";
                try {
                    var parsedData = JSON.parse(data);
                    log = "";
                    var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
                    // Scene
                    scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
                    scene.autoClear = parsedData.autoClear;
                    scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
                    scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
                    if (parsedData.gravity) {
                        scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
                    }
                    // Fog
                    if (parsedData.fogMode && parsedData.fogMode !== 0) {
                        scene.fogMode = parsedData.fogMode;
                        scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
                        scene.fogStart = parsedData.fogStart;
                        scene.fogEnd = parsedData.fogEnd;
                        scene.fogDensity = parsedData.fogDensity;
                        log += "\tFog mode for scene:  ";
                        switch (scene.fogMode) {
                            // getters not compiling, so using hardcoded
                            case 1:
                                log += "exp\n";
                                break;
                            case 2:
                                log += "exp2\n";
                                break;
                            case 3:
                                log += "linear\n";
                                break;
                        }
                    }
                    //Physics
                    if (parsedData.physicsEnabled) {
                        var physicsPlugin;
                        if (parsedData.physicsEngine === "cannon") {
                            physicsPlugin = new BABYLON.CannonJSPlugin();
                        }
                        else if (parsedData.physicsEngine === "oimo") {
                            physicsPlugin = new BABYLON.OimoJSPlugin();
                        }
                        log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
                        //else - default engine, which is currently oimo
                        var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
                        scene.enablePhysics(physicsGravity, physicsPlugin);
                    }
                    // Metadata
                    if (parsedData.metadata !== undefined) {
                        scene.metadata = parsedData.metadata;
                    }
                    //collisions, if defined. otherwise, default is true
                    if (parsedData.collisionsEnabled != undefined) {
                        scene.collisionsEnabled = parsedData.collisionsEnabled;
                    }
                    scene.workerCollisions = !!parsedData.workerCollisions;
                    var index;
                    var cache;
                    // Lights
                    for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
                        var parsedLight = parsedData.lights[index];
                        var light = BABYLON.Light.Parse(parsedLight, scene);
                        log += (index === 0 ? "\n\tLights:" : "");
                        log += "\n\t\t" + light.toString(fullDetails);
                    }
                    // Animations
                    if (parsedData.animations) {
                        for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
                            var parsedAnimation = parsedData.animations[index];
                            var animation = BABYLON.Animation.Parse(parsedAnimation);
                            scene.animations.push(animation);
                            log += (index === 0 ? "\n\tAnimations:" : "");
                            log += "\n\t\t" + animation.toString(fullDetails);
                        }
                    }
                    if (parsedData.autoAnimate) {
                        scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
                    }
                    // Materials
                    if (parsedData.materials) {
                        for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
                            var parsedMaterial = parsedData.materials[index];
                            var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
                            log += (index === 0 ? "\n\tMaterials:" : "");
                            log += "\n\t\t" + mat.toString(fullDetails);
                        }
                    }
                    if (parsedData.multiMaterials) {
                        for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
                            var parsedMultiMaterial = parsedData.multiMaterials[index];
                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
                            log += (index === 0 ? "\n\tMultiMaterials:" : "");
                            log += "\n\t\t" + mmat.toString(fullDetails);
                        }
                    }
                    // Skeletons
                    if (parsedData.skeletons) {
                        for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
                            var parsedSkeleton = parsedData.skeletons[index];
                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
                            log += (index === 0 ? "\n\tSkeletons:" : "");
                            log += "\n\t\t" + skeleton.toString(fullDetails);
                        }
                    }
                    // Geometries
                    var geometries = parsedData.geometries;
                    if (geometries) {
                        // Boxes
                        var boxes = geometries.boxes;
                        if (boxes) {
                            for (index = 0, cache = boxes.length; index < cache; index++) {
                                var parsedBox = boxes[index];
                                BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
                            }
                        }
                        // Spheres
                        var spheres = geometries.spheres;
                        if (spheres) {
                            for (index = 0, cache = spheres.length; index < cache; index++) {
                                var parsedSphere = spheres[index];
                                BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
                            }
                        }
                        // Cylinders
                        var cylinders = geometries.cylinders;
                        if (cylinders) {
                            for (index = 0, cache = cylinders.length; index < cache; index++) {
                                var parsedCylinder = cylinders[index];
                                BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
                            }
                        }
                        // Toruses
                        var toruses = geometries.toruses;
                        if (toruses) {
                            for (index = 0, cache = toruses.length; index < cache; index++) {
                                var parsedTorus = toruses[index];
                                BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
                            }
                        }
                        // Grounds
                        var grounds = geometries.grounds;
                        if (grounds) {
                            for (index = 0, cache = grounds.length; index < cache; index++) {
                                var parsedGround = grounds[index];
                                BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
                            }
                        }
                        // Planes
                        var planes = geometries.planes;
                        if (planes) {
                            for (index = 0, cache = planes.length; index < cache; index++) {
                                var parsedPlane = planes[index];
                                BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
                            }
                        }
                        // TorusKnots
                        var torusKnots = geometries.torusKnots;
                        if (torusKnots) {
                            for (index = 0, cache = torusKnots.length; index < cache; index++) {
                                var parsedTorusKnot = torusKnots[index];
                                BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
                            }
                        }
                        // VertexData
                        var vertexData = geometries.vertexData;
                        if (vertexData) {
                            for (index = 0, cache = vertexData.length; index < cache; index++) {
                                var parsedVertexData = vertexData[index];
                                BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
                            }
                        }
                    }
                    // Meshes
                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
                        var parsedMesh = parsedData.meshes[index];
                        var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
                        log += (index === 0 ? "\n\tMeshes:" : "");
                        log += "\n\t\t" + mesh.toString(fullDetails);
                    }
                    // Cameras
                    for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
                        var parsedCamera = parsedData.cameras[index];
                        var camera = BABYLON.Camera.Parse(parsedCamera, scene);
                        log += (index === 0 ? "\n\tCameras:" : "");
                        log += "\n\t\t" + camera.toString(fullDetails);
                    }
                    if (parsedData.activeCameraID) {
                        scene.setActiveCameraByID(parsedData.activeCameraID);
                    }
                    // Browsing all the graph to connect the dots
                    for (index = 0, cache = scene.cameras.length; index < cache; index++) {
                        var camera = scene.cameras[index];
                        if (camera._waitingParentId) {
                            camera.parent = scene.getLastEntryByID(camera._waitingParentId);
                            camera._waitingParentId = undefined;
                        }
                    }
                    for (index = 0, cache = scene.lights.length; index < cache; index++) {
                        var light = scene.lights[index];
                        if (light._waitingParentId) {
                            light.parent = scene.getLastEntryByID(light._waitingParentId);
                            light._waitingParentId = undefined;
                        }
                    }
                    // Sounds
                    var loadedSounds = [];
                    var loadedSound;
                    if (BABYLON.AudioEngine && parsedData.sounds) {
                        for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
                            var parsedSound = parsedData.sounds[index];
                            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                                if (!parsedSound.url)
                                    parsedSound.url = parsedSound.name;
                                if (!loadedSounds[parsedSound.url]) {
                                    loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
                                    loadedSounds[parsedSound.url] = loadedSound;
                                }
                                else {
                                    BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
                                }
                            }
                            else {
                                var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
                            }
                        }
                    }
                    loadedSounds = [];
                    // Connect parents & children and parse actions
                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                        var mesh = scene.meshes[index];
                        if (mesh._waitingParentId) {
                            mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
                            mesh._waitingParentId = undefined;
                        }
                        if (mesh._waitingActions) {
                            BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
                            mesh._waitingActions = undefined;
                        }
                    }
                    // freeze world matrix application
                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                        var currentMesh = scene.meshes[index];
                        if (currentMesh._waitingFreezeWorldMatrix) {
                            currentMesh.freezeWorldMatrix();
                            currentMesh._waitingFreezeWorldMatrix = undefined;
                        }
                        else {
                            currentMesh.computeWorldMatrix(true);
                        }
                    }
                    // Particles Systems
                    if (parsedData.particleSystems) {
                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
                            var parsedParticleSystem = parsedData.particleSystems[index];
                            BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
                        }
                    }
                    // Lens flares
                    if (parsedData.lensFlareSystems) {
                        for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
                            var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
                            BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
                        }
                    }
                    // Shadows
                    if (parsedData.shadowGenerators) {
                        for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
                            var parsedShadowGenerator = parsedData.shadowGenerators[index];
                            BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
                        }
                    }
                    // Actions (scene)
                    if (parsedData.actions) {
                        BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
                    }
                    // Finish
                    return true;
                }
                catch (err) {
                    BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
                    log = null;
                    throw err;
                }
                finally {
                    if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
                        BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
                    }
                }
            }
        });
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.babylonFileLoader.js.map
 
var BABYLON;
(function (BABYLON) {
    var SpriteManager = (function () {
        function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
            if (epsilon === void 0) { epsilon = 0.01; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            this.name = name;
            this.sprites = new Array();
            this.renderingGroupId = 0;
            this.layerMask = 0x0FFFFFFF;
            this.fogEnabled = true;
            this.isPickable = false;
            /**
            * An event triggered when the manager is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            this._vertexBuffers = {};
            this._capacity = capacity;
            this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
            this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            if (cellSize.width && cellSize.height) {
                this.cellWidth = cellSize.width;
                this.cellHeight = cellSize.height;
            }
            else if (cellSize !== undefined) {
                this.cellWidth = cellSize;
                this.cellHeight = cellSize;
            }
            else {
                return;
            }
            this._epsilon = epsilon;
            this._scene = scene;
            this._scene.spriteManagers.push(this);
            var indices = [];
            var index = 0;
            for (var count = 0; count < capacity; count++) {
                indices.push(index);
                indices.push(index + 1);
                indices.push(index + 2);
                indices.push(index);
                indices.push(index + 2);
                indices.push(index + 3);
                index += 4;
            }
            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
            // VBO
            // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
            this._vertexData = new Float32Array(capacity * 16 * 4);
            this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
            var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
            var options = this._buffer.createVertexBuffer("options", 4, 4);
            var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
            var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
            this._vertexBuffers["options"] = options;
            this._vertexBuffers["cellInfo"] = cellInfo;
            this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
            // Effects
            this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
            this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
        }
        Object.defineProperty(SpriteManager.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpriteManager.prototype, "texture", {
            get: function () {
                return this._spriteTexture;
            },
            set: function (value) {
                this._spriteTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
            var arrayOffset = index * 16;
            if (offsetX === 0)
                offsetX = this._epsilon;
            else if (offsetX === 1)
                offsetX = 1 - this._epsilon;
            if (offsetY === 0)
                offsetY = this._epsilon;
            else if (offsetY === 1)
                offsetY = 1 - this._epsilon;
            this._vertexData[arrayOffset] = sprite.position.x;
            this._vertexData[arrayOffset + 1] = sprite.position.y;
            this._vertexData[arrayOffset + 2] = sprite.position.z;
            this._vertexData[arrayOffset + 3] = sprite.angle;
            this._vertexData[arrayOffset + 4] = sprite.width;
            this._vertexData[arrayOffset + 5] = sprite.height;
            this._vertexData[arrayOffset + 6] = offsetX;
            this._vertexData[arrayOffset + 7] = offsetY;
            this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
            this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
            var offset = (sprite.cellIndex / rowSize) >> 0;
            this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
            this._vertexData[arrayOffset + 11] = offset;
            // Color
            this._vertexData[arrayOffset + 12] = sprite.color.r;
            this._vertexData[arrayOffset + 13] = sprite.color.g;
            this._vertexData[arrayOffset + 14] = sprite.color.b;
            this._vertexData[arrayOffset + 15] = sprite.color.a;
        };
        SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
            var count = Math.min(this._capacity, this.sprites.length);
            var min = BABYLON.Vector3.Zero();
            var max = BABYLON.Vector3.Zero();
            var distance = Number.MAX_VALUE;
            var currentSprite;
            var cameraSpacePosition = BABYLON.Vector3.Zero();
            var cameraView = camera.getViewMatrix();
            for (var index = 0; index < count; index++) {
                var sprite = this.sprites[index];
                if (!sprite) {
                    continue;
                }
                if (predicate) {
                    if (!predicate(sprite)) {
                        continue;
                    }
                }
                else if (!sprite.isPickable) {
                    continue;
                }
                BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
                min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
                max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
                if (ray.intersectsBoxMinMax(min, max)) {
                    var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
                    if (distance > currentDistance) {
                        distance = currentDistance;
                        currentSprite = sprite;
                        if (fastCheck) {
                            break;
                        }
                    }
                }
            }
            if (currentSprite) {
                var result = new BABYLON.PickingInfo();
                result.hit = true;
                result.pickedSprite = currentSprite;
                result.distance = distance;
                return result;
            }
            return null;
        };
        SpriteManager.prototype.render = function () {
            // Check
            if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
                return;
            var engine = this._scene.getEngine();
            var baseSize = this._spriteTexture.getBaseSize();
            // Sprites
            var deltaTime = engine.getDeltaTime();
            var max = Math.min(this._capacity, this.sprites.length);
            var rowSize = baseSize.width / this.cellWidth;
            var offset = 0;
            for (var index = 0; index < max; index++) {
                var sprite = this.sprites[index];
                if (!sprite) {
                    continue;
                }
                sprite._animate(deltaTime);
                this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
                this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
                this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
                this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
            }
            this._buffer.update(this._vertexData);
            // Render
            var effect = this._effectBase;
            if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
                effect = this._effectFog;
            }
            engine.enableEffect(effect);
            var viewMatrix = this._scene.getViewMatrix();
            effect.setTexture("diffuseSampler", this._spriteTexture);
            effect.setMatrix("view", viewMatrix);
            effect.setMatrix("projection", this._scene.getProjectionMatrix());
            effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
            // Fog
            if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
                effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
                effect.setColor3("vFogColor", this._scene.fogColor);
            }
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
            // Draw order
            engine.setDepthFunctionToLessOrEqual();
            effect.setBool("alphaTest", true);
            engine.setColorWrite(false);
            engine.draw(true, 0, max * 6);
            engine.setColorWrite(true);
            effect.setBool("alphaTest", false);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
            engine.draw(true, 0, max * 6);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
        };
        SpriteManager.prototype.dispose = function () {
            if (this._buffer) {
                this._buffer.dispose();
                this._buffer = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            if (this._spriteTexture) {
                this._spriteTexture.dispose();
                this._spriteTexture = null;
            }
            // Remove from scene
            var index = this._scene.spriteManagers.indexOf(this);
            this._scene.spriteManagers.splice(index, 1);
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        return SpriteManager;
    }());
    BABYLON.SpriteManager = SpriteManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.spriteManager.js.map
 
var BABYLON;
(function (BABYLON) {
    var Sprite = (function () {
        function Sprite(name, manager) {
            this.name = name;
            this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            this.width = 1.0;
            this.height = 1.0;
            this.angle = 0;
            this.cellIndex = 0;
            this.invertU = 0;
            this.invertV = 0;
            this.animations = new Array();
            this.isPickable = false;
            this._animationStarted = false;
            this._loopAnimation = false;
            this._fromIndex = 0;
            this._toIndex = 0;
            this._delay = 0;
            this._direction = 1;
            this._frameCount = 0;
            this._time = 0;
            this._manager = manager;
            this._manager.sprites.push(this);
            this.position = BABYLON.Vector3.Zero();
        }
        Object.defineProperty(Sprite.prototype, "size", {
            get: function () {
                return this.width;
            },
            set: function (value) {
                this.width = value;
                this.height = value;
            },
            enumerable: true,
            configurable: true
        });
        Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
            this._fromIndex = from;
            this._toIndex = to;
            this._loopAnimation = loop;
            this._delay = delay;
            this._animationStarted = true;
            this._direction = from < to ? 1 : -1;
            this.cellIndex = from;
            this._time = 0;
            this._onAnimationEnd = onAnimationEnd;
        };
        Sprite.prototype.stopAnimation = function () {
            this._animationStarted = false;
        };
        Sprite.prototype._animate = function (deltaTime) {
            if (!this._animationStarted)
                return;
            this._time += deltaTime;
            if (this._time > this._delay) {
                this._time = this._time % this._delay;
                this.cellIndex += this._direction;
                if (this.cellIndex === this._toIndex) {
                    if (this._loopAnimation) {
                        this.cellIndex = this._fromIndex;
                    }
                    else {
                        this._animationStarted = false;
                        if (this._onAnimationEnd) {
                            this._onAnimationEnd();
                        }
                        if (this.disposeWhenFinishedAnimating) {
                            this.dispose();
                        }
                    }
                }
            }
        };
        Sprite.prototype.dispose = function () {
            for (var i = 0; i < this._manager.sprites.length; i++) {
                if (this._manager.sprites[i] == this) {
                    this._manager.sprites.splice(i, 1);
                }
            }
        };
        return Sprite;
    }());
    BABYLON.Sprite = Sprite;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.sprite.js.map
 
var BABYLON;
(function (BABYLON) {
    var Layer = (function () {
        function Layer(name, imgUrl, scene, isBackground, color) {
            this.name = name;
            this.scale = new BABYLON.Vector2(1, 1);
            this.offset = new BABYLON.Vector2(0, 0);
            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
            this._vertexBuffers = {};
            // Events
            /**
            * An event triggered when the layer is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the scene
            * @type {BABYLON.Observable}
            */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the scene
            * @type {BABYLON.Observable}
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
            this.isBackground = isBackground === undefined ? true : isBackground;
            this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
            this._scene = scene;
            this._scene.layers.push(this);
            var engine = scene.getEngine();
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
            // Effects
            this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
            this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
        }
        Object.defineProperty(Layer.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Layer.prototype, "onBeforeRender", {
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Layer.prototype, "onAfterRender", {
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Layer.prototype.render = function () {
            var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
            // Check
            if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
                return;
            var engine = this._scene.getEngine();
            this.onBeforeRenderObservable.notifyObservers(this);
            // Render
            engine.enableEffect(currentEffect);
            engine.setState(false);
            // Texture
            currentEffect.setTexture("textureSampler", this.texture);
            currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
            // Color
            currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
            // Scale / offset
            currentEffect.setVector2("offset", this.offset);
            currentEffect.setVector2("scale", this.scale);
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
            // Draw order
            if (!this.alphaTest) {
                engine.setAlphaMode(this.alphaBlendingMode);
                engine.draw(true, 0, 6);
                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            }
            else {
                engine.draw(true, 0, 6);
            }
            this.onAfterRenderObservable.notifyObservers(this);
        };
        Layer.prototype.dispose = function () {
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            if (this.texture) {
                this.texture.dispose();
                this.texture = null;
            }
            // Remove from scene
            var index = this._scene.layers.indexOf(this);
            this._scene.layers.splice(index, 1);
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onAfterRenderObservable.clear();
            this.onBeforeRenderObservable.clear();
        };
        return Layer;
    }());
    BABYLON.Layer = Layer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.layer.js.map
 
var BABYLON;
(function (BABYLON) {
    var Particle = (function () {
        function Particle() {
            this.position = BABYLON.Vector3.Zero();
            this.direction = BABYLON.Vector3.Zero();
            this.color = new BABYLON.Color4(0, 0, 0, 0);
            this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
            this.lifeTime = 1.0;
            this.age = 0;
            this.size = 0;
            this.angle = 0;
            this.angularSpeed = 0;
        }
        Particle.prototype.copyTo = function (other) {
            other.position.copyFrom(this.position);
            other.direction.copyFrom(this.direction);
            other.color.copyFrom(this.color);
            other.colorStep.copyFrom(this.colorStep);
            other.lifeTime = this.lifeTime;
            other.age = this.age;
            other.size = this.size;
            other.angle = this.angle;
            other.angularSpeed = this.angularSpeed;
        };
        return Particle;
    }());
    BABYLON.Particle = Particle;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.particle.js.map
 
var BABYLON;
(function (BABYLON) {
    var randomNumber = function (min, max) {
        if (min === max) {
            return (min);
        }
        var random = Math.random();
        return ((random * (max - min)) + min);
    };
    var ParticleSystem = (function () {
        function ParticleSystem(name, capacity, scene, customEffect) {
            var _this = this;
            this.name = name;
            // Members
            this.animations = [];
            this.renderingGroupId = 0;
            this.emitter = null;
            this.emitRate = 10;
            this.manualEmitCount = -1;
            this.updateSpeed = 0.01;
            this.targetStopDuration = 0;
            this.disposeOnStop = false;
            this.minEmitPower = 1;
            this.maxEmitPower = 1;
            this.minLifeTime = 1;
            this.maxLifeTime = 1;
            this.minSize = 1;
            this.maxSize = 1;
            this.minAngularSpeed = 0;
            this.maxAngularSpeed = 0;
            this.layerMask = 0x0FFFFFFF;
            /**
            * An event triggered when the system is disposed.
            * @type {BABYLON.Observable}
            */
            this.onDisposeObservable = new BABYLON.Observable();
            this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
            this.forceDepthWrite = false;
            this.gravity = BABYLON.Vector3.Zero();
            this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
            this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
            this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
            this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
            this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
            this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            this.particles = new Array();
            this._stockParticles = new Array();
            this._newPartsExcess = 0;
            this._vertexBuffers = {};
            this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
            this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
            this._scaledDirection = BABYLON.Vector3.Zero();
            this._scaledGravity = BABYLON.Vector3.Zero();
            this._currentRenderId = -1;
            this._started = false;
            this._stopped = false;
            this._actualFrame = 0;
            this.id = name;
            this._capacity = capacity;
            this._scene = scene;
            this._customEffect = customEffect;
            scene.particleSystems.push(this);
            var indices = [];
            var index = 0;
            for (var count = 0; count < capacity; count++) {
                indices.push(index);
                indices.push(index + 1);
                indices.push(index + 2);
                indices.push(index);
                indices.push(index + 2);
                indices.push(index + 3);
                index += 4;
            }
            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
            // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
            this._vertexData = new Float32Array(capacity * 11 * 4);
            this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
            var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
            var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
            var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
            this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
            this._vertexBuffers["options"] = options;
            // Default behaviors
            this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
                var randX = randomNumber(_this.direction1.x, _this.direction2.x);
                var randY = randomNumber(_this.direction1.y, _this.direction2.y);
                var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
                BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
            };
            this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
                var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
                var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
                var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
            };
            this.updateFunction = function (particles) {
                for (var index = 0; index < particles.length; index++) {
                    var particle = particles[index];
                    particle.age += _this._scaledUpdateSpeed;
                    if (particle.age >= particle.lifeTime) {
                        _this.recycleParticle(particle);
                        index--;
                        continue;
                    }
                    else {
                        particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
                        particle.color.addInPlace(_this._scaledColorStep);
                        if (particle.color.a < 0)
                            particle.color.a = 0;
                        particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
                        particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
                        particle.position.addInPlace(_this._scaledDirection);
                        _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
                        particle.direction.addInPlace(_this._scaledGravity);
                    }
                }
            };
        }
        Object.defineProperty(ParticleSystem.prototype, "onDispose", {
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        ParticleSystem.prototype.recycleParticle = function (particle) {
            var lastParticle = this.particles.pop();
            if (lastParticle !== particle) {
                lastParticle.copyTo(particle);
                this._stockParticles.push(lastParticle);
            }
        };
        ParticleSystem.prototype.getCapacity = function () {
            return this._capacity;
        };
        ParticleSystem.prototype.isAlive = function () {
            return this._alive;
        };
        ParticleSystem.prototype.isStarted = function () {
            return this._started;
        };
        ParticleSystem.prototype.start = function () {
            this._started = true;
            this._stopped = false;
            this._actualFrame = 0;
        };
        ParticleSystem.prototype.stop = function () {
            this._stopped = true;
        };
        ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
            var offset = index * 11;
            this._vertexData[offset] = particle.position.x;
            this._vertexData[offset + 1] = particle.position.y;
            this._vertexData[offset + 2] = particle.position.z;
            this._vertexData[offset + 3] = particle.color.r;
            this._vertexData[offset + 4] = particle.color.g;
            this._vertexData[offset + 5] = particle.color.b;
            this._vertexData[offset + 6] = particle.color.a;
            this._vertexData[offset + 7] = particle.angle;
            this._vertexData[offset + 8] = particle.size;
            this._vertexData[offset + 9] = offsetX;
            this._vertexData[offset + 10] = offsetY;
        };
        ParticleSystem.prototype._update = function (newParticles) {
            // Update current
            this._alive = this.particles.length > 0;
            this.updateFunction(this.particles);
            // Add new ones
            var worldMatrix;
            if (this.emitter.position) {
                worldMatrix = this.emitter.getWorldMatrix();
            }
            else {
                worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
            }
            var particle;
            for (var index = 0; index < newParticles; index++) {
                if (this.particles.length === this._capacity) {
                    break;
                }
                if (this._stockParticles.length !== 0) {
                    particle = this._stockParticles.pop();
                    particle.age = 0;
                }
                else {
                    particle = new BABYLON.Particle();
                }
                this.particles.push(particle);
                var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
                this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
                particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
                particle.size = randomNumber(this.minSize, this.maxSize);
                particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
                this.startPositionFunction(worldMatrix, particle.position, particle);
                var step = randomNumber(0, 1.0);
                BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
                this.colorDead.subtractToRef(particle.color, this._colorDiff);
                this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
            }
        };
        ParticleSystem.prototype._getEffect = function () {
            if (this._customEffect) {
                return this._customEffect;
            }
            ;
            var defines = [];
            if (this._scene.clipPlane) {
                defines.push("#define CLIPPLANE");
            }
            // Effect
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
            }
            return this._effect;
        };
        ParticleSystem.prototype.animate = function () {
            if (!this._started)
                return;
            var effect = this._getEffect();
            // Check
            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
                return;
            if (this._currentRenderId === this._scene.getRenderId()) {
                return;
            }
            this._currentRenderId = this._scene.getRenderId();
            this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
            // determine the number of particles we need to create   
            var newParticles;
            if (this.manualEmitCount > -1) {
                newParticles = this.manualEmitCount;
                this._newPartsExcess = 0;
                this.manualEmitCount = 0;
            }
            else {
                newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
                this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
            }
            if (this._newPartsExcess > 1.0) {
                newParticles += this._newPartsExcess >> 0;
                this._newPartsExcess -= this._newPartsExcess >> 0;
            }
            this._alive = false;
            if (!this._stopped) {
                this._actualFrame += this._scaledUpdateSpeed;
                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
                    this.stop();
            }
            else {
                newParticles = 0;
            }
            this._update(newParticles);
            // Stopped?
            if (this._stopped) {
                if (!this._alive) {
                    this._started = false;
                    if (this.disposeOnStop) {
                        this._scene._toBeDisposed.push(this);
                    }
                }
            }
            // Update VBO
            var offset = 0;
            for (var index = 0; index < this.particles.length; index++) {
                var particle = this.particles[index];
                this._appendParticleVertex(offset++, particle, 0, 0);
                this._appendParticleVertex(offset++, particle, 1, 0);
                this._appendParticleVertex(offset++, particle, 1, 1);
                this._appendParticleVertex(offset++, particle, 0, 1);
            }
            this._vertexBuffer.update(this._vertexData);
        };
        ParticleSystem.prototype.render = function () {
            var effect = this._getEffect();
            // Check
            if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
                return 0;
            var engine = this._scene.getEngine();
            // Render
            engine.enableEffect(effect);
            engine.setState(false);
            var viewMatrix = this._scene.getViewMatrix();
            effect.setTexture("diffuseSampler", this.particleTexture);
            effect.setMatrix("view", viewMatrix);
            effect.setMatrix("projection", this._scene.getProjectionMatrix());
            effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
            if (this._scene.clipPlane) {
                var clipPlane = this._scene.clipPlane;
                var invView = viewMatrix.clone();
                invView.invert();
                effect.setMatrix("invView", invView);
                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
            }
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
            // Draw order
            if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
                engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
            }
            else {
                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
            }
            if (this.forceDepthWrite) {
                engine.setDepthWrite(true);
            }
            engine.draw(true, 0, this.particles.length * 6);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            return this.particles.length;
        };
        ParticleSystem.prototype.dispose = function () {
            if (this._vertexBuffer) {
                this._vertexBuffer.dispose();
                this._vertexBuffer = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            if (this.particleTexture) {
                this.particleTexture.dispose();
                this.particleTexture = null;
            }
            // Remove from scene
            var index = this._scene.particleSystems.indexOf(this);
            this._scene.particleSystems.splice(index, 1);
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        // Clone
        ParticleSystem.prototype.clone = function (name, newEmitter) {
            var result = new ParticleSystem(name, this._capacity, this._scene);
            BABYLON.Tools.DeepCopy(this, result, ["particles"]);
            if (newEmitter === undefined) {
                newEmitter = this.emitter;
            }
            result.emitter = newEmitter;
            if (this.particleTexture) {
                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
            }
            result.start();
            return result;
        };
        ParticleSystem.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.id = this.id;
            // Emitter
            if (this.emitter.position) {
                serializationObject.emitterId = this.emitter.id;
            }
            else {
                serializationObject.emitter = this.emitter.asArray();
            }
            serializationObject.capacity = this.getCapacity();
            if (this.particleTexture) {
                serializationObject.textureName = this.particleTexture.name;
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            // Particle system
            serializationObject.minAngularSpeed = this.minAngularSpeed;
            serializationObject.maxAngularSpeed = this.maxAngularSpeed;
            serializationObject.minSize = this.minSize;
            serializationObject.maxSize = this.maxSize;
            serializationObject.minEmitPower = this.minEmitPower;
            serializationObject.maxEmitPower = this.maxEmitPower;
            serializationObject.minLifeTime = this.minLifeTime;
            serializationObject.maxLifeTime = this.maxLifeTime;
            serializationObject.emitRate = this.emitRate;
            serializationObject.minEmitBox = this.minEmitBox.asArray();
            serializationObject.maxEmitBox = this.maxEmitBox.asArray();
            serializationObject.gravity = this.gravity.asArray();
            serializationObject.direction1 = this.direction1.asArray();
            serializationObject.direction2 = this.direction2.asArray();
            serializationObject.color1 = this.color1.asArray();
            serializationObject.color2 = this.color2.asArray();
            serializationObject.colorDead = this.colorDead.asArray();
            serializationObject.updateSpeed = this.updateSpeed;
            serializationObject.targetStopDuration = this.targetStopDuration;
            serializationObject.textureMask = this.textureMask.asArray();
            serializationObject.blendMode = this.blendMode;
            return serializationObject;
        };
        ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
            var name = parsedParticleSystem.name;
            var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
            if (parsedParticleSystem.id) {
                particleSystem.id = parsedParticleSystem.id;
            }
            // Texture
            if (parsedParticleSystem.textureName) {
                particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
                particleSystem.particleTexture.name = parsedParticleSystem.textureName;
            }
            // Emitter
            if (parsedParticleSystem.emitterId) {
                particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
            }
            else {
                particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
            }
            // Animations
            if (parsedParticleSystem.animations) {
                for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
                    var parsedAnimation = parsedParticleSystem.animations[animationIndex];
                    particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
            }
            if (parsedParticleSystem.autoAnimate) {
                scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
            }
            // Particle system
            particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
            particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
            particleSystem.minSize = parsedParticleSystem.minSize;
            particleSystem.maxSize = parsedParticleSystem.maxSize;
            particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
            particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
            particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
            particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
            particleSystem.emitRate = parsedParticleSystem.emitRate;
            particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
            particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
            particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
            particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
            particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
            particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
            particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
            particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
            particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
            particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
            particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
            particleSystem.blendMode = parsedParticleSystem.blendMode;
            if (!parsedParticleSystem.preventAutoStart) {
                particleSystem.start();
            }
            return particleSystem;
        };
        // Statics
        ParticleSystem.BLENDMODE_ONEONE = 0;
        ParticleSystem.BLENDMODE_STANDARD = 1;
        return ParticleSystem;
    }());
    BABYLON.ParticleSystem = ParticleSystem;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.particleSystem.js.map
 
var BABYLON;
(function (BABYLON) {
    var AnimationRange = (function () {
        function AnimationRange(name, from, to) {
            this.name = name;
            this.from = from;
            this.to = to;
        }
        AnimationRange.prototype.clone = function () {
            return new AnimationRange(this.name, this.from, this.to);
        };
        return AnimationRange;
    }());
    BABYLON.AnimationRange = AnimationRange;
    /**
     * Composed of a frame, and an action function
     */
    var AnimationEvent = (function () {
        function AnimationEvent(frame, action, onlyOnce) {
            this.frame = frame;
            this.action = action;
            this.onlyOnce = onlyOnce;
            this.isDone = false;
        }
        return AnimationEvent;
    }());
    BABYLON.AnimationEvent = AnimationEvent;
    var PathCursor = (function () {
        function PathCursor(path) {
            this.path = path;
            this._onchange = new Array();
            this.value = 0;
            this.animations = new Array();
        }
        PathCursor.prototype.getPoint = function () {
            var point = this.path.getPointAtLengthPosition(this.value);
            return new BABYLON.Vector3(point.x, 0, point.y);
        };
        PathCursor.prototype.moveAhead = function (step) {
            if (step === void 0) { step = 0.002; }
            this.move(step);
            return this;
        };
        PathCursor.prototype.moveBack = function (step) {
            if (step === void 0) { step = 0.002; }
            this.move(-step);
            return this;
        };
        PathCursor.prototype.move = function (step) {
            if (Math.abs(step) > 1) {
                throw "step size should be less than 1.";
            }
            this.value += step;
            this.ensureLimits();
            this.raiseOnChange();
            return this;
        };
        PathCursor.prototype.ensureLimits = function () {
            while (this.value > 1) {
                this.value -= 1;
            }
            while (this.value < 0) {
                this.value += 1;
            }
            return this;
        };
        // used by animation engine
        PathCursor.prototype.markAsDirty = function (propertyName) {
            this.ensureLimits();
            this.raiseOnChange();
            return this;
        };
        PathCursor.prototype.raiseOnChange = function () {
            var _this = this;
            this._onchange.forEach(function (f) { return f(_this); });
            return this;
        };
        PathCursor.prototype.onchange = function (f) {
            this._onchange.push(f);
            return this;
        };
        return PathCursor;
    }());
    BABYLON.PathCursor = PathCursor;
    var Animation = (function () {
        function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
            this.name = name;
            this.targetProperty = targetProperty;
            this.framePerSecond = framePerSecond;
            this.dataType = dataType;
            this.loopMode = loopMode;
            this.enableBlending = enableBlending;
            this._offsetsCache = {};
            this._highLimitsCache = {};
            this._stopped = false;
            this._blendingFactor = 0;
            // The set of event that will be linked to this animation
            this._events = new Array();
            this.allowMatricesInterpolation = false;
            this.blendingSpeed = 0.01;
            this._ranges = {};
            this.targetPropertyPath = targetProperty.split(".");
            this.dataType = dataType;
            this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
        }
        Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
            var dataType = undefined;
            if (!isNaN(parseFloat(from)) && isFinite(from)) {
                dataType = Animation.ANIMATIONTYPE_FLOAT;
            }
            else if (from instanceof BABYLON.Quaternion) {
                dataType = Animation.ANIMATIONTYPE_QUATERNION;
            }
            else if (from instanceof BABYLON.Vector3) {
                dataType = Animation.ANIMATIONTYPE_VECTOR3;
            }
            else if (from instanceof BABYLON.Vector2) {
                dataType = Animation.ANIMATIONTYPE_VECTOR2;
            }
            else if (from instanceof BABYLON.Color3) {
                dataType = Animation.ANIMATIONTYPE_COLOR3;
            }
            else if (from instanceof BABYLON.Size) {
                dataType = Animation.ANIMATIONTYPE_SIZE;
            }
            if (dataType == undefined) {
                return null;
            }
            var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
            var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
            animation.setKeys(keys);
            if (easingFunction !== undefined) {
                animation.setEasingFunction(easingFunction);
            }
            return animation;
        };
        Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
            var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
            return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
        };
        Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
            var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
            node.animations.push(animation);
            return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
        };
        // Methods
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         */
        Animation.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name + ", property: " + this.targetProperty;
            ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
            ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
            ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
            if (fullDetails) {
                ret += ", Ranges: {";
                var first = true;
                for (var name in this._ranges) {
                    if (first) {
                        ret += ", ";
                        first = false;
                    }
                    ret += name;
                }
                ret += "}";
            }
            return ret;
        };
        /**
         * Add an event to this animation.
         */
        Animation.prototype.addEvent = function (event) {
            this._events.push(event);
        };
        /**
         * Remove all events found at the given frame
         * @param frame
         */
        Animation.prototype.removeEvents = function (frame) {
            for (var index = 0; index < this._events.length; index++) {
                if (this._events[index].frame === frame) {
                    this._events.splice(index, 1);
                    index--;
                }
            }
        };
        Animation.prototype.createRange = function (name, from, to) {
            // check name not already in use; could happen for bones after serialized
            if (!this._ranges[name]) {
                this._ranges[name] = new AnimationRange(name, from, to);
            }
        };
        Animation.prototype.deleteRange = function (name, deleteFrames) {
            if (deleteFrames === void 0) { deleteFrames = true; }
            if (this._ranges[name]) {
                if (deleteFrames) {
                    var from = this._ranges[name].from;
                    var to = this._ranges[name].to;
                    // this loop MUST go high to low for multiple splices to work
                    for (var key = this._keys.length - 1; key >= 0; key--) {
                        if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
                            this._keys.splice(key, 1);
                        }
                    }
                }
                this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
            }
        };
        Animation.prototype.getRange = function (name) {
            return this._ranges[name];
        };
        Animation.prototype.reset = function () {
            this._offsetsCache = {};
            this._highLimitsCache = {};
            this.currentFrame = 0;
            this._blendingFactor = 0;
            this._originalBlendValue = null;
        };
        Animation.prototype.isStopped = function () {
            return this._stopped;
        };
        Animation.prototype.getKeys = function () {
            return this._keys;
        };
        Animation.prototype.getHighestFrame = function () {
            var ret = 0;
            for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
                if (ret < this._keys[key].frame) {
                    ret = this._keys[key].frame;
                }
            }
            return ret;
        };
        Animation.prototype.getEasingFunction = function () {
            return this._easingFunction;
        };
        Animation.prototype.setEasingFunction = function (easingFunction) {
            this._easingFunction = easingFunction;
        };
        Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
            return startValue + (endValue - startValue) * gradient;
        };
        Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
        };
        Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
        };
        Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
        };
        Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Size.Lerp(startValue, endValue, gradient);
        };
        Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Color3.Lerp(startValue, endValue, gradient);
        };
        Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
        };
        Animation.prototype.clone = function () {
            var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
            if (this._keys) {
                clone.setKeys(this._keys);
            }
            if (this._ranges) {
                clone._ranges = {};
                for (var name in this._ranges) {
                    clone._ranges[name] = this._ranges[name].clone();
                }
            }
            return clone;
        };
        Animation.prototype.setKeys = function (values) {
            this._keys = values.slice(0);
            this._offsetsCache = {};
            this._highLimitsCache = {};
        };
        Animation.prototype._getKeyValue = function (value) {
            if (typeof value === "function") {
                return value();
            }
            return value;
        };
        Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
            if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
                return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
            }
            this.currentFrame = currentFrame;
            // Try to get a hash to find the right key
            var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
            if (this._keys[startKey].frame >= currentFrame) {
                while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
                    startKey--;
                }
            }
            for (var key = startKey; key < this._keys.length; key++) {
                if (this._keys[key + 1].frame >= currentFrame) {
                    var startValue = this._getKeyValue(this._keys[key].value);
                    var endValue = this._getKeyValue(this._keys[key + 1].value);
                    // gradient : percent of currentFrame between the frame inf and the frame sup
                    var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
                    // check for easingFunction and correction of gradient
                    if (this._easingFunction != null) {
                        gradient = this._easingFunction.ease(gradient);
                    }
                    switch (this.dataType) {
                        // Float
                        case Animation.ANIMATIONTYPE_FLOAT:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.floatInterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
                            }
                            break;
                        // Quaternion
                        case Animation.ANIMATIONTYPE_QUATERNION:
                            var quaternion = null;
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
                                    break;
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                                    break;
                            }
                            return quaternion;
                        // Vector3
                        case Animation.ANIMATIONTYPE_VECTOR3:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.vector3InterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                            }
                        // Vector2
                        case Animation.ANIMATIONTYPE_VECTOR2:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.vector2InterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                            }
                        // Size
                        case Animation.ANIMATIONTYPE_SIZE:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.sizeInterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                            }
                        // Color3
                        case Animation.ANIMATIONTYPE_COLOR3:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.color3InterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                            }
                        // Matrix
                        case Animation.ANIMATIONTYPE_MATRIX:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    if (this.allowMatricesInterpolation) {
                                        return this.matrixInterpolateFunction(startValue, endValue, gradient);
                                    }
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return startValue;
                            }
                        default:
                            break;
                    }
                    break;
                }
            }
            return this._getKeyValue(this._keys[this._keys.length - 1].value);
        };
        Animation.prototype.setValue = function (currentValue, blend) {
            if (blend === void 0) { blend = false; }
            // Set value
            var path;
            var destination;
            if (this.targetPropertyPath.length > 1) {
                var property = this._target[this.targetPropertyPath[0]];
                for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
                    property = property[this.targetPropertyPath[index]];
                }
                path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
                destination = property;
            }
            else {
                path = this.targetPropertyPath[0];
                destination = this._target;
            }
            // Blending
            if (this.enableBlending && this._blendingFactor <= 1.0) {
                if (!this._originalBlendValue) {
                    if (destination[path].clone) {
                        this._originalBlendValue = destination[path].clone();
                    }
                    else {
                        this._originalBlendValue = destination[path];
                    }
                }
                if (this._originalBlendValue.prototype) {
                    if (this._originalBlendValue.prototype.Lerp) {
                        destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
                    }
                    else {
                        destination[path] = currentValue;
                    }
                }
                else if (this._originalBlendValue.m) {
                    destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
                }
                else {
                    destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
                }
                this._blendingFactor += this.blendingSpeed;
            }
            else {
                destination[path] = currentValue;
            }
            if (this._target.markAsDirty) {
                this._target.markAsDirty(this.targetProperty);
            }
        };
        Animation.prototype.goToFrame = function (frame) {
            if (frame < this._keys[0].frame) {
                frame = this._keys[0].frame;
            }
            else if (frame > this._keys[this._keys.length - 1].frame) {
                frame = this._keys[this._keys.length - 1].frame;
            }
            var currentValue = this._interpolate(frame, 0, this.loopMode);
            this.setValue(currentValue);
        };
        Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
            if (blend === void 0) { blend = false; }
            if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
                this._stopped = true;
                return false;
            }
            var returnValue = true;
            // Adding a start key at frame 0 if missing
            if (this._keys[0].frame !== 0) {
                var newKey = { frame: 0, value: this._keys[0].value };
                this._keys.splice(0, 0, newKey);
            }
            // Check limits
            if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
                from = this._keys[0].frame;
            }
            if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
                to = this._keys[this._keys.length - 1].frame;
            }
            //to and from cannot be the same key
            if (from === to) {
                from++;
            }
            // Compute ratio
            var range = to - from;
            var offsetValue;
            // ratio represents the frame delta between from and to
            var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
            var highLimitValue = 0;
            if (ratio > range && !loop) {
                returnValue = false;
                highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
            }
            else {
                // Get max value if required
                if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
                    var keyOffset = to.toString() + from.toString();
                    if (!this._offsetsCache[keyOffset]) {
                        var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
                        var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
                        switch (this.dataType) {
                            // Float
                            case Animation.ANIMATIONTYPE_FLOAT:
                                this._offsetsCache[keyOffset] = toValue - fromValue;
                                break;
                            // Quaternion
                            case Animation.ANIMATIONTYPE_QUATERNION:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                                break;
                            // Vector3
                            case Animation.ANIMATIONTYPE_VECTOR3:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            // Vector2
                            case Animation.ANIMATIONTYPE_VECTOR2:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            // Size
                            case Animation.ANIMATIONTYPE_SIZE:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            // Color3
                            case Animation.ANIMATIONTYPE_COLOR3:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            default:
                                break;
                        }
                        this._highLimitsCache[keyOffset] = toValue;
                    }
                    highLimitValue = this._highLimitsCache[keyOffset];
                    offsetValue = this._offsetsCache[keyOffset];
                }
            }
            if (offsetValue === undefined) {
                switch (this.dataType) {
                    // Float
                    case Animation.ANIMATIONTYPE_FLOAT:
                        offsetValue = 0;
                        break;
                    // Quaternion
                    case Animation.ANIMATIONTYPE_QUATERNION:
                        offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
                        break;
                    // Vector3
                    case Animation.ANIMATIONTYPE_VECTOR3:
                        offsetValue = BABYLON.Vector3.Zero();
                        break;
                    // Vector2
                    case Animation.ANIMATIONTYPE_VECTOR2:
                        offsetValue = BABYLON.Vector2.Zero();
                        break;
                    // Size
                    case Animation.ANIMATIONTYPE_SIZE:
                        offsetValue = BABYLON.Size.Zero();
                        break;
                    // Color3
                    case Animation.ANIMATIONTYPE_COLOR3:
                        offsetValue = BABYLON.Color3.Black();
                }
            }
            // Compute value
            var repeatCount = (ratio / range) >> 0;
            var currentFrame = returnValue ? from + ratio % range : to;
            var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
            // Set value
            this.setValue(currentValue);
            // Check events
            for (var index = 0; index < this._events.length; index++) {
                if (currentFrame >= this._events[index].frame) {
                    var event = this._events[index];
                    if (!event.isDone) {
                        // If event should be done only once, remove it.
                        if (event.onlyOnce) {
                            this._events.splice(index, 1);
                            index--;
                        }
                        event.isDone = true;
                        event.action();
                    } // Don't do anything if the event has already be done.
                }
                else if (this._events[index].isDone && !this._events[index].onlyOnce) {
                    // reset event, the animation is looping
                    this._events[index].isDone = false;
                }
            }
            if (!returnValue) {
                this._stopped = true;
            }
            return returnValue;
        };
        Animation.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.property = this.targetProperty;
            serializationObject.framePerSecond = this.framePerSecond;
            serializationObject.dataType = this.dataType;
            serializationObject.loopBehavior = this.loopMode;
            var dataType = this.dataType;
            serializationObject.keys = [];
            var keys = this.getKeys();
            for (var index = 0; index < keys.length; index++) {
                var animationKey = keys[index];
                var key = {};
                key.frame = animationKey.frame;
                switch (dataType) {
                    case Animation.ANIMATIONTYPE_FLOAT:
                        key.values = [animationKey.value];
                        break;
                    case Animation.ANIMATIONTYPE_QUATERNION:
                    case Animation.ANIMATIONTYPE_MATRIX:
                    case Animation.ANIMATIONTYPE_VECTOR3:
                    case Animation.ANIMATIONTYPE_COLOR3:
                        key.values = animationKey.value.asArray();
                        break;
                }
                serializationObject.keys.push(key);
            }
            serializationObject.ranges = [];
            for (var name in this._ranges) {
                var range = {};
                range.name = name;
                range.from = this._ranges[name].from;
                range.to = this._ranges[name].to;
                serializationObject.ranges.push(range);
            }
            return serializationObject;
        };
        Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
            get: function () {
                return Animation._ANIMATIONTYPE_FLOAT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
            get: function () {
                return Animation._ANIMATIONTYPE_VECTOR3;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
            get: function () {
                return Animation._ANIMATIONTYPE_VECTOR2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
            get: function () {
                return Animation._ANIMATIONTYPE_SIZE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
            get: function () {
                return Animation._ANIMATIONTYPE_QUATERNION;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
            get: function () {
                return Animation._ANIMATIONTYPE_MATRIX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
            get: function () {
                return Animation._ANIMATIONTYPE_COLOR3;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
            get: function () {
                return Animation._ANIMATIONLOOPMODE_RELATIVE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
            get: function () {
                return Animation._ANIMATIONLOOPMODE_CYCLE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
            get: function () {
                return Animation._ANIMATIONLOOPMODE_CONSTANT;
            },
            enumerable: true,
            configurable: true
        });
        Animation.Parse = function (parsedAnimation) {
            var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
            var dataType = parsedAnimation.dataType;
            var keys = [];
            var data;
            var index;
            for (index = 0; index < parsedAnimation.keys.length; index++) {
                var key = parsedAnimation.keys[index];
                switch (dataType) {
                    case Animation.ANIMATIONTYPE_FLOAT:
                        data = key.values[0];
                        break;
                    case Animation.ANIMATIONTYPE_QUATERNION:
                        data = BABYLON.Quaternion.FromArray(key.values);
                        break;
                    case Animation.ANIMATIONTYPE_MATRIX:
                        data = BABYLON.Matrix.FromArray(key.values);
                        break;
                    case Animation.ANIMATIONTYPE_COLOR3:
                        data = BABYLON.Color3.FromArray(key.values);
                        break;
                    case Animation.ANIMATIONTYPE_VECTOR3:
                    default:
                        data = BABYLON.Vector3.FromArray(key.values);
                        break;
                }
                keys.push({
                    frame: key.frame,
                    value: data
                });
            }
            animation.setKeys(keys);
            if (parsedAnimation.ranges) {
                for (index = 0; index < parsedAnimation.ranges.length; index++) {
                    data = parsedAnimation.ranges[index];
                    animation.createRange(data.name, data.from, data.to);
                }
            }
            return animation;
        };
        Animation.AppendSerializedAnimations = function (source, destination) {
            if (source.animations) {
                destination.animations = [];
                for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
                    var animation = source.animations[animationIndex];
                    destination.animations.push(animation.serialize());
                }
            }
        };
        // Statics
        Animation._ANIMATIONTYPE_FLOAT = 0;
        Animation._ANIMATIONTYPE_VECTOR3 = 1;
        Animation._ANIMATIONTYPE_QUATERNION = 2;
        Animation._ANIMATIONTYPE_MATRIX = 3;
        Animation._ANIMATIONTYPE_COLOR3 = 4;
        Animation._ANIMATIONTYPE_VECTOR2 = 5;
        Animation._ANIMATIONTYPE_SIZE = 6;
        Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
        Animation._ANIMATIONLOOPMODE_CYCLE = 1;
        Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
        return Animation;
    }());
    BABYLON.Animation = Animation;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.animation.js.map
 
var BABYLON;
(function (BABYLON) {
    var Animatable = (function () {
        function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
            if (fromFrame === void 0) { fromFrame = 0; }
            if (toFrame === void 0) { toFrame = 100; }
            if (loopAnimation === void 0) { loopAnimation = false; }
            if (speedRatio === void 0) { speedRatio = 1.0; }
            this.target = target;
            this.fromFrame = fromFrame;
            this.toFrame = toFrame;
            this.loopAnimation = loopAnimation;
            this.speedRatio = speedRatio;
            this.onAnimationEnd = onAnimationEnd;
            this._animations = new Array();
            this._paused = false;
            this.animationStarted = false;
            if (animations) {
                this.appendAnimations(target, animations);
            }
            this._scene = scene;
            scene._activeAnimatables.push(this);
        }
        // Methods
        Animatable.prototype.getAnimations = function () {
            return this._animations;
        };
        Animatable.prototype.appendAnimations = function (target, animations) {
            for (var index = 0; index < animations.length; index++) {
                var animation = animations[index];
                animation._target = target;
                this._animations.push(animation);
            }
        };
        Animatable.prototype.getAnimationByTargetProperty = function (property) {
            var animations = this._animations;
            for (var index = 0; index < animations.length; index++) {
                if (animations[index].targetProperty === property) {
                    return animations[index];
                }
            }
            return null;
        };
        Animatable.prototype.reset = function () {
            var animations = this._animations;
            for (var index = 0; index < animations.length; index++) {
                animations[index].reset();
            }
            this._localDelayOffset = null;
            this._pausedDelay = null;
        };
        Animatable.prototype.enableBlending = function (blendingSpeed) {
            var animations = this._animations;
            for (var index = 0; index < animations.length; index++) {
                animations[index].enableBlending = true;
                animations[index].blendingSpeed = blendingSpeed;
            }
        };
        Animatable.prototype.disableBlending = function () {
            var animations = this._animations;
            for (var index = 0; index < animations.length; index++) {
                animations[index].enableBlending = false;
            }
        };
        Animatable.prototype.goToFrame = function (frame) {
            var animations = this._animations;
            if (animations[0]) {
                var fps = animations[0].framePerSecond;
                var currentFrame = animations[0].currentFrame;
                var adjustTime = frame - currentFrame;
                var delay = adjustTime * 1000 / fps;
                this._localDelayOffset -= delay;
            }
            for (var index = 0; index < animations.length; index++) {
                animations[index].goToFrame(frame);
            }
        };
        Animatable.prototype.pause = function () {
            if (this._paused) {
                return;
            }
            this._paused = true;
        };
        Animatable.prototype.restart = function () {
            this._paused = false;
        };
        Animatable.prototype.stop = function (animationName) {
            var index = this._scene._activeAnimatables.indexOf(this);
            if (index > -1) {
                var animations = this._animations;
                var numberOfAnimationsStopped = 0;
                for (var index = animations.length - 1; index >= 0; index--) {
                    if (typeof animationName === "string" && animations[index].name != animationName) {
                        continue;
                    }
                    animations[index].reset();
                    animations.splice(index, 1);
                    numberOfAnimationsStopped++;
                }
                if (animations.length == numberOfAnimationsStopped) {
                    this._scene._activeAnimatables.splice(index, 1);
                    if (this.onAnimationEnd) {
                        this.onAnimationEnd();
                    }
                }
            }
        };
        Animatable.prototype._animate = function (delay) {
            if (this._paused) {
                this.animationStarted = false;
                if (!this._pausedDelay) {
                    this._pausedDelay = delay;
                }
                return true;
            }
            if (!this._localDelayOffset) {
                this._localDelayOffset = delay;
            }
            else if (this._pausedDelay) {
                this._localDelayOffset += delay - this._pausedDelay;
                this._pausedDelay = null;
            }
            // Animating
            var running = false;
            var animations = this._animations;
            var index;
            for (index = 0; index < animations.length; index++) {
                var animation = animations[index];
                var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
                running = running || isRunning;
            }
            this.animationStarted = running;
            if (!running) {
                // Remove from active animatables
                index = this._scene._activeAnimatables.indexOf(this);
                this._scene._activeAnimatables.splice(index, 1);
            }
            if (!running && this.onAnimationEnd) {
                this.onAnimationEnd();
                this.onAnimationEnd = null;
            }
            return running;
        };
        return Animatable;
    }());
    BABYLON.Animatable = Animatable;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.animatable.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var EasingFunction = (function () {
        function EasingFunction() {
            // Properties
            this._easingMode = EasingFunction.EASINGMODE_EASEIN;
        }
        Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
            get: function () {
                return EasingFunction._EASINGMODE_EASEIN;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
            get: function () {
                return EasingFunction._EASINGMODE_EASEOUT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
            get: function () {
                return EasingFunction._EASINGMODE_EASEINOUT;
            },
            enumerable: true,
            configurable: true
        });
        EasingFunction.prototype.setEasingMode = function (easingMode) {
            var n = Math.min(Math.max(easingMode, 0), 2);
            this._easingMode = n;
        };
        EasingFunction.prototype.getEasingMode = function () {
            return this._easingMode;
        };
        EasingFunction.prototype.easeInCore = function (gradient) {
            throw new Error('You must implement this method');
        };
        EasingFunction.prototype.ease = function (gradient) {
            switch (this._easingMode) {
                case EasingFunction.EASINGMODE_EASEIN:
                    return this.easeInCore(gradient);
                case EasingFunction.EASINGMODE_EASEOUT:
                    return (1 - this.easeInCore(1 - gradient));
            }
            if (gradient >= 0.5) {
                return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
            }
            return (this.easeInCore(gradient * 2) * 0.5);
        };
        //Statics
        EasingFunction._EASINGMODE_EASEIN = 0;
        EasingFunction._EASINGMODE_EASEOUT = 1;
        EasingFunction._EASINGMODE_EASEINOUT = 2;
        return EasingFunction;
    }());
    BABYLON.EasingFunction = EasingFunction;
    var CircleEase = (function (_super) {
        __extends(CircleEase, _super);
        function CircleEase() {
            _super.apply(this, arguments);
        }
        CircleEase.prototype.easeInCore = function (gradient) {
            gradient = Math.max(0, Math.min(1, gradient));
            return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
        };
        return CircleEase;
    }(EasingFunction));
    BABYLON.CircleEase = CircleEase;
    var BackEase = (function (_super) {
        __extends(BackEase, _super);
        function BackEase(amplitude) {
            if (amplitude === void 0) { amplitude = 1; }
            _super.call(this);
            this.amplitude = amplitude;
        }
        BackEase.prototype.easeInCore = function (gradient) {
            var num = Math.max(0, this.amplitude);
            return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
        };
        return BackEase;
    }(EasingFunction));
    BABYLON.BackEase = BackEase;
    var BounceEase = (function (_super) {
        __extends(BounceEase, _super);
        function BounceEase(bounces, bounciness) {
            if (bounces === void 0) { bounces = 3; }
            if (bounciness === void 0) { bounciness = 2; }
            _super.call(this);
            this.bounces = bounces;
            this.bounciness = bounciness;
        }
        BounceEase.prototype.easeInCore = function (gradient) {
            var y = Math.max(0.0, this.bounces);
            var bounciness = this.bounciness;
            if (bounciness <= 1.0) {
                bounciness = 1.001;
            }
            var num9 = Math.pow(bounciness, y);
            var num5 = 1.0 - bounciness;
            var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
            var num15 = gradient * num4;
            var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
            var num3 = Math.floor(num65);
            var num13 = num3 + 1.0;
            var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
            var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
            var num7 = (num8 + num12) * 0.5;
            var num6 = gradient - num7;
            var num2 = num7 - num8;
            return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
        };
        return BounceEase;
    }(EasingFunction));
    BABYLON.BounceEase = BounceEase;
    var CubicEase = (function (_super) {
        __extends(CubicEase, _super);
        function CubicEase() {
            _super.apply(this, arguments);
        }
        CubicEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient * gradient);
        };
        return CubicEase;
    }(EasingFunction));
    BABYLON.CubicEase = CubicEase;
    var ElasticEase = (function (_super) {
        __extends(ElasticEase, _super);
        function ElasticEase(oscillations, springiness) {
            if (oscillations === void 0) { oscillations = 3; }
            if (springiness === void 0) { springiness = 3; }
            _super.call(this);
            this.oscillations = oscillations;
            this.springiness = springiness;
        }
        ElasticEase.prototype.easeInCore = function (gradient) {
            var num2;
            var num3 = Math.max(0.0, this.oscillations);
            var num = Math.max(0.0, this.springiness);
            if (num == 0) {
                num2 = gradient;
            }
            else {
                num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
            }
            return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
        };
        return ElasticEase;
    }(EasingFunction));
    BABYLON.ElasticEase = ElasticEase;
    var ExponentialEase = (function (_super) {
        __extends(ExponentialEase, _super);
        function ExponentialEase(exponent) {
            if (exponent === void 0) { exponent = 2; }
            _super.call(this);
            this.exponent = exponent;
        }
        ExponentialEase.prototype.easeInCore = function (gradient) {
            if (this.exponent <= 0) {
                return gradient;
            }
            return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
        };
        return ExponentialEase;
    }(EasingFunction));
    BABYLON.ExponentialEase = ExponentialEase;
    var PowerEase = (function (_super) {
        __extends(PowerEase, _super);
        function PowerEase(power) {
            if (power === void 0) { power = 2; }
            _super.call(this);
            this.power = power;
        }
        PowerEase.prototype.easeInCore = function (gradient) {
            var y = Math.max(0.0, this.power);
            return Math.pow(gradient, y);
        };
        return PowerEase;
    }(EasingFunction));
    BABYLON.PowerEase = PowerEase;
    var QuadraticEase = (function (_super) {
        __extends(QuadraticEase, _super);
        function QuadraticEase() {
            _super.apply(this, arguments);
        }
        QuadraticEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient);
        };
        return QuadraticEase;
    }(EasingFunction));
    BABYLON.QuadraticEase = QuadraticEase;
    var QuarticEase = (function (_super) {
        __extends(QuarticEase, _super);
        function QuarticEase() {
            _super.apply(this, arguments);
        }
        QuarticEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient * gradient * gradient);
        };
        return QuarticEase;
    }(EasingFunction));
    BABYLON.QuarticEase = QuarticEase;
    var QuinticEase = (function (_super) {
        __extends(QuinticEase, _super);
        function QuinticEase() {
            _super.apply(this, arguments);
        }
        QuinticEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient * gradient * gradient * gradient);
        };
        return QuinticEase;
    }(EasingFunction));
    BABYLON.QuinticEase = QuinticEase;
    var SineEase = (function (_super) {
        __extends(SineEase, _super);
        function SineEase() {
            _super.apply(this, arguments);
        }
        SineEase.prototype.easeInCore = function (gradient) {
            return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
        };
        return SineEase;
    }(EasingFunction));
    BABYLON.SineEase = SineEase;
    var BezierCurveEase = (function (_super) {
        __extends(BezierCurveEase, _super);
        function BezierCurveEase(x1, y1, x2, y2) {
            if (x1 === void 0) { x1 = 0; }
            if (y1 === void 0) { y1 = 0; }
            if (x2 === void 0) { x2 = 1; }
            if (y2 === void 0) { y2 = 1; }
            _super.call(this);
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
        }
        BezierCurveEase.prototype.easeInCore = function (gradient) {
            return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
        };
        return BezierCurveEase;
    }(EasingFunction));
    BABYLON.BezierCurveEase = BezierCurveEase;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.easing.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Bone = (function (_super) {
        __extends(Bone, _super);
        function Bone(name, skeleton, parentBone, matrix, restPose) {
            _super.call(this, name, skeleton.getScene());
            this.name = name;
            this.children = new Array();
            this.animations = new Array();
            this._worldTransform = new BABYLON.Matrix();
            this._absoluteTransform = new BABYLON.Matrix();
            this._invertedAbsoluteTransform = new BABYLON.Matrix();
            this._scaleMatrix = BABYLON.Matrix.Identity();
            this._scaleVector = new BABYLON.Vector3(1, 1, 1);
            this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
            this._scalingDeterminant = 1;
            this._syncScaleVector = function () {
                var lm = this.getLocalMatrix();
                var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
                var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
                var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
                var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
                var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
                var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
                this._scaleVector.x = xs * Math.sqrt(xsq);
                this._scaleVector.y = ys * Math.sqrt(ysq);
                this._scaleVector.z = zs * Math.sqrt(zsq);
                if (this._parent) {
                    this._scaleVector.x /= this._parent._negateScaleChildren.x;
                    this._scaleVector.y /= this._parent._negateScaleChildren.y;
                    this._scaleVector.z /= this._parent._negateScaleChildren.z;
                }
                BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
            };
            this._skeleton = skeleton;
            this._matrix = matrix;
            this._baseMatrix = matrix;
            this._restPose = restPose ? restPose : matrix.clone();
            skeleton.bones.push(this);
            if (parentBone) {
                this._parent = parentBone;
                parentBone.children.push(this);
            }
            else {
                this._parent = null;
            }
            this._updateDifferenceMatrix();
            if (this.getAbsoluteTransform().determinant() < 0) {
                this._scalingDeterminant *= -1;
            }
        }
        // Members
        Bone.prototype.getParent = function () {
            return this._parent;
        };
        Bone.prototype.getLocalMatrix = function () {
            return this._matrix;
        };
        Bone.prototype.getBaseMatrix = function () {
            return this._baseMatrix;
        };
        Bone.prototype.getRestPose = function () {
            return this._restPose;
        };
        Bone.prototype.returnToRest = function () {
            this.updateMatrix(this._restPose.clone());
        };
        Bone.prototype.getWorldMatrix = function () {
            return this._worldTransform;
        };
        Bone.prototype.getInvertedAbsoluteTransform = function () {
            return this._invertedAbsoluteTransform;
        };
        Bone.prototype.getAbsoluteTransform = function () {
            return this._absoluteTransform;
        };
        // Methods
        Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
            if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
            this._baseMatrix = matrix.clone();
            this._matrix = matrix.clone();
            this._skeleton._markAsDirty();
            if (updateDifferenceMatrix) {
                this._updateDifferenceMatrix();
            }
        };
        Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
            if (!rootMatrix) {
                rootMatrix = this._baseMatrix;
            }
            if (this._parent) {
                rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
            }
            else {
                this._absoluteTransform.copyFrom(rootMatrix);
            }
            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
            for (var index = 0; index < this.children.length; index++) {
                this.children[index]._updateDifferenceMatrix();
            }
        };
        Bone.prototype.markAsDirty = function () {
            this._currentRenderId++;
            this._skeleton._markAsDirty();
        };
        Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
            if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
            // all animation may be coming from a library skeleton, so may need to create animation
            if (this.animations.length === 0) {
                this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
                this.animations[0].setKeys([]);
            }
            // get animation info / verify there is such a range from the source bone
            var sourceRange = source.animations[0].getRange(rangeName);
            if (!sourceRange) {
                return false;
            }
            var from = sourceRange.from;
            var to = sourceRange.to;
            var sourceKeys = source.animations[0].getKeys();
            // rescaling prep
            var sourceBoneLength = source.length;
            var sourceParent = source.getParent();
            var parent = this.getParent();
            var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
            var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
            var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
            var destKeys = this.animations[0].getKeys();
            // loop vars declaration
            var orig;
            var origTranslation;
            var mat;
            for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
                orig = sourceKeys[key];
                if (orig.frame >= from && orig.frame <= to) {
                    if (rescaleAsRequired) {
                        mat = orig.value.clone();
                        // scale based on parent ratio, when bone has parent
                        if (parentScalingReqd) {
                            origTranslation = mat.getTranslation();
                            mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
                        }
                        else if (dimensionsScalingReqd) {
                            origTranslation = mat.getTranslation();
                            mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
                        }
                        else {
                            mat = orig.value;
                        }
                    }
                    else {
                        mat = orig.value;
                    }
                    destKeys.push({ frame: orig.frame + frameOffset, value: mat });
                }
            }
            this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
            return true;
        };
        Bone.prototype.translate = function (vec, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var lm = this.getLocalMatrix();
            if (space == BABYLON.Space.LOCAL) {
                lm.m[12] += vec.x;
                lm.m[13] += vec.y;
                lm.m[14] += vec.z;
            }
            else {
                this._skeleton.computeAbsoluteTransforms();
                var tmat = BABYLON.Tmp.Matrix[0];
                var tvec = BABYLON.Tmp.Vector3[0];
                if (mesh) {
                    tmat.copyFrom(this._parent.getAbsoluteTransform());
                    tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
                }
                else {
                    tmat.copyFrom(this._parent.getAbsoluteTransform());
                }
                tmat.m[12] = 0;
                tmat.m[13] = 0;
                tmat.m[14] = 0;
                tmat.invert();
                BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
                lm.m[12] += tvec.x;
                lm.m[13] += tvec.y;
                lm.m[14] += tvec.z;
            }
            this.markAsDirty();
        };
        Bone.prototype.setPosition = function (position, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var lm = this.getLocalMatrix();
            if (space == BABYLON.Space.LOCAL) {
                lm.m[12] = position.x;
                lm.m[13] = position.y;
                lm.m[14] = position.z;
            }
            else {
                this._skeleton.computeAbsoluteTransforms();
                var tmat = BABYLON.Tmp.Matrix[0];
                var vec = BABYLON.Tmp.Vector3[0];
                if (mesh) {
                    tmat.copyFrom(this._parent.getAbsoluteTransform());
                    tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
                }
                else {
                    tmat.copyFrom(this._parent.getAbsoluteTransform());
                }
                tmat.invert();
                BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
                lm.m[12] = vec.x;
                lm.m[13] = vec.y;
                lm.m[14] = vec.z;
            }
            this.markAsDirty();
        };
        Bone.prototype.setAbsolutePosition = function (position, mesh) {
            this.setPosition(position, BABYLON.Space.WORLD, mesh);
        };
        Bone.prototype.setScale = function (x, y, z, scaleChildren) {
            if (scaleChildren === void 0) { scaleChildren = false; }
            if (this.animations[0] && !this.animations[0].isStopped()) {
                if (!scaleChildren) {
                    this._negateScaleChildren.x = 1 / x;
                    this._negateScaleChildren.y = 1 / y;
                    this._negateScaleChildren.z = 1 / z;
                }
                this._syncScaleVector();
            }
            this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
        };
        Bone.prototype.scale = function (x, y, z, scaleChildren) {
            if (scaleChildren === void 0) { scaleChildren = false; }
            var locMat = this.getLocalMatrix();
            var origLocMat = BABYLON.Tmp.Matrix[0];
            origLocMat.copyFrom(locMat);
            var origLocMatInv = BABYLON.Tmp.Matrix[1];
            origLocMatInv.copyFrom(origLocMat);
            origLocMatInv.invert();
            var scaleMat = BABYLON.Tmp.Matrix[2];
            BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
            this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
            this._scaleVector.x *= x;
            this._scaleVector.y *= y;
            this._scaleVector.z *= z;
            locMat.multiplyToRef(origLocMatInv, locMat);
            locMat.multiplyToRef(scaleMat, locMat);
            locMat.multiplyToRef(origLocMat, locMat);
            var parent = this.getParent();
            if (parent) {
                locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
            }
            else {
                this.getAbsoluteTransform().copyFrom(locMat);
            }
            var len = this.children.length;
            scaleMat.invert();
            for (var i = 0; i < len; i++) {
                var child = this.children[i];
                var cm = child.getLocalMatrix();
                cm.multiplyToRef(scaleMat, cm);
                var lm = child.getLocalMatrix();
                lm.m[12] *= x;
                lm.m[13] *= y;
                lm.m[14] *= z;
            }
            this.computeAbsoluteTransforms();
            if (scaleChildren) {
                for (var i = 0; i < len; i++) {
                    this.children[i].scale(x, y, z, scaleChildren);
                }
            }
            this.markAsDirty();
        };
        Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var rotMat = BABYLON.Tmp.Matrix[0];
            BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
            var rotMatInv = BABYLON.Tmp.Matrix[1];
            this._getNegativeRotationToRef(rotMatInv, space, mesh);
            rotMatInv.multiplyToRef(rotMat, rotMat);
            this._rotateWithMatrix(rotMat, space, mesh);
        };
        Bone.prototype.rotate = function (axis, amount, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var rmat = BABYLON.Tmp.Matrix[0];
            rmat.m[12] = 0;
            rmat.m[13] = 0;
            rmat.m[14] = 0;
            BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
            this._rotateWithMatrix(rmat, space, mesh);
        };
        Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var rotMat = BABYLON.Tmp.Matrix[0];
            BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
            var rotMatInv = BABYLON.Tmp.Matrix[1];
            this._getNegativeRotationToRef(rotMatInv, space, mesh);
            rotMatInv.multiplyToRef(rotMat, rotMat);
            this._rotateWithMatrix(rotMat, space, mesh);
        };
        Bone.prototype.setRotation = function (rotation, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
        };
        Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var rotMatInv = BABYLON.Tmp.Matrix[0];
            this._getNegativeRotationToRef(rotMatInv, space, mesh);
            var rotMat = BABYLON.Tmp.Matrix[1];
            BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
            rotMatInv.multiplyToRef(rotMat, rotMat);
            this._rotateWithMatrix(rotMat, space, mesh);
        };
        Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var rotMatInv = BABYLON.Tmp.Matrix[0];
            this._getNegativeRotationToRef(rotMatInv, space, mesh);
            var rotMat2 = BABYLON.Tmp.Matrix[1];
            rotMat2.copyFrom(rotMat);
            rotMatInv.multiplyToRef(rotMat, rotMat2);
            this._rotateWithMatrix(rotMat2, space, mesh);
        };
        Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var lmat = this.getLocalMatrix();
            var lx = lmat.m[12];
            var ly = lmat.m[13];
            var lz = lmat.m[14];
            var parent = this.getParent();
            var parentScale = BABYLON.Tmp.Matrix[3];
            var parentScaleInv = BABYLON.Tmp.Matrix[4];
            if (parent) {
                if (space == BABYLON.Space.WORLD) {
                    if (mesh) {
                        parentScale.copyFrom(mesh.getWorldMatrix());
                        parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
                    }
                    else {
                        parentScale.copyFrom(parent.getAbsoluteTransform());
                    }
                }
                else {
                    parentScale = parent._scaleMatrix;
                }
                parentScaleInv.copyFrom(parentScale);
                parentScaleInv.invert();
                lmat.multiplyToRef(parentScale, lmat);
                lmat.multiplyToRef(rmat, lmat);
                lmat.multiplyToRef(parentScaleInv, lmat);
            }
            else {
                if (space == BABYLON.Space.WORLD && mesh) {
                    parentScale.copyFrom(mesh.getWorldMatrix());
                    parentScaleInv.copyFrom(parentScale);
                    parentScaleInv.invert();
                    lmat.multiplyToRef(parentScale, lmat);
                    lmat.multiplyToRef(rmat, lmat);
                    lmat.multiplyToRef(parentScaleInv, lmat);
                }
                else {
                    lmat.multiplyToRef(rmat, lmat);
                }
            }
            lmat.m[12] = lx;
            lmat.m[13] = ly;
            lmat.m[14] = lz;
            this.computeAbsoluteTransforms();
            this.markAsDirty();
        };
        Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space == BABYLON.Space.WORLD) {
                var scaleMatrix = BABYLON.Tmp.Matrix[2];
                scaleMatrix.copyFrom(this._scaleMatrix);
                rotMatInv.copyFrom(this.getAbsoluteTransform());
                if (mesh) {
                    rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
                    var meshScale = BABYLON.Tmp.Matrix[3];
                    BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
                    scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
                }
                rotMatInv.invert();
                scaleMatrix.m[0] *= this._scalingDeterminant;
                rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
            }
            else {
                rotMatInv.copyFrom(this.getLocalMatrix());
                rotMatInv.invert();
                var scaleMatrix = BABYLON.Tmp.Matrix[2];
                scaleMatrix.copyFrom(this._scaleMatrix);
                if (this._parent) {
                    var pscaleMatrix = BABYLON.Tmp.Matrix[3];
                    pscaleMatrix.copyFrom(this._parent._scaleMatrix);
                    pscaleMatrix.invert();
                    pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
                }
                else {
                    scaleMatrix.m[0] *= this._scalingDeterminant;
                }
                rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
            }
        };
        Bone.prototype.getScale = function () {
            return this._scaleVector.clone();
        };
        Bone.prototype.getScaleToRef = function (result) {
            result.copyFrom(this._scaleVector);
        };
        Bone.prototype.getPosition = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var pos = BABYLON.Vector3.Zero();
            this.getPositionToRef(space, mesh, pos);
            return pos;
        };
        Bone.prototype.getPositionToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space == BABYLON.Space.LOCAL) {
                var lm = this.getLocalMatrix();
                result.x = lm.m[12];
                result.y = lm.m[13];
                result.z = lm.m[14];
            }
            else {
                this._skeleton.computeAbsoluteTransforms();
                var tmat = BABYLON.Tmp.Matrix[0];
                if (mesh) {
                    tmat.copyFrom(this.getAbsoluteTransform());
                    tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
                }
                else {
                    tmat = this.getAbsoluteTransform();
                }
                result.x = tmat.m[12];
                result.y = tmat.m[13];
                result.z = tmat.m[14];
            }
        };
        Bone.prototype.getAbsolutePosition = function (mesh) {
            var pos = BABYLON.Vector3.Zero();
            this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
            return pos;
        };
        Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
            this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
        };
        Bone.prototype.computeAbsoluteTransforms = function () {
            if (this._parent) {
                this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
            }
            else {
                this._absoluteTransform.copyFrom(this._matrix);
                var poseMatrix = this._skeleton.getPoseMatrix();
                if (poseMatrix) {
                    this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
                }
            }
            var children = this.children;
            var len = children.length;
            for (var i = 0; i < len; i++) {
                children[i].computeAbsoluteTransforms();
            }
        };
        Bone.prototype.getDirection = function (localAxis, mesh) {
            var result = BABYLON.Vector3.Zero();
            this.getDirectionToRef(localAxis, mesh, result);
            return result;
        };
        Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
            this._skeleton.computeAbsoluteTransforms();
            var mat = BABYLON.Tmp.Matrix[0];
            mat.copyFrom(this.getAbsoluteTransform());
            if (mesh) {
                mat.multiplyToRef(mesh.getWorldMatrix(), mat);
            }
            BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
            result.normalize();
        };
        Bone.prototype.getRotation = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var result = BABYLON.Vector3.Zero();
            this.getRotationToRef(space, mesh, result);
            return result;
        };
        Bone.prototype.getRotationToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var quat = BABYLON.Tmp.Quaternion[0];
            this.getRotationQuaternionToRef(space, mesh, quat);
            quat.toEulerAnglesToRef(result);
        };
        Bone.prototype.getRotationQuaternion = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var result = BABYLON.Quaternion.Identity();
            this.getRotationQuaternionToRef(space, mesh, result);
            return result;
        };
        Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space == BABYLON.Space.LOCAL) {
                this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
            }
            else {
                var mat = BABYLON.Tmp.Matrix[0];
                var amat = this.getAbsoluteTransform();
                if (mesh) {
                    amat.multiplyToRef(mesh.getWorldMatrix(), mat);
                }
                else {
                    mat.copyFrom(amat);
                }
                mat.m[0] *= this._scalingDeterminant;
                mat.m[1] *= this._scalingDeterminant;
                mat.m[2] *= this._scalingDeterminant;
                mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
            }
        };
        Bone.prototype.getRotationMatrix = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var result = BABYLON.Matrix.Identity();
            this.getRotationMatrixToRef(space, mesh, result);
            return result;
        };
        Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space == BABYLON.Space.LOCAL) {
                this.getLocalMatrix().getRotationMatrixToRef(result);
            }
            else {
                var mat = BABYLON.Tmp.Matrix[0];
                var amat = this.getAbsoluteTransform();
                if (mesh) {
                    amat.multiplyToRef(mesh.getWorldMatrix(), mat);
                }
                else {
                    mat.copyFrom(amat);
                }
                mat.m[0] *= this._scalingDeterminant;
                mat.m[1] *= this._scalingDeterminant;
                mat.m[2] *= this._scalingDeterminant;
                mat.getRotationMatrixToRef(result);
            }
        };
        Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
            var result = BABYLON.Vector3.Zero();
            this.getAbsolutePositionFromLocalToRef(position, mesh, result);
            return result;
        };
        Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
            this._skeleton.computeAbsoluteTransforms();
            var tmat = BABYLON.Tmp.Matrix[0];
            if (mesh) {
                tmat.copyFrom(this.getAbsoluteTransform());
                tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
            }
            else {
                tmat = this.getAbsoluteTransform();
            }
            BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
        };
        Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
            var result = BABYLON.Vector3.Zero();
            this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
            return result;
        };
        Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
            this._skeleton.computeAbsoluteTransforms();
            var tmat = BABYLON.Tmp.Matrix[0];
            tmat.copyFrom(this.getAbsoluteTransform());
            if (mesh) {
                tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
            }
            tmat.invert();
            BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
        };
        return Bone;
    }(BABYLON.Node));
    BABYLON.Bone = Bone;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.bone.js.map
 
var BABYLON;
(function (BABYLON) {
    var BoneIKController = (function () {
        function BoneIKController(mesh, bone, options) {
            this.targetPosition = BABYLON.Vector3.Zero();
            this.poleTargetPosition = BABYLON.Vector3.Zero();
            this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
            this.poleAngle = 0;
            this.slerpAmount = 1;
            this._bone1Quat = BABYLON.Quaternion.Identity();
            this._bone1Mat = BABYLON.Matrix.Identity();
            this._bone2Ang = Math.PI;
            this._maxAngle = Math.PI;
            this._tmpVec1 = BABYLON.Vector3.Zero();
            this._tmpVec2 = BABYLON.Vector3.Zero();
            this._tmpVec3 = BABYLON.Vector3.Zero();
            this._tmpVec4 = BABYLON.Vector3.Zero();
            this._tmpVec5 = BABYLON.Vector3.Zero();
            this._tmpMat1 = BABYLON.Matrix.Identity();
            this._tmpMat2 = BABYLON.Matrix.Identity();
            this._tmpQuat1 = BABYLON.Quaternion.Identity();
            this._rightHandedSystem = false;
            this._bendAxis = BABYLON.Vector3.Right();
            this._slerping = false;
            this._bone2 = bone;
            this._bone1 = bone.getParent();
            this.mesh = mesh;
            if (bone.getAbsoluteTransform().determinant() > 0) {
                this._rightHandedSystem = true;
                this._bendAxis.x = 0;
                this._bendAxis.y = 0;
                this._bendAxis.z = 1;
            }
            if (this._bone1.length) {
                var boneScale1 = this._bone1.getScale();
                var boneScale2 = this._bone2.getScale();
                this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
                this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
            }
            else if (this._bone1.children[0]) {
                mesh.computeWorldMatrix(true);
                var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
                var pos2 = this._bone2.getAbsolutePosition(mesh);
                var pos3 = this._bone1.getAbsolutePosition(mesh);
                this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
                this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
            }
            this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
            this.maxAngle = Math.PI;
            if (options) {
                if (options.targetMesh) {
                    this.targetMesh = options.targetMesh;
                    this.targetMesh.computeWorldMatrix(true);
                }
                if (options.poleTargetMesh) {
                    this.poleTargetMesh = options.poleTargetMesh;
                    this.poleTargetMesh.computeWorldMatrix(true);
                }
                else if (options.poleTargetBone) {
                    this.poleTargetBone = options.poleTargetBone;
                }
                else if (this._bone1.getParent()) {
                    this.poleTargetBone = this._bone1.getParent();
                }
                if (options.poleTargetLocalOffset) {
                    this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
                }
                if (options.poleAngle) {
                    this.poleAngle = options.poleAngle;
                }
                if (options.bendAxis) {
                    this._bendAxis.copyFrom(options.bendAxis);
                }
                if (options.maxAngle) {
                    this.maxAngle = options.maxAngle;
                }
                if (options.slerpAmount) {
                    this.slerpAmount = options.slerpAmount;
                }
            }
        }
        Object.defineProperty(BoneIKController.prototype, "maxAngle", {
            get: function () {
                return this._maxAngle;
            },
            set: function (value) {
                this._setMaxAngle(value);
            },
            enumerable: true,
            configurable: true
        });
        BoneIKController.prototype._setMaxAngle = function (ang) {
            if (ang < 0) {
                ang = 0;
            }
            if (ang > Math.PI || ang == undefined) {
                ang = Math.PI;
            }
            this._maxAngle = ang;
            var a = this._bone1Length;
            var b = this._bone2Length;
            this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
        };
        BoneIKController.prototype.update = function () {
            var bone1 = this._bone1;
            var target = this.targetPosition;
            var poleTarget = this.poleTargetPosition;
            var mat1 = this._tmpMat1;
            var mat2 = this._tmpMat2;
            if (this.targetMesh) {
                target.copyFrom(this.targetMesh.getAbsolutePosition());
            }
            if (this.poleTargetBone) {
                this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
            }
            else if (this.poleTargetMesh) {
                BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
            }
            var bonePos = this._tmpVec1;
            var zaxis = this._tmpVec2;
            var xaxis = this._tmpVec3;
            var yaxis = this._tmpVec4;
            var upAxis = this._tmpVec5;
            bone1.getAbsolutePositionToRef(this.mesh, bonePos);
            poleTarget.subtractToRef(bonePos, upAxis);
            if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
                upAxis.y = 1;
            }
            else {
                upAxis.normalize();
            }
            target.subtractToRef(bonePos, yaxis);
            yaxis.normalize();
            BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
            zaxis.normalize();
            BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
            xaxis.normalize();
            BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
            var a = this._bone1Length;
            var b = this._bone2Length;
            var c = BABYLON.Vector3.Distance(bonePos, target);
            if (this._maxReach > 0) {
                c = Math.min(this._maxReach, c);
            }
            var acosa = (b * b + c * c - a * a) / (2 * b * c);
            var acosb = (c * c + a * a - b * b) / (2 * c * a);
            if (acosa > 1) {
                acosa = 1;
            }
            if (acosb > 1) {
                acosb = 1;
            }
            if (acosa < -1) {
                acosa = -1;
            }
            if (acosb < -1) {
                acosb = -1;
            }
            var angA = Math.acos(acosa);
            var angB = Math.acos(acosb);
            var angC = -angA - angB;
            if (this._rightHandedSystem) {
                BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
                mat2.multiplyToRef(mat1, mat1);
                BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
                mat2.multiplyToRef(mat1, mat1);
            }
            else {
                this._tmpVec1.copyFrom(this._bendAxis);
                this._tmpVec1.x *= -1;
                BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
                mat2.multiplyToRef(mat1, mat1);
            }
            if (this.poleAngle) {
                BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
                mat1.multiplyToRef(mat2, mat1);
            }
            if (this.slerpAmount < 1) {
                if (!this._slerping) {
                    BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
                }
                BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
                BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
                angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
                this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
                this._slerping = true;
            }
            else {
                this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
                this._bone1Mat.copyFrom(mat1);
                this._slerping = false;
            }
            this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
            this._bone2Ang = angC;
        };
        return BoneIKController;
    }());
    BABYLON.BoneIKController = BoneIKController;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boneIKController.js.map
 
var BABYLON;
(function (BABYLON) {
    var BoneLookController = (function () {
        function BoneLookController(mesh, bone, target, options) {
            this.upAxis = BABYLON.Vector3.Up();
            this.adjustYaw = 0;
            this.adjustPitch = 0;
            this.adjustRoll = 0;
            this._tmpVec1 = BABYLON.Vector3.Zero();
            this._tmpVec2 = BABYLON.Vector3.Zero();
            this._tmpVec3 = BABYLON.Vector3.Zero();
            this._tmpVec4 = BABYLON.Vector3.Zero();
            this._tmpMat1 = BABYLON.Matrix.Identity();
            this._tmpMat2 = BABYLON.Matrix.Identity();
            this.mesh = mesh;
            this.bone = bone;
            this.target = target;
            if (options) {
                if (options.adjustYaw) {
                    this.adjustYaw = options.adjustYaw;
                }
                if (options.adjustPitch) {
                    this.adjustPitch = options.adjustPitch;
                }
                if (options.adjustRoll) {
                    this.adjustRoll = options.adjustRoll;
                }
            }
        }
        BoneLookController.prototype.update = function () {
            var bone = this.bone;
            var target = this.target;
            var bonePos = this._tmpVec1;
            var zaxis = this._tmpVec2;
            var xaxis = this._tmpVec3;
            var yaxis = this._tmpVec4;
            var mat1 = this._tmpMat1;
            var mat2 = this._tmpMat2;
            bone.getAbsolutePositionToRef(this.mesh, bonePos);
            target.subtractToRef(bonePos, zaxis);
            zaxis.normalize();
            BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
            xaxis.normalize();
            BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
            yaxis.normalize();
            BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
            if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
                BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
                mat2.multiplyToRef(mat1, mat1);
            }
            this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
        };
        return BoneLookController;
    }());
    BABYLON.BoneLookController = BoneLookController;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boneLookController.js.map
 
var BABYLON;
(function (BABYLON) {
    var Skeleton = (function () {
        function Skeleton(name, id, scene) {
            this.name = name;
            this.id = id;
            this.bones = new Array();
            this.needInitialSkinMatrix = false;
            this._isDirty = true;
            this._meshesWithPoseMatrix = new Array();
            this._identity = BABYLON.Matrix.Identity();
            this._ranges = {};
            this._lastAbsoluteTransformsUpdateId = -1;
            this.bones = [];
            this._scene = scene;
            scene.skeletons.push(this);
            //make sure it will recalculate the matrix next time prepare is called.
            this._isDirty = true;
        }
        // Members
        Skeleton.prototype.getTransformMatrices = function (mesh) {
            if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
                return mesh._bonesTransformMatrices;
            }
            return this._transformMatrices;
        };
        Skeleton.prototype.getScene = function () {
            return this._scene;
        };
        // Methods
        /**
         * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
         */
        Skeleton.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
            ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
            if (fullDetails) {
                ret += ", Ranges: {";
                var first = true;
                for (var name_1 in this._ranges) {
                    if (first) {
                        ret += ", ";
                        first = false;
                    }
                    ret += name_1;
                }
                ret += "}";
            }
            return ret;
        };
        /**
        * Get bone's index searching by name
        * @param {string} name is bone's name to search for
        * @return {number} Indice of the bone. Returns -1 if not found
        */
        Skeleton.prototype.getBoneIndexByName = function (name) {
            for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
                if (this.bones[boneIndex].name === name) {
                    return boneIndex;
                }
            }
            return -1;
        };
        Skeleton.prototype.createAnimationRange = function (name, from, to) {
            // check name not already in use
            if (!this._ranges[name]) {
                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
                for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
                    if (this.bones[i].animations[0]) {
                        this.bones[i].animations[0].createRange(name, from, to);
                    }
                }
            }
        };
        Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
            if (deleteFrames === void 0) { deleteFrames = true; }
            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
                if (this.bones[i].animations[0]) {
                    this.bones[i].animations[0].deleteRange(name, deleteFrames);
                }
            }
            this._ranges[name] = undefined; // said much faster than 'delete this._range[name]' 
        };
        Skeleton.prototype.getAnimationRange = function (name) {
            return this._ranges[name];
        };
        /**
         *  Returns as an Array, all AnimationRanges defined on this skeleton
         */
        Skeleton.prototype.getAnimationRanges = function () {
            var animationRanges = [];
            var name;
            var i = 0;
            for (name in this._ranges) {
                animationRanges[i] = this._ranges[name];
                i++;
            }
            return animationRanges;
        };
        /**
         *  note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
         */
        Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
            if (this._ranges[name] || !source.getAnimationRange(name)) {
                return false;
            }
            var ret = true;
            var frameOffset = this._getHighestAnimationFrame() + 1;
            // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
            var boneDict = {};
            var sourceBones = source.bones;
            var nBones;
            var i;
            for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
                boneDict[sourceBones[i].name] = sourceBones[i];
            }
            if (this.bones.length !== sourceBones.length) {
                BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
                ret = false;
            }
            var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
            for (i = 0, nBones = this.bones.length; i < nBones; i++) {
                var boneName = this.bones[i].name;
                var sourceBone = boneDict[boneName];
                if (sourceBone) {
                    ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
                }
                else {
                    BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
                    ret = false;
                }
            }
            // do not call createAnimationRange(), since it also is done to bones, which was already done
            var range = source.getAnimationRange(name);
            this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
            return ret;
        };
        Skeleton.prototype.returnToRest = function () {
            for (var index = 0; index < this.bones.length; index++) {
                this.bones[index].returnToRest();
            }
        };
        Skeleton.prototype._getHighestAnimationFrame = function () {
            var ret = 0;
            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
                if (this.bones[i].animations[0]) {
                    var highest = this.bones[i].animations[0].getHighestFrame();
                    if (ret < highest) {
                        ret = highest;
                    }
                }
            }
            return ret;
        };
        Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
            var range = this.getAnimationRange(name);
            if (!range) {
                return null;
            }
            return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
        };
        Skeleton.prototype._markAsDirty = function () {
            this._isDirty = true;
        };
        Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
            this._meshesWithPoseMatrix.push(mesh);
        };
        Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
            var index = this._meshesWithPoseMatrix.indexOf(mesh);
            if (index > -1) {
                this._meshesWithPoseMatrix.splice(index, 1);
            }
        };
        Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
            for (var index = 0; index < this.bones.length; index++) {
                var bone = this.bones[index];
                var parentBone = bone.getParent();
                if (parentBone) {
                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
                }
                else {
                    if (initialSkinMatrix) {
                        bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
                    }
                    else {
                        bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
                    }
                }
                bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
            }
            this._identity.copyToArray(targetMatrix, this.bones.length * 16);
        };
        Skeleton.prototype.prepare = function () {
            if (!this._isDirty) {
                return;
            }
            if (this.needInitialSkinMatrix) {
                for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
                    var mesh = this._meshesWithPoseMatrix[index];
                    if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
                        mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
                    }
                    var poseMatrix = mesh.getPoseMatrix();
                    // Prepare bones
                    for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
                        var bone = this.bones[boneIndex];
                        if (!bone.getParent()) {
                            var matrix = bone.getBaseMatrix();
                            matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
                            bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
                        }
                    }
                    this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
                }
            }
            else {
                if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
                    this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
                }
                this._computeTransformMatrices(this._transformMatrices, null);
            }
            this._isDirty = false;
            this._scene._activeBones.addCount(this.bones.length, false);
        };
        Skeleton.prototype.getAnimatables = function () {
            if (!this._animatables || this._animatables.length !== this.bones.length) {
                this._animatables = [];
                for (var index = 0; index < this.bones.length; index++) {
                    this._animatables.push(this.bones[index]);
                }
            }
            return this._animatables;
        };
        Skeleton.prototype.clone = function (name, id) {
            var result = new Skeleton(name, id || name, this._scene);
            result.needInitialSkinMatrix = this.needInitialSkinMatrix;
            for (var index = 0; index < this.bones.length; index++) {
                var source = this.bones[index];
                var parentBone = null;
                if (source.getParent()) {
                    var parentIndex = this.bones.indexOf(source.getParent());
                    parentBone = result.bones[parentIndex];
                }
                var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
            }
            if (this._ranges) {
                result._ranges = {};
                for (var rangeName in this._ranges) {
                    result._ranges[rangeName] = this._ranges[rangeName].clone();
                }
            }
            this._isDirty = true;
            return result;
        };
        Skeleton.prototype.enableBlending = function (blendingSpeed) {
            if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
            this.bones.forEach(function (bone) {
                bone.animations.forEach(function (animation) {
                    animation.enableBlending = true;
                    animation.blendingSpeed = blendingSpeed;
                });
            });
        };
        Skeleton.prototype.dispose = function () {
            this._meshesWithPoseMatrix = [];
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            this.getScene().removeSkeleton(this);
        };
        Skeleton.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.id = this.id;
            serializationObject.dimensionsAtRest = this.dimensionsAtRest;
            serializationObject.bones = [];
            serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
            for (var index = 0; index < this.bones.length; index++) {
                var bone = this.bones[index];
                var serializedBone = {
                    parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
                    name: bone.name,
                    matrix: bone.getLocalMatrix().toArray(),
                    rest: bone.getRestPose().toArray()
                };
                serializationObject.bones.push(serializedBone);
                if (bone.length) {
                    serializedBone.length = bone.length;
                }
                if (bone.animations && bone.animations.length > 0) {
                    serializedBone.animation = bone.animations[0].serialize();
                }
                serializationObject.ranges = [];
                for (var name in this._ranges) {
                    var range = {};
                    range.name = name;
                    range.from = this._ranges[name].from;
                    range.to = this._ranges[name].to;
                    serializationObject.ranges.push(range);
                }
            }
            return serializationObject;
        };
        Skeleton.Parse = function (parsedSkeleton, scene) {
            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
            if (parsedSkeleton.dimensionsAtRest) {
                skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
            }
            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
            var index;
            for (index = 0; index < parsedSkeleton.bones.length; index++) {
                var parsedBone = parsedSkeleton.bones[index];
                var parentBone = null;
                if (parsedBone.parentBoneIndex > -1) {
                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
                }
                var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
                var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
                if (parsedBone.length) {
                    bone.length = parsedBone.length;
                }
                if (parsedBone.animation) {
                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
                }
            }
            // placed after bones, so createAnimationRange can cascade down
            if (parsedSkeleton.ranges) {
                for (index = 0; index < parsedSkeleton.ranges.length; index++) {
                    var data = parsedSkeleton.ranges[index];
                    skeleton.createAnimationRange(data.name, data.from, data.to);
                }
            }
            return skeleton;
        };
        Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
            if (forceUpdate === void 0) { forceUpdate = false; }
            var renderId = this._scene.getRenderId();
            if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
                this.bones[0].computeAbsoluteTransforms();
                this._lastAbsoluteTransformsUpdateId = renderId;
            }
        };
        Skeleton.prototype.getPoseMatrix = function () {
            var poseMatrix;
            if (this._meshesWithPoseMatrix.length > 0) {
                poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
            }
            return poseMatrix;
        };
        return Skeleton;
    }());
    BABYLON.Skeleton = Skeleton;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.skeleton.js.map
 
var BABYLON;
(function (BABYLON) {
    var PostProcess = (function () {
        function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            this.name = name;
            this.width = -1;
            this.height = -1;
            /*
                Enable Pixel Perfect mode where texture is not scaled to be power of 2.
                Can only be used on a single postprocess or on the last one of a chain.
            */
            this.enablePixelPerfectMode = false;
            this._reusable = false;
            this._textures = new BABYLON.SmartArray(2);
            this._currentRenderTextureInd = 0;
            this._scaleRatio = new BABYLON.Vector2(1, 1);
            // Events
            /**
            * An event triggered when the postprocess is activated.
            * @type {BABYLON.Observable}
            */
            this.onActivateObservable = new BABYLON.Observable();
            /**
            * An event triggered when the postprocess changes its size.
            * @type {BABYLON.Observable}
            */
            this.onSizeChangedObservable = new BABYLON.Observable();
            /**
            * An event triggered when the postprocess applies its effect.
            * @type {BABYLON.Observable}
            */
            this.onApplyObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the postprocess
            * @type {BABYLON.Observable}
            */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the postprocess
            * @type {BABYLON.Observable}
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            if (camera != null) {
                this._camera = camera;
                this._scene = camera.getScene();
                camera.attachPostProcess(this);
                this._engine = this._scene.getEngine();
            }
            else {
                this._engine = engine;
            }
            this._options = options;
            this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
            this._reusable = reusable || false;
            this._textureType = textureType;
            this._samplers = samplers || [];
            this._samplers.push("textureSampler");
            this._fragmentUrl = fragmentUrl;
            this._parameters = parameters || [];
            this._parameters.push("scale");
            this.updateEffect(defines);
        }
        Object.defineProperty(PostProcess.prototype, "onActivate", {
            set: function (callback) {
                if (this._onActivateObserver) {
                    this.onActivateObservable.remove(this._onActivateObserver);
                }
                this._onActivateObserver = this.onActivateObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
            set: function (callback) {
                if (this._onSizeChangedObserver) {
                    this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
                }
                this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onApply", {
            set: function (callback) {
                if (this._onApplyObserver) {
                    this.onApplyObservable.remove(this._onApplyObserver);
                }
                this._onApplyObserver = this.onApplyObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onAfterRender", {
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        PostProcess.prototype.updateEffect = function (defines) {
            this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
        };
        PostProcess.prototype.isReusable = function () {
            return this._reusable;
        };
        /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
        PostProcess.prototype.markTextureDirty = function () {
            this.width = -1;
        };
        PostProcess.prototype.activate = function (camera, sourceTexture) {
            camera = camera || this._camera;
            var scene = camera.getScene();
            var maxSize = camera.getEngine().getCaps().maxTextureSize;
            var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
            var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
            var desiredWidth = this._options.width || requiredWidth;
            var desiredHeight = this._options.height || requiredHeight;
            if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
                if (!this._options.width) {
                    desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
                }
                if (!this._options.height) {
                    desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
                }
            }
            if (this.width !== desiredWidth || this.height !== desiredHeight) {
                if (this._textures.length > 0) {
                    for (var i = 0; i < this._textures.length; i++) {
                        this._engine._releaseTexture(this._textures.data[i]);
                    }
                    this._textures.reset();
                }
                this.width = desiredWidth;
                this.height = desiredHeight;
                var textureSize = { width: this.width, height: this.height };
                var textureOptions = {
                    generateMipMaps: false,
                    generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
                    generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
                    samplingMode: this.renderTargetSamplingMode,
                    type: this._textureType
                };
                this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
                if (this._reusable) {
                    this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
                }
                this.onSizeChangedObservable.notifyObservers(this);
            }
            if (this.enablePixelPerfectMode) {
                this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
                this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
            }
            else {
                this._scaleRatio.copyFromFloats(1, 1);
                this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
            }
            this.onActivateObservable.notifyObservers(camera);
            // Clear
            if (this.clearColor) {
                this._engine.clear(this.clearColor, true, true, true);
            }
            else {
                this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
            }
            if (this._reusable) {
                this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
            }
        };
        Object.defineProperty(PostProcess.prototype, "isSupported", {
            get: function () {
                return this._effect.isSupported;
            },
            enumerable: true,
            configurable: true
        });
        PostProcess.prototype.apply = function () {
            // Check
            if (!this._effect.isReady())
                return null;
            // States
            this._engine.enableEffect(this._effect);
            this._engine.setState(false);
            this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            this._engine.setDepthBuffer(false);
            this._engine.setDepthWrite(false);
            // Texture
            this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
            // Parameters
            this._effect.setVector2("scale", this._scaleRatio);
            this.onApplyObservable.notifyObservers(this._effect);
            return this._effect;
        };
        PostProcess.prototype.dispose = function (camera) {
            camera = camera || this._camera;
            if (this._textures.length > 0) {
                for (var i = 0; i < this._textures.length; i++) {
                    this._engine._releaseTexture(this._textures.data[i]);
                }
                this._textures.reset();
            }
            if (!camera) {
                return;
            }
            camera.detachPostProcess(this);
            var index = camera._postProcesses.indexOf(this);
            if (index === 0 && camera._postProcesses.length > 0) {
                this._camera._postProcesses[0].markTextureDirty();
            }
            this.onActivateObservable.clear();
            this.onAfterRenderObservable.clear();
            this.onApplyObservable.clear();
            this.onBeforeRenderObservable.clear();
            this.onSizeChangedObservable.clear();
        };
        return PostProcess;
    }());
    BABYLON.PostProcess = PostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.postProcess.js.map
 
var BABYLON;
(function (BABYLON) {
    var PostProcessManager = (function () {
        function PostProcessManager(scene) {
            this._vertexBuffers = {};
            this._scene = scene;
        }
        PostProcessManager.prototype._prepareBuffers = function () {
            if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
                return;
            }
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
        };
        // Methods
        PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
            var postProcesses = this._scene.activeCamera._postProcesses;
            if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
                return false;
            }
            postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
            return true;
        };
        PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
            var engine = this._scene.getEngine();
            for (var index = 0; index < postProcesses.length; index++) {
                if (index < postProcesses.length - 1) {
                    postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
                }
                else {
                    if (targetTexture) {
                        engine.bindFramebuffer(targetTexture);
                    }
                    else {
                        engine.restoreDefaultFramebuffer();
                    }
                }
                var pp = postProcesses[index];
                var effect = pp.apply();
                if (effect) {
                    pp.onBeforeRenderObservable.notifyObservers(effect);
                    // VBOs
                    this._prepareBuffers();
                    engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
                    // Draw order
                    engine.draw(true, 0, 6);
                    pp.onAfterRenderObservable.notifyObservers(effect);
                }
            }
            // Restore depth buffer
            engine.setDepthBuffer(true);
            engine.setDepthWrite(true);
        };
        PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
            postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
            if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
                return;
            }
            var engine = this._scene.getEngine();
            for (var index = 0, len = postProcesses.length; index < len; index++) {
                if (index < len - 1) {
                    postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
                }
                else {
                    if (targetTexture) {
                        engine.bindFramebuffer(targetTexture, faceIndex);
                    }
                    else {
                        engine.restoreDefaultFramebuffer();
                    }
                }
                if (doNotPresent) {
                    break;
                }
                var pp = postProcesses[index];
                var effect = pp.apply();
                if (effect) {
                    pp.onBeforeRenderObservable.notifyObservers(effect);
                    // VBOs
                    this._prepareBuffers();
                    engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
                    // Draw order
                    engine.draw(true, 0, 6);
                    pp.onAfterRenderObservable.notifyObservers(effect);
                }
            }
            // Restore depth buffer
            engine.setDepthBuffer(true);
            engine.setDepthWrite(true);
        };
        PostProcessManager.prototype.dispose = function () {
            var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
        };
        return PostProcessManager;
    }());
    BABYLON.PostProcessManager = PostProcessManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.postProcessManager.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var PassPostProcess = (function (_super) {
        __extends(PassPostProcess, _super);
        function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
            _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
        }
        return PassPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.PassPostProcess = PassPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.passPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * This is a holder class for the physics joint created by the physics plugin.
     * It holds a set of functions to control the underlying joint.
     */
    var PhysicsJoint = (function () {
        function PhysicsJoint(type, jointData) {
            this.type = type;
            this.jointData = jointData;
            jointData.nativeParams = jointData.nativeParams || {};
        }
        Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
            get: function () {
                return this._physicsJoint;
            },
            set: function (newJoint) {
                if (this._physicsJoint) {
                }
                this._physicsJoint = newJoint;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
            set: function (physicsPlugin) {
                this._physicsPlugin = physicsPlugin;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Execute a function that is physics-plugin specific.
         * @param {Function} func the function that will be executed.
         *                        It accepts two parameters: the physics world and the physics joint.
         */
        PhysicsJoint.prototype.executeNativeFunction = function (func) {
            func(this._physicsPlugin.world, this._physicsJoint);
        };
        //TODO check if the native joints are the same
        //Joint Types
        PhysicsJoint.DistanceJoint = 0;
        PhysicsJoint.HingeJoint = 1;
        PhysicsJoint.BallAndSocketJoint = 2;
        PhysicsJoint.WheelJoint = 3;
        PhysicsJoint.SliderJoint = 4;
        //OIMO
        PhysicsJoint.PrismaticJoint = 5;
        //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
        PhysicsJoint.UniversalJoint = 6;
        PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
        //Cannon
        //Similar to a Ball-Joint. Different in params
        PhysicsJoint.PointToPointJoint = 8;
        //Cannon only at the moment
        PhysicsJoint.SpringJoint = 9;
        PhysicsJoint.LockJoint = 10;
        return PhysicsJoint;
    }());
    BABYLON.PhysicsJoint = PhysicsJoint;
    /**
     * A class representing a physics distance joint.
     */
    var DistanceJoint = (function (_super) {
        __extends(DistanceJoint, _super);
        function DistanceJoint(jointData) {
            _super.call(this, PhysicsJoint.DistanceJoint, jointData);
        }
        /**
         * Update the predefined distance.
         */
        DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
            this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
        };
        return DistanceJoint;
    }(PhysicsJoint));
    BABYLON.DistanceJoint = DistanceJoint;
    var MotorEnabledJoint = (function (_super) {
        __extends(MotorEnabledJoint, _super);
        function MotorEnabledJoint(type, jointData) {
            _super.call(this, type, jointData);
        }
        /**
         * Set the motor values.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} force the force to apply
         * @param {number} maxForce max force for this motor.
         */
        MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
            this._physicsPlugin.setMotor(this, force, maxForce);
        };
        /**
         * Set the motor's limits.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         */
        MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
            this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
        };
        return MotorEnabledJoint;
    }(PhysicsJoint));
    BABYLON.MotorEnabledJoint = MotorEnabledJoint;
    /**
     * This class represents a single hinge physics joint
     */
    var HingeJoint = (function (_super) {
        __extends(HingeJoint, _super);
        function HingeJoint(jointData) {
            _super.call(this, PhysicsJoint.HingeJoint, jointData);
        }
        /**
         * Set the motor values.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} force the force to apply
         * @param {number} maxForce max force for this motor.
         */
        HingeJoint.prototype.setMotor = function (force, maxForce) {
            this._physicsPlugin.setMotor(this, force, maxForce);
        };
        /**
         * Set the motor's limits.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         */
        HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
            this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
        };
        return HingeJoint;
    }(MotorEnabledJoint));
    BABYLON.HingeJoint = HingeJoint;
    /**
     * This class represents a dual hinge physics joint (same as wheel joint)
     */
    var Hinge2Joint = (function (_super) {
        __extends(Hinge2Joint, _super);
        function Hinge2Joint(jointData) {
            _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
        }
        /**
         * Set the motor values.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} force the force to apply
         * @param {number} maxForce max force for this motor.
         * @param {motorIndex} the motor's index, 0 or 1.
         */
        Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
            if (motorIndex === void 0) { motorIndex = 0; }
            this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
        };
        /**
         * Set the motor limits.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} upperLimit the upper limit
         * @param {number} lowerLimit lower limit
         * @param {motorIndex} the motor's index, 0 or 1.
         */
        Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
            if (motorIndex === void 0) { motorIndex = 0; }
            this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
        };
        return Hinge2Joint;
    }(MotorEnabledJoint));
    BABYLON.Hinge2Joint = Hinge2Joint;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.physicsJoint.js.map
 
var BABYLON;
(function (BABYLON) {
    var PhysicsImpostor = (function () {
        function PhysicsImpostor(object, type, _options, _scene) {
            var _this = this;
            if (_options === void 0) { _options = { mass: 0 }; }
            this.object = object;
            this.type = type;
            this._options = _options;
            this._scene = _scene;
            this._bodyUpdateRequired = false;
            this._onBeforePhysicsStepCallbacks = new Array();
            this._onAfterPhysicsStepCallbacks = new Array();
            this._onPhysicsCollideCallbacks = [];
            this._deltaPosition = BABYLON.Vector3.Zero();
            this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
            this._tmpRotationWithDelta = new BABYLON.Quaternion();
            /**
             * this function is executed by the physics engine.
             */
            this.beforeStep = function () {
                _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
                //conjugate deltaRotation
                if (_this._deltaRotationConjugated) {
                    _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
                }
                else {
                    _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
                }
                _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
                _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
                    func(_this);
                });
            };
            /**
             * this function is executed by the physics engine.
             */
            this.afterStep = function () {
                _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
                    func(_this);
                });
                _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
                _this.object.position.addInPlace(_this._deltaPosition);
                if (_this._deltaRotation) {
                    _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
                }
            };
            //event and body object due to cannon's event-based architecture.
            this.onCollide = function (e) {
                if (!_this._onPhysicsCollideCallbacks.length)
                    return;
                var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
                if (otherImpostor) {
                    _this._onPhysicsCollideCallbacks.filter(function (obj) {
                        return obj.otherImpostors.indexOf(otherImpostor) !== -1;
                    }).forEach(function (obj) {
                        obj.callback(_this, otherImpostor);
                    });
                }
            };
            //sanity check!
            if (!this.object) {
                BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
                return;
            }
            //legacy support for old syntax.
            if (!this._scene && object.getScene) {
                this._scene = object.getScene();
            }
            this._physicsEngine = this._scene.getPhysicsEngine();
            if (!this._physicsEngine) {
                BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
            }
            else {
                //set the object's quaternion, if not set
                if (!this.object.rotationQuaternion) {
                    if (this.object.rotation) {
                        this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
                    }
                    else {
                        this.object.rotationQuaternion = new BABYLON.Quaternion();
                    }
                }
                //default options params
                this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
                this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
                this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
                this._joints = [];
                //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
                if (!this.object.parent) {
                    this._init();
                }
            }
        }
        /**
         * This function will completly initialize this impostor.
         * It will create a new body - but only if this mesh has no parent.
         * If it has, this impostor will not be used other than to define the impostor
         * of the child mesh.
         */
        PhysicsImpostor.prototype._init = function () {
            this._physicsEngine.removeImpostor(this);
            this.physicsBody = null;
            this._parent = this._parent || this._getPhysicsParent();
            if (!this.parent) {
                this._physicsEngine.addImpostor(this);
            }
        };
        PhysicsImpostor.prototype._getPhysicsParent = function () {
            if (this.object.parent instanceof BABYLON.AbstractMesh) {
                var parentMesh = this.object.parent;
                return parentMesh.physicsImpostor;
            }
            return;
        };
        /**
         * Should a new body be generated.
         */
        PhysicsImpostor.prototype.isBodyInitRequired = function () {
            return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
        };
        PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
            this.forceUpdate();
        };
        /**
         * Force a regeneration of this or the parent's impostor's body.
         * Use under cautious - This will remove all joints already implemented.
         */
        PhysicsImpostor.prototype.forceUpdate = function () {
            this._init();
            if (this.parent) {
                this.parent.forceUpdate();
            }
        };
        Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
            /*public get mesh(): AbstractMesh {
                return this._mesh;
            }*/
            /**
             * Gets the body that holds this impostor. Either its own, or its parent.
             */
            get: function () {
                return this._parent ? this._parent.physicsBody : this._physicsBody;
            },
            /**
             * Set the physics body. Used mainly by the physics engine/plugin
             */
            set: function (physicsBody) {
                if (this._physicsBody) {
                    this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
                }
                this._physicsBody = physicsBody;
                this.resetUpdateFlags();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsImpostor.prototype, "parent", {
            get: function () {
                return this._parent;
            },
            set: function (value) {
                this._parent = value;
            },
            enumerable: true,
            configurable: true
        });
        PhysicsImpostor.prototype.resetUpdateFlags = function () {
            this._bodyUpdateRequired = false;
        };
        PhysicsImpostor.prototype.getObjectExtendSize = function () {
            if (this.object.getBoundingInfo) {
                this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
                return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
            }
            else {
                return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
            }
        };
        PhysicsImpostor.prototype.getObjectCenter = function () {
            if (this.object.getBoundingInfo) {
                return this.object.getBoundingInfo().boundingBox.center;
            }
            else {
                return this.object.position;
            }
        };
        /**
         * Get a specific parametes from the options parameter.
         */
        PhysicsImpostor.prototype.getParam = function (paramName) {
            return this._options[paramName];
        };
        /**
         * Sets a specific parameter in the options given to the physics plugin
         */
        PhysicsImpostor.prototype.setParam = function (paramName, value) {
            this._options[paramName] = value;
            this._bodyUpdateRequired = true;
        };
        /**
         * Specifically change the body's mass option. Won't recreate the physics body object
         */
        PhysicsImpostor.prototype.setMass = function (mass) {
            if (this.getParam("mass") !== mass) {
                this.setParam("mass", mass);
            }
            this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
        };
        PhysicsImpostor.prototype.getLinearVelocity = function () {
            return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
        };
        /**
         * Set the body's linear velocity.
         */
        PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
            this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
        };
        PhysicsImpostor.prototype.getAngularVelocity = function () {
            return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
        };
        /**
         * Set the body's linear velocity.
         */
        PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
            this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
        };
        /**
         * Execute a function with the physics plugin native code.
         * Provide a function the will have two variables - the world object and the physics body object.
         */
        PhysicsImpostor.prototype.executeNativeFunction = function (func) {
            func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
        };
        /**
         * Register a function that will be executed before the physics world is stepping forward.
         */
        PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
            this._onBeforePhysicsStepCallbacks.push(func);
        };
        PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
            var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
            if (index > -1) {
                this._onBeforePhysicsStepCallbacks.splice(index, 1);
            }
            else {
                BABYLON.Tools.Warn("Function to remove was not found");
            }
        };
        /**
         * Register a function that will be executed after the physics step
         */
        PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
            this._onAfterPhysicsStepCallbacks.push(func);
        };
        PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
            var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
            if (index > -1) {
                this._onAfterPhysicsStepCallbacks.splice(index, 1);
            }
            else {
                BABYLON.Tools.Warn("Function to remove was not found");
            }
        };
        /**
         * register a function that will be executed when this impostor collides against a different body.
         */
        PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
            var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
            this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
        };
        PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
            var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
            var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
            if (index > -1) {
                this._onPhysicsCollideCallbacks.splice(index, 1);
            }
            else {
                BABYLON.Tools.Warn("Function to remove was not found");
            }
        };
        /**
         * Apply a force
         */
        PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
            this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
        };
        /**
         * Apply an impulse
         */
        PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
            this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
        };
        /**
         * A help function to create a joint.
         */
        PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
            var joint = new BABYLON.PhysicsJoint(jointType, jointData);
            this.addJoint(otherImpostor, joint);
        };
        /**
         * Add a joint to this impostor with a different impostor.
         */
        PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
            this._joints.push({
                otherImpostor: otherImpostor,
                joint: joint
            });
            this._physicsEngine.addJoint(this, otherImpostor, joint);
        };
        /**
         * Will keep this body still, in a sleep mode.
         */
        PhysicsImpostor.prototype.sleep = function () {
            this._physicsEngine.getPhysicsPlugin().sleepBody(this);
        };
        /**
         * Wake the body up.
         */
        PhysicsImpostor.prototype.wakeUp = function () {
            this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
        };
        PhysicsImpostor.prototype.clone = function (newObject) {
            if (!newObject)
                return null;
            return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
        };
        PhysicsImpostor.prototype.dispose = function () {
            var _this = this;
            //no dispose if no physics engine is available.
            if (!this._physicsEngine) {
                return;
            }
            this._joints.forEach(function (j) {
                _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
            });
            //dispose the physics body
            this._physicsEngine.removeImpostor(this);
            if (this.parent) {
                this.parent.forceUpdate();
            }
            else {
            }
        };
        PhysicsImpostor.prototype.setDeltaPosition = function (position) {
            this._deltaPosition.copyFrom(position);
        };
        PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
            if (!this._deltaRotation) {
                this._deltaRotation = new BABYLON.Quaternion();
            }
            this._deltaRotation.copyFrom(rotation);
            this._deltaRotationConjugated = this._deltaRotation.conjugate();
        };
        PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
        //Impostor types
        PhysicsImpostor.NoImpostor = 0;
        PhysicsImpostor.SphereImpostor = 1;
        PhysicsImpostor.BoxImpostor = 2;
        PhysicsImpostor.PlaneImpostor = 3;
        PhysicsImpostor.MeshImpostor = 4;
        PhysicsImpostor.CylinderImpostor = 7;
        PhysicsImpostor.ParticleImpostor = 8;
        PhysicsImpostor.HeightmapImpostor = 9;
        return PhysicsImpostor;
    }());
    BABYLON.PhysicsImpostor = PhysicsImpostor;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.physicsImpostor.js.map
 
var BABYLON;
(function (BABYLON) {
    var PhysicsEngine = (function () {
        function PhysicsEngine(gravity, _physicsPlugin) {
            if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
            this._physicsPlugin = _physicsPlugin;
            //new methods and parameters
            this._impostors = [];
            this._joints = [];
            if (!this._physicsPlugin.isSupported()) {
                throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
                    + "Please make sure it is included.");
            }
            gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
            this.setGravity(gravity);
            this.setTimeStep();
        }
        PhysicsEngine.prototype.setGravity = function (gravity) {
            this.gravity = gravity;
            this._physicsPlugin.setGravity(this.gravity);
        };
        /**
         * Set the time step of the physics engine.
         * default is 1/60.
         * To slow it down, enter 1/600 for example.
         * To speed it up, 1/30
         * @param {number} newTimeStep the new timestep to apply to this world.
         */
        PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
            if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
            this._physicsPlugin.setTimeStep(newTimeStep);
        };
        PhysicsEngine.prototype.dispose = function () {
            this._impostors.forEach(function (impostor) {
                impostor.dispose();
            });
            this._physicsPlugin.dispose();
        };
        PhysicsEngine.prototype.getPhysicsPluginName = function () {
            return this._physicsPlugin.name;
        };
        /**
         * Adding a new impostor for the impostor tracking.
         * This will be done by the impostor itself.
         * @param {PhysicsImpostor} impostor the impostor to add
         */
        PhysicsEngine.prototype.addImpostor = function (impostor) {
            impostor.uniqueId = this._impostors.push(impostor);
            //if no parent, generate the body
            if (!impostor.parent) {
                this._physicsPlugin.generatePhysicsBody(impostor);
            }
        };
        /**
         * Remove an impostor from the engine.
         * This impostor and its mesh will not longer be updated by the physics engine.
         * @param {PhysicsImpostor} impostor the impostor to remove
         */
        PhysicsEngine.prototype.removeImpostor = function (impostor) {
            var index = this._impostors.indexOf(impostor);
            if (index > -1) {
                var removed = this._impostors.splice(index, 1);
                //Is it needed?
                if (removed.length) {
                    //this will also remove it from the world.
                    removed[0].physicsBody = null;
                }
            }
        };
        /**
         * Add a joint to the physics engine
         * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
         * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
         * @param {PhysicsJoint} the joint that will connect both impostors.
         */
        PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
            var impostorJoint = {
                mainImpostor: mainImpostor,
                connectedImpostor: connectedImpostor,
                joint: joint
            };
            joint.physicsPlugin = this._physicsPlugin;
            this._joints.push(impostorJoint);
            this._physicsPlugin.generateJoint(impostorJoint);
        };
        PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
            var matchingJoints = this._joints.filter(function (impostorJoint) {
                return (impostorJoint.connectedImpostor === connectedImpostor
                    && impostorJoint.joint === joint
                    && impostorJoint.mainImpostor === mainImpostor);
            });
            if (matchingJoints.length) {
                this._physicsPlugin.removeJoint(matchingJoints[0]);
            }
        };
        /**
         * Called by the scene. no need to call it.
         */
        PhysicsEngine.prototype._step = function (delta) {
            var _this = this;
            //check if any mesh has no body / requires an update
            this._impostors.forEach(function (impostor) {
                if (impostor.isBodyInitRequired()) {
                    _this._physicsPlugin.generatePhysicsBody(impostor);
                }
            });
            if (delta > 0.1) {
                delta = 0.1;
            }
            else if (delta <= 0) {
                delta = 1.0 / 60.0;
            }
            this._physicsPlugin.executeStep(delta, this._impostors);
        };
        PhysicsEngine.prototype.getPhysicsPlugin = function () {
            return this._physicsPlugin;
        };
        PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
            for (var i = 0; i < this._impostors.length; ++i) {
                if (this._impostors[i].object === object) {
                    return this._impostors[i];
                }
            }
        };
        PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
            for (var i = 0; i < this._impostors.length; ++i) {
                if (this._impostors[i].physicsBody === body) {
                    return this._impostors[i];
                }
            }
        };
        // Statics, Legacy support.
        /**
         * @Deprecated
         *
         */
        PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
        PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
        PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
        PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
        PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
        PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
        PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
        PhysicsEngine.CapsuleImpostor = -1;
        PhysicsEngine.ConeImpostor = -1;
        PhysicsEngine.ConvexHullImpostor = -1;
        PhysicsEngine.Epsilon = 0.001;
        return PhysicsEngine;
    }());
    BABYLON.PhysicsEngine = PhysicsEngine;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.physicsEngine.js.map
 
var BABYLON;
(function (BABYLON) {
    var VertexData = (function () {
        function VertexData() {
        }
        VertexData.prototype.set = function (data, kind) {
            switch (kind) {
                case BABYLON.VertexBuffer.PositionKind:
                    this.positions = data;
                    break;
                case BABYLON.VertexBuffer.NormalKind:
                    this.normals = data;
                    break;
                case BABYLON.VertexBuffer.UVKind:
                    this.uvs = data;
                    break;
                case BABYLON.VertexBuffer.UV2Kind:
                    this.uvs2 = data;
                    break;
                case BABYLON.VertexBuffer.UV3Kind:
                    this.uvs3 = data;
                    break;
                case BABYLON.VertexBuffer.UV4Kind:
                    this.uvs4 = data;
                    break;
                case BABYLON.VertexBuffer.UV5Kind:
                    this.uvs5 = data;
                    break;
                case BABYLON.VertexBuffer.UV6Kind:
                    this.uvs6 = data;
                    break;
                case BABYLON.VertexBuffer.ColorKind:
                    this.colors = data;
                    break;
                case BABYLON.VertexBuffer.MatricesIndicesKind:
                    this.matricesIndices = data;
                    break;
                case BABYLON.VertexBuffer.MatricesWeightsKind:
                    this.matricesWeights = data;
                    break;
                case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
                    this.matricesIndicesExtra = data;
                    break;
                case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
                    this.matricesWeightsExtra = data;
                    break;
            }
        };
        VertexData.prototype.applyToMesh = function (mesh, updatable) {
            this._applyTo(mesh, updatable);
        };
        VertexData.prototype.applyToGeometry = function (geometry, updatable) {
            this._applyTo(geometry, updatable);
        };
        VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
            this._update(mesh);
        };
        VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
            this._update(geometry);
        };
        VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
            if (this.positions) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
            }
            if (this.normals) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
            }
            if (this.uvs) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
            }
            if (this.uvs2) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
            }
            if (this.uvs3) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
            }
            if (this.uvs4) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
            }
            if (this.uvs5) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
            }
            if (this.uvs6) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
            }
            if (this.colors) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
            }
            if (this.matricesIndices) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
            }
            if (this.matricesWeights) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
            }
            if (this.matricesIndicesExtra) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
            }
            if (this.matricesWeightsExtra) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
            }
            if (this.indices) {
                meshOrGeometry.setIndices(this.indices);
            }
        };
        VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
            if (this.positions) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
            }
            if (this.normals) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
            }
            if (this.uvs) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
            }
            if (this.uvs2) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
            }
            if (this.uvs3) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
            }
            if (this.uvs4) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
            }
            if (this.uvs5) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
            }
            if (this.uvs6) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
            }
            if (this.colors) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
            }
            if (this.matricesIndices) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
            }
            if (this.matricesWeights) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
            }
            if (this.matricesIndicesExtra) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
            }
            if (this.matricesWeightsExtra) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
            }
            if (this.indices) {
                meshOrGeometry.setIndices(this.indices);
            }
        };
        VertexData.prototype.transform = function (matrix) {
            var transformed = BABYLON.Vector3.Zero();
            var index;
            if (this.positions) {
                var position = BABYLON.Vector3.Zero();
                for (index = 0; index < this.positions.length; index += 3) {
                    BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
                    BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
                    this.positions[index] = transformed.x;
                    this.positions[index + 1] = transformed.y;
                    this.positions[index + 2] = transformed.z;
                }
            }
            if (this.normals) {
                var normal = BABYLON.Vector3.Zero();
                for (index = 0; index < this.normals.length; index += 3) {
                    BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
                    BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
                    this.normals[index] = transformed.x;
                    this.normals[index + 1] = transformed.y;
                    this.normals[index + 2] = transformed.z;
                }
            }
        };
        VertexData.prototype.merge = function (other) {
            if (other.indices) {
                if (!this.indices) {
                    this.indices = [];
                }
                var offset = this.positions ? this.positions.length / 3 : 0;
                for (var index = 0; index < other.indices.length; index++) {
                    //TODO check type - if Int32Array!
                    this.indices.push(other.indices[index] + offset);
                }
            }
            this.positions = this._mergeElement(this.positions, other.positions);
            this.normals = this._mergeElement(this.normals, other.normals);
            this.uvs = this._mergeElement(this.uvs, other.uvs);
            this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
            this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
            this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
            this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
            this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
            this.colors = this._mergeElement(this.colors, other.colors);
            this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
            this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
            this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
            this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
        };
        VertexData.prototype._mergeElement = function (source, other) {
            if (!other)
                return source;
            if (!source)
                return other;
            var len = other.length + source.length;
            var isSrcTypedArray = source instanceof Float32Array;
            var isOthTypedArray = other instanceof Float32Array;
            // use non-loop method when the source is Float32Array
            if (isSrcTypedArray) {
                var ret32 = new Float32Array(len);
                ret32.set(source);
                ret32.set(other, source.length);
                return ret32;
            }
            else if (!isOthTypedArray) {
                return source.concat(other);
            }
            else {
                var ret = source.slice(0); // copy source to a separate array
                for (var i = 0, len = other.length; i < len; i++) {
                    ret.push(other[i]);
                }
                return ret;
            }
        };
        VertexData.prototype.serialize = function () {
            var serializationObject = this.serialize();
            if (this.positions) {
                serializationObject.positions = this.positions;
            }
            if (this.normals) {
                serializationObject.normals = this.normals;
            }
            if (this.uvs) {
                serializationObject.uvs = this.uvs;
            }
            if (this.uvs2) {
                serializationObject.uvs2 = this.uvs2;
            }
            if (this.uvs3) {
                serializationObject.uvs3 = this.uvs3;
            }
            if (this.uvs4) {
                serializationObject.uvs4 = this.uvs4;
            }
            if (this.uvs5) {
                serializationObject.uvs5 = this.uvs5;
            }
            if (this.uvs6) {
                serializationObject.uvs6 = this.uvs6;
            }
            if (this.colors) {
                serializationObject.colors = this.colors;
            }
            if (this.matricesIndices) {
                serializationObject.matricesIndices = this.matricesIndices;
                serializationObject.matricesIndices._isExpanded = true;
            }
            if (this.matricesWeights) {
                serializationObject.matricesWeights = this.matricesWeights;
            }
            if (this.matricesIndicesExtra) {
                serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
                serializationObject.matricesIndicesExtra._isExpanded = true;
            }
            if (this.matricesWeightsExtra) {
                serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
            }
            serializationObject.indices = this.indices;
            return serializationObject;
        };
        // Statics
        VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
            return VertexData._ExtractFrom(mesh, copyWhenShared);
        };
        VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
            return VertexData._ExtractFrom(geometry, copyWhenShared);
        };
        VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
            var result = new VertexData();
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
                result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
                result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
                result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
                result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
                result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
                result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
            }
            result.indices = meshOrGeometry.getIndices(copyWhenShared);
            return result;
        };
        VertexData.CreateRibbon = function (options) {
            var pathArray = options.pathArray;
            var closeArray = options.closeArray || false;
            var closePath = options.closePath || false;
            var invertUV = options.invertUV || false;
            var defaultOffset = Math.floor(pathArray[0].length / 2);
            var offset = options.offset || defaultOffset;
            offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var positions = [];
            var indices = [];
            var normals = [];
            var uvs = [];
            var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
            var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
            var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
            var vTotalDistance = []; //  vTotalDistance[i] : total distance between points i of first and last path from pathArray
            var minlg; // minimal length among all paths from pathArray
            var lg = []; // array of path lengths : nb of vertex per path
            var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
            var p; // path iterator
            var i; // point iterator
            var j; // point iterator
            // if single path in pathArray
            if (pathArray.length < 2) {
                var ar1 = [];
                var ar2 = [];
                for (i = 0; i < pathArray[0].length - offset; i++) {
                    ar1.push(pathArray[0][i]);
                    ar2.push(pathArray[0][i + offset]);
                }
                pathArray = [ar1, ar2];
            }
            // positions and horizontal distances (u)
            var idc = 0;
            var closePathCorr = (closePath) ? 1 : 0;
            var path;
            var l;
            minlg = pathArray[0].length;
            var vectlg;
            var dist;
            for (p = 0; p < pathArray.length; p++) {
                uTotalDistance[p] = 0;
                us[p] = [0];
                path = pathArray[p];
                l = path.length;
                minlg = (minlg < l) ? minlg : l;
                j = 0;
                while (j < l) {
                    positions.push(path[j].x, path[j].y, path[j].z);
                    if (j > 0) {
                        vectlg = path[j].subtract(path[j - 1]).length();
                        dist = vectlg + uTotalDistance[p];
                        us[p].push(dist);
                        uTotalDistance[p] = dist;
                    }
                    j++;
                }
                if (closePath) {
                    j--;
                    positions.push(path[0].x, path[0].y, path[0].z);
                    vectlg = path[j].subtract(path[0]).length();
                    dist = vectlg + uTotalDistance[p];
                    us[p].push(dist);
                    uTotalDistance[p] = dist;
                }
                lg[p] = l + closePathCorr;
                idx[p] = idc;
                idc += (l + closePathCorr);
            }
            // vertical distances (v)
            var path1;
            var path2;
            var vertex1;
            var vertex2;
            for (i = 0; i < minlg + closePathCorr; i++) {
                vTotalDistance[i] = 0;
                vs[i] = [0];
                for (p = 0; p < pathArray.length - 1; p++) {
                    path1 = pathArray[p];
                    path2 = pathArray[p + 1];
                    if (i === minlg) {
                        vertex1 = path1[0];
                        vertex2 = path2[0];
                    }
                    else {
                        vertex1 = path1[i];
                        vertex2 = path2[i];
                    }
                    vectlg = vertex2.subtract(vertex1).length();
                    dist = vectlg + vTotalDistance[i];
                    vs[i].push(dist);
                    vTotalDistance[i] = dist;
                }
                if (closeArray) {
                    path1 = pathArray[p];
                    path2 = pathArray[0];
                    if (i === minlg) {
                        vertex2 = path2[0];
                    }
                    vectlg = vertex2.subtract(vertex1).length();
                    dist = vectlg + vTotalDistance[i];
                    vTotalDistance[i] = dist;
                }
            }
            // uvs
            var u;
            var v;
            for (p = 0; p < pathArray.length; p++) {
                for (i = 0; i < minlg + closePathCorr; i++) {
                    u = us[p][i] / uTotalDistance[p];
                    v = vs[i][p] / vTotalDistance[i];
                    if (invertUV) {
                        uvs.push(v, u);
                    }
                    else {
                        uvs.push(u, v);
                    }
                }
            }
            // indices
            p = 0; // path index
            var pi = 0; // positions array index
            var l1 = lg[p] - 1; // path1 length
            var l2 = lg[p + 1] - 1; // path2 length
            var min = (l1 < l2) ? l1 : l2; // current path stop index
            var shft = idx[1] - idx[0]; // shift
            var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate	on
            while (pi <= min && p < path1nb) {
                // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
                indices.push(pi, pi + shft, pi + 1);
                indices.push(pi + shft + 1, pi + 1, pi + shft);
                pi += 1;
                if (pi === min) {
                    p++;
                    if (p === lg.length - 1) {
                        shft = idx[0] - idx[p];
                        l1 = lg[p] - 1;
                        l2 = lg[0] - 1;
                    }
                    else {
                        shft = idx[p + 1] - idx[p];
                        l1 = lg[p] - 1;
                        l2 = lg[p + 1] - 1;
                    }
                    pi = idx[p];
                    min = (l1 < l2) ? l1 + pi : l2 + pi;
                }
            }
            // normals
            VertexData.ComputeNormals(positions, indices, normals);
            if (closePath) {
                var indexFirst = 0;
                var indexLast = 0;
                for (p = 0; p < pathArray.length; p++) {
                    indexFirst = idx[p] * 3;
                    if (p + 1 < pathArray.length) {
                        indexLast = (idx[p + 1] - 1) * 3;
                    }
                    else {
                        indexLast = normals.length - 3;
                    }
                    normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
                    normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
                    normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
                    normals[indexLast] = normals[indexFirst];
                    normals[indexLast + 1] = normals[indexFirst + 1];
                    normals[indexLast + 2] = normals[indexFirst + 2];
                }
            }
            // sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (closePath) {
                vertexData._idx = idx;
            }
            return vertexData;
        };
        VertexData.CreateBox = function (options) {
            var normalsSource = [
                new BABYLON.Vector3(0, 0, 1),
                new BABYLON.Vector3(0, 0, -1),
                new BABYLON.Vector3(1, 0, 0),
                new BABYLON.Vector3(-1, 0, 0),
                new BABYLON.Vector3(0, 1, 0),
                new BABYLON.Vector3(0, -1, 0)
            ];
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var width = options.width || options.size || 1;
            var height = options.height || options.size || 1;
            var depth = options.depth || options.size || 1;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var faceUV = options.faceUV || new Array(6);
            var faceColors = options.faceColors;
            var colors = [];
            // default face colors and UV if undefined
            for (var f = 0; f < 6; f++) {
                if (faceUV[f] === undefined) {
                    faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                }
                if (faceColors && faceColors[f] === undefined) {
                    faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                }
            }
            var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
            // Create each face in turn.
            for (var index = 0; index < normalsSource.length; index++) {
                var normal = normalsSource[index];
                // Get two vectors perpendicular to the face normal and to each other.
                var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
                var side2 = BABYLON.Vector3.Cross(normal, side1);
                // Six indices (two triangles) per face.
                var verticesLength = positions.length / 3;
                indices.push(verticesLength);
                indices.push(verticesLength + 1);
                indices.push(verticesLength + 2);
                indices.push(verticesLength);
                indices.push(verticesLength + 2);
                indices.push(verticesLength + 3);
                // Four vertices per face.
                var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].z, faceUV[index].w);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
                vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].x, faceUV[index].w);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
                vertex = normal.add(side1).add(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].x, faceUV[index].y);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
                vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].z, faceUV[index].y);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
            }
            // sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors) {
                var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
                vertexData.colors = totalColors;
            }
            return vertexData;
        };
        VertexData.CreateSphere = function (options) {
            var segments = options.segments || 32;
            var diameterX = options.diameterX || options.diameter || 1;
            var diameterY = options.diameterY || options.diameter || 1;
            var diameterZ = options.diameterZ || options.diameter || 1;
            var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
            var totalZRotationSteps = 2 + segments;
            var totalYRotationSteps = 2 * totalZRotationSteps;
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
                var normalizedZ = zRotationStep / totalZRotationSteps;
                var angleZ = normalizedZ * Math.PI * slice;
                for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
                    var normalizedY = yRotationStep / totalYRotationSteps;
                    var angleY = normalizedY * Math.PI * 2 * arc;
                    var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
                    var rotationY = BABYLON.Matrix.RotationY(angleY);
                    var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
                    var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
                    var vertex = complete.multiply(radius);
                    var normal = complete.divide(radius).normalize();
                    positions.push(vertex.x, vertex.y, vertex.z);
                    normals.push(normal.x, normal.y, normal.z);
                    uvs.push(normalizedY, normalizedZ);
                }
                if (zRotationStep > 0) {
                    var verticesCount = positions.length / 3;
                    for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
                        indices.push((firstIndex));
                        indices.push((firstIndex + 1));
                        indices.push(firstIndex + totalYRotationSteps + 1);
                        indices.push((firstIndex + totalYRotationSteps + 1));
                        indices.push((firstIndex + 1));
                        indices.push((firstIndex + totalYRotationSteps + 2));
                    }
                }
            }
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        // Cylinder and cone
        VertexData.CreateCylinder = function (options) {
            var height = options.height || 2;
            var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
            var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
            var tessellation = options.tessellation || 24;
            var subdivisions = options.subdivisions || 1;
            var hasRings = options.hasRings;
            var enclose = options.enclose;
            var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var faceUV = options.faceUV || new Array(3);
            var faceColors = options.faceColors;
            // default face colors and UV if undefined
            var quadNb = (arc !== 1 && enclose) ? 2 : 0;
            var ringNb = (hasRings) ? subdivisions : 1;
            var surfaceNb = 2 + (1 + quadNb) * ringNb;
            var f;
            for (f = 0; f < surfaceNb; f++) {
                if (faceColors && faceColors[f] === undefined) {
                    faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                }
            }
            for (f = 0; f < surfaceNb; f++) {
                if (faceUV && faceUV[f] === undefined) {
                    faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                }
            }
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var colors = [];
            var angle_step = Math.PI * 2 * arc / tessellation;
            var angle;
            var h;
            var radius;
            var tan = (diameterBottom - diameterTop) / 2 / height;
            var ringVertex = BABYLON.Vector3.Zero();
            var ringNormal = BABYLON.Vector3.Zero();
            var ringFirstVertex = BABYLON.Vector3.Zero();
            var ringFirstNormal = BABYLON.Vector3.Zero();
            var quadNormal = BABYLON.Vector3.Zero();
            var Y = BABYLON.Axis.Y;
            // positions, normals, uvs
            var i;
            var j;
            var r;
            var ringIdx = 1;
            var s = 1; // surface index
            var cs = 0;
            var v = 0;
            for (i = 0; i <= subdivisions; i++) {
                h = i / subdivisions;
                radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
                ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
                for (r = 0; r < ringIdx; r++) {
                    if (hasRings) {
                        s += r;
                    }
                    if (enclose) {
                        s += 2 * r;
                    }
                    for (j = 0; j <= tessellation; j++) {
                        angle = j * angle_step;
                        // position
                        ringVertex.x = Math.cos(-angle) * radius;
                        ringVertex.y = -height / 2 + h * height;
                        ringVertex.z = Math.sin(-angle) * radius;
                        // normal
                        if (diameterTop === 0 && i === subdivisions) {
                            // if no top cap, reuse former normals
                            ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
                            ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
                            ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
                        }
                        else {
                            ringNormal.x = ringVertex.x;
                            ringNormal.z = ringVertex.z;
                            ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
                            ringNormal.normalize();
                        }
                        // keep first ring vertex values for enclose
                        if (j === 0) {
                            ringFirstVertex.copyFrom(ringVertex);
                            ringFirstNormal.copyFrom(ringNormal);
                        }
                        positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
                        normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
                        if (hasRings) {
                            v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
                        }
                        else {
                            v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
                        }
                        uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
                        if (faceColors) {
                            colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
                        }
                    }
                    // if enclose, add four vertices and their dedicated normals
                    if (arc !== 1 && enclose) {
                        positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
                        positions.push(0, ringVertex.y, 0);
                        positions.push(0, ringVertex.y, 0);
                        positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
                        BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
                        quadNormal.normalize();
                        normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
                        BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
                        quadNormal.normalize();
                        normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
                        if (hasRings) {
                            v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
                        }
                        else {
                            v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
                        }
                        uvs.push(faceUV[s + 1].x, v);
                        uvs.push(faceUV[s + 1].z, v);
                        if (hasRings) {
                            v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
                        }
                        else {
                            v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
                        }
                        uvs.push(faceUV[s + 2].x, v);
                        uvs.push(faceUV[s + 2].z, v);
                        if (faceColors) {
                            colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
                            colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
                            colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
                            colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
                        }
                    }
                    if (cs !== s) {
                        cs = s;
                    }
                }
            }
            // indices
            var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
            var s;
            i = 0;
            for (s = 0; s < subdivisions; s++) {
                for (j = 0; j < tessellation; j++) {
                    var i0 = i * (e + 1) + j;
                    var i1 = (i + 1) * (e + 1) + j;
                    var i2 = i * (e + 1) + (j + 1);
                    var i3 = (i + 1) * (e + 1) + (j + 1);
                    indices.push(i0, i1, i2);
                    indices.push(i3, i2, i1);
                }
                if (arc !== 1 && enclose) {
                    indices.push(i0 + 2, i1 + 2, i2 + 2);
                    indices.push(i3 + 2, i2 + 2, i1 + 2);
                    indices.push(i0 + 4, i1 + 4, i2 + 4);
                    indices.push(i3 + 4, i2 + 4, i1 + 4);
                }
                i = (hasRings) ? (i + 2) : (i + 1);
            }
            // Caps
            var createCylinderCap = function (isTop) {
                var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
                if (radius === 0) {
                    return;
                }
                // Cap positions, normals & uvs
                var angle;
                var circleVector;
                var i;
                var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
                var c;
                if (faceColors) {
                    c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
                }
                // cap center
                var vbase = positions.length / 3;
                var offset = isTop ? height / 2 : -height / 2;
                var center = new BABYLON.Vector3(0, offset, 0);
                positions.push(center.x, center.y, center.z);
                normals.push(0, isTop ? 1 : -1, 0);
                uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
                if (faceColors) {
                    colors.push(c.r, c.g, c.b, c.a);
                }
                var textureScale = new BABYLON.Vector2(0.5, 0.5);
                for (i = 0; i <= tessellation; i++) {
                    angle = Math.PI * 2 * i * arc / tessellation;
                    var cos = Math.cos(-angle);
                    var sin = Math.sin(-angle);
                    circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
                    var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
                    positions.push(circleVector.x, circleVector.y, circleVector.z);
                    normals.push(0, isTop ? 1 : -1, 0);
                    uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
                    if (faceColors) {
                        colors.push(c.r, c.g, c.b, c.a);
                    }
                }
                // Cap indices
                for (i = 0; i < tessellation; i++) {
                    if (!isTop) {
                        indices.push(vbase);
                        indices.push(vbase + (i + 1));
                        indices.push(vbase + (i + 2));
                    }
                    else {
                        indices.push(vbase);
                        indices.push(vbase + (i + 2));
                        indices.push(vbase + (i + 1));
                    }
                }
            };
            // add caps to geometry
            createCylinderCap(false);
            createCylinderCap(true);
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors) {
                vertexData.colors = colors;
            }
            return vertexData;
        };
        VertexData.CreateTorus = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var diameter = options.diameter || 1;
            var thickness = options.thickness || 0.5;
            var tessellation = options.tessellation || 16;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var stride = tessellation + 1;
            for (var i = 0; i <= tessellation; i++) {
                var u = i / tessellation;
                var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
                var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
                for (var j = 0; j <= tessellation; j++) {
                    var v = 1 - j / tessellation;
                    var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
                    var dx = Math.cos(innerAngle);
                    var dy = Math.sin(innerAngle);
                    // Create a vertex.
                    var normal = new BABYLON.Vector3(dx, dy, 0);
                    var position = normal.scale(thickness / 2);
                    var textureCoordinate = new BABYLON.Vector2(u, v);
                    position = BABYLON.Vector3.TransformCoordinates(position, transform);
                    normal = BABYLON.Vector3.TransformNormal(normal, transform);
                    positions.push(position.x, position.y, position.z);
                    normals.push(normal.x, normal.y, normal.z);
                    uvs.push(textureCoordinate.x, textureCoordinate.y);
                    // And create indices for two triangles.
                    var nextI = (i + 1) % stride;
                    var nextJ = (j + 1) % stride;
                    indices.push(i * stride + j);
                    indices.push(i * stride + nextJ);
                    indices.push(nextI * stride + j);
                    indices.push(i * stride + nextJ);
                    indices.push(nextI * stride + nextJ);
                    indices.push(nextI * stride + j);
                }
            }
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        VertexData.CreateLineSystem = function (options) {
            var indices = [];
            var positions = [];
            var lines = options.lines;
            var idx = 0;
            for (var l = 0; l < lines.length; l++) {
                var points = lines[l];
                for (var index = 0; index < points.length; index++) {
                    positions.push(points[index].x, points[index].y, points[index].z);
                    if (index > 0) {
                        indices.push(idx - 1);
                        indices.push(idx);
                    }
                    idx++;
                }
            }
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            return vertexData;
        };
        VertexData.CreateDashedLines = function (options) {
            var dashSize = options.dashSize || 3;
            var gapSize = options.gapSize || 1;
            var dashNb = options.dashNb || 200;
            var points = options.points;
            var positions = new Array();
            var indices = new Array();
            var curvect = BABYLON.Vector3.Zero();
            var lg = 0;
            var nb = 0;
            var shft = 0;
            var dashshft = 0;
            var curshft = 0;
            var idx = 0;
            var i = 0;
            for (i = 0; i < points.length - 1; i++) {
                points[i + 1].subtractToRef(points[i], curvect);
                lg += curvect.length();
            }
            shft = lg / dashNb;
            dashshft = dashSize * shft / (dashSize + gapSize);
            for (i = 0; i < points.length - 1; i++) {
                points[i + 1].subtractToRef(points[i], curvect);
                nb = Math.floor(curvect.length() / shft);
                curvect.normalize();
                for (var j = 0; j < nb; j++) {
                    curshft = shft * j;
                    positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
                    positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
                    indices.push(idx, idx + 1);
                    idx += 2;
                }
            }
            // Result
            var vertexData = new VertexData();
            vertexData.positions = positions;
            vertexData.indices = indices;
            return vertexData;
        };
        VertexData.CreateGround = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var row, col;
            var width = options.width || 1;
            var height = options.height || 1;
            var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
            var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
            for (row = 0; row <= subdivisionsY; row++) {
                for (col = 0; col <= subdivisionsX; col++) {
                    var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
                    var normal = new BABYLON.Vector3(0, 1.0, 0);
                    positions.push(position.x, position.y, position.z);
                    normals.push(normal.x, normal.y, normal.z);
                    uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
                }
            }
            for (row = 0; row < subdivisionsY; row++) {
                for (col = 0; col < subdivisionsX; col++) {
                    indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
                    indices.push(col + 1 + row * (subdivisionsX + 1));
                    indices.push(col + row * (subdivisionsX + 1));
                    indices.push(col + (row + 1) * (subdivisionsX + 1));
                    indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
                    indices.push(col + row * (subdivisionsX + 1));
                }
            }
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        VertexData.CreateTiledGround = function (options) {
            var xmin = options.xmin || -1.0;
            var zmin = options.zmin || -1.0;
            var xmax = options.xmax || 1.0;
            var zmax = options.zmax || 1.0;
            var subdivisions = options.subdivisions || { w: 1, h: 1 };
            var precision = options.precision || { w: 1, h: 1 };
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var row, col, tileRow, tileCol;
            subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
            subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
            precision.w = (precision.w < 1) ? 1 : precision.w;
            precision.h = (precision.h < 1) ? 1 : precision.h;
            var tileSize = {
                'w': (xmax - xmin) / subdivisions.w,
                'h': (zmax - zmin) / subdivisions.h
            };
            function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
                // Indices
                var base = positions.length / 3;
                var rowLength = precision.w + 1;
                for (row = 0; row < precision.h; row++) {
                    for (col = 0; col < precision.w; col++) {
                        var square = [
                            base + col + row * rowLength,
                            base + (col + 1) + row * rowLength,
                            base + (col + 1) + (row + 1) * rowLength,
                            base + col + (row + 1) * rowLength
                        ];
                        indices.push(square[1]);
                        indices.push(square[2]);
                        indices.push(square[3]);
                        indices.push(square[0]);
                        indices.push(square[1]);
                        indices.push(square[3]);
                    }
                }
                // Position, normals and uvs
                var position = BABYLON.Vector3.Zero();
                var normal = new BABYLON.Vector3(0, 1.0, 0);
                for (row = 0; row <= precision.h; row++) {
                    position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
                    for (col = 0; col <= precision.w; col++) {
                        position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
                        position.y = 0;
                        positions.push(position.x, position.y, position.z);
                        normals.push(normal.x, normal.y, normal.z);
                        uvs.push(col / precision.w, row / precision.h);
                    }
                }
            }
            for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
                for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
                    applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
                }
            }
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        VertexData.CreateGroundFromHeightMap = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var row, col;
            // Vertices
            for (row = 0; row <= options.subdivisions; row++) {
                for (col = 0; col <= options.subdivisions; col++) {
                    var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
                    // Compute height
                    var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
                    var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
                    var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
                    var r = options.buffer[pos] / 255.0;
                    var g = options.buffer[pos + 1] / 255.0;
                    var b = options.buffer[pos + 2] / 255.0;
                    var gradient = r * 0.3 + g * 0.59 + b * 0.11;
                    position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
                    // Add  vertex
                    positions.push(position.x, position.y, position.z);
                    normals.push(0, 0, 0);
                    uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
                }
            }
            // Indices
            for (row = 0; row < options.subdivisions; row++) {
                for (col = 0; col < options.subdivisions; col++) {
                    indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
                    indices.push(col + 1 + row * (options.subdivisions + 1));
                    indices.push(col + row * (options.subdivisions + 1));
                    indices.push(col + (row + 1) * (options.subdivisions + 1));
                    indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
                    indices.push(col + row * (options.subdivisions + 1));
                }
            }
            // Normals
            VertexData.ComputeNormals(positions, indices, normals);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        VertexData.CreatePlane = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var width = options.width || options.size || 1;
            var height = options.height || options.size || 1;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            // Vertices
            var halfWidth = width / 2.0;
            var halfHeight = height / 2.0;
            positions.push(-halfWidth, -halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(0.0, 0.0);
            positions.push(halfWidth, -halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(1.0, 0.0);
            positions.push(halfWidth, halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(1.0, 1.0);
            positions.push(-halfWidth, halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(0.0, 1.0);
            // Indices
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        VertexData.CreateDisc = function (options) {
            var positions = [];
            var indices = [];
            var normals = [];
            var uvs = [];
            var radius = options.radius || 0.5;
            var tessellation = options.tessellation || 64;
            var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            // positions and uvs
            positions.push(0, 0, 0); // disc center first
            uvs.push(0.5, 0.5);
            var theta = Math.PI * 2 * arc;
            var step = theta / tessellation;
            for (var a = 0; a < theta; a += step) {
                var x = Math.cos(a);
                var y = Math.sin(a);
                var u = (x + 1) / 2;
                var v = (1 - y) / 2;
                positions.push(radius * x, radius * y, 0);
                uvs.push(u, v);
            }
            if (arc === 1) {
                positions.push(positions[3], positions[4], positions[5]); // close the circle
                uvs.push(uvs[2], uvs[3]);
            }
            //indices
            var vertexNb = positions.length / 3;
            for (var i = 1; i < vertexNb - 1; i++) {
                indices.push(i + 1, 0, i);
            }
            // result
            VertexData.ComputeNormals(positions, indices, normals);
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        VertexData.CreateIcoSphere = function (options) {
            var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var radius = options.radius || 1;
            var flat = (options.flat === undefined) ? true : options.flat;
            var subdivisions = options.subdivisions || 4;
            var radiusX = options.radiusX || radius;
            var radiusY = options.radiusY || radius;
            var radiusZ = options.radiusZ || radius;
            var t = (1 + Math.sqrt(5)) / 2;
            // 12 vertex x,y,z
            var ico_vertices = [
                -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
                0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
                t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
            ];
            // index of 3 vertex makes a face of icopshere
            var ico_indices = [
                0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
                1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
                14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
                4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
            ];
            // vertex for uv have aliased position, not for UV
            var vertices_unalias_id = [
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                // vertex alias
                0,
                2,
                3,
                3,
                3,
                4,
                7,
                8,
                9,
                9,
                10,
                11 // 23: B + 12
            ];
            // uv as integer step (not pixels !)
            var ico_vertexuv = [
                5, 1, 3, 1, 6, 4, 0, 0,
                5, 3, 4, 2, 2, 2, 4, 0,
                2, 0, 1, 1, 6, 0, 6, 2,
                // vertex alias (for same vertex on different faces)
                0, 4,
                3, 3,
                4, 4,
                3, 1,
                4, 2,
                4, 4,
                0, 2,
                1, 1,
                2, 2,
                3, 3,
                1, 3,
                2, 4 // 23: B + 12
            ];
            // Vertices[0, 1, ...9, A, B] : position on UV plane
            // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
            // First island of uv mapping
            // v = 4h          3+  2
            // v = 3h        9+  4
            // v = 2h      9+  5   B
            // v = 1h    9   1   0
            // v = 0h  3   8   7   A
            //     u = 0 1 2 3 4 5 6  *a
            // Second island of uv mapping
            // v = 4h  0+  B+  4+
            // v = 3h    A+  2+
            // v = 2h  7+  6   3+
            // v = 1h    8+  3+
            // v = 0h
            //     u = 0 1 2 3 4 5 6  *a
            // Face layout on texture UV mapping
            // ============
            // \ 4  /\ 16 /   ======
            //  \  /  \  /   /\ 11 /
            //   \/ 7  \/   /  \  /
            //    =======  / 10 \/
            //   /\ 17 /\  =======
            //  /  \  /  \ \ 15 /\
            // / 8  \/ 12 \ \  /  \
            // ============  \/ 6  \
            // \ 18 /\  ============
            //  \  /  \ \ 5  /\ 0  /
            //   \/ 13 \ \  /  \  /
            //   =======  \/ 1  \/
            //       =============
            //      /\ 19 /\  2 /\
            //     /  \  /  \  /  \
            //    / 14 \/ 9  \/  3 \
            //   ===================
            // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
            var ustep = 138 / 1024;
            var vstep = 239 / 1024;
            var uoffset = 60 / 1024;
            var voffset = 26 / 1024;
            // Second island should have margin, not to touch the first island
            // avoid any borderline artefact in pixel rounding
            var island_u_offset = -40 / 1024;
            var island_v_offset = +20 / 1024;
            // face is either island 0 or 1 :
            // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
            var island = [
                0, 0, 0, 0, 1,
                0, 0, 1, 1, 0,
                0, 0, 1, 1, 0,
                0, 1, 1, 1, 0 //  15 - 19
            ];
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var current_indice = 0;
            // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
            var face_vertex_pos = new Array(3);
            var face_vertex_uv = new Array(3);
            var v012;
            for (v012 = 0; v012 < 3; v012++) {
                face_vertex_pos[v012] = BABYLON.Vector3.Zero();
                face_vertex_uv[v012] = BABYLON.Vector2.Zero();
            }
            // create all with normals
            for (var face = 0; face < 20; face++) {
                // 3 vertex per face
                for (v012 = 0; v012 < 3; v012++) {
                    // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
                    var v_id = ico_indices[3 * face + v012];
                    // vertex have 3D position (x,y,z)
                    face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
                    // Normalize to get normal, then scale to radius
                    face_vertex_pos[v012].normalize().scaleInPlace(radius);
                    // uv Coordinates from vertex ID
                    face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
                }
                // Subdivide the face (interpolate pos, norm, uv)
                // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
                // - norm is linear interpolation of vertex corner normal
                //   (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
                // - uv is linear interpolation
                //
                // Topology is as below for sub-divide by 2
                // vertex shown as v0,v1,v2
                // interp index is i1 to progress in range [v0,v1[
                // interp index is i2 to progress in range [v0,v2[
                // face index as  (i1,i2)  for /\  : (i1,i2),(i1+1,i2),(i1,i2+1)
                //            and (i1,i2)' for \/  : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
                //
                //
                //                    i2    v2
                //                    ^    ^
                //                   /    / \
                //                  /    /   \
                //                 /    /     \
                //                /    / (0,1) \
                //               /    #---------\
                //              /    / \ (0,0)'/ \
                //             /    /   \     /   \
                //            /    /     \   /     \
                //           /    / (0,0) \ / (1,0) \
                //          /    #---------#---------\
                //              v0                    v1
                //
                //              --------------------> i1
                //
                // interp of (i1,i2):
                //  along i2 :  x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
                //  along i1 :  lerp(x0,x1, i1/(S-i2))
                //
                // centroid of triangle is needed to get help normal computation
                //  (c1,c2) are used for centroid location
                var interp_vertex = function (i1, i2, c1, c2) {
                    // vertex is interpolated from
                    //   - face_vertex_pos[0..2]
                    //   - face_vertex_uv[0..2]
                    var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
                    var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
                    var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
                    pos_interp.normalize();
                    var vertex_normal;
                    if (flat) {
                        // in flat mode, recalculate normal as face centroid normal
                        var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
                        var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
                        vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
                    }
                    else {
                        // in smooth mode, recalculate normal from each single vertex position
                        vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
                    }
                    // Vertex normal need correction due to X,Y,Z radius scaling
                    vertex_normal.x /= radiusX;
                    vertex_normal.y /= radiusY;
                    vertex_normal.z /= radiusZ;
                    vertex_normal.normalize();
                    var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
                    var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
                    var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
                    positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
                    normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
                    uvs.push(uv_interp.x, uv_interp.y);
                    // push each vertex has member of a face
                    // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
                    indices.push(current_indice);
                    current_indice++;
                };
                for (var i2 = 0; i2 < subdivisions; i2++) {
                    for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
                        // face : (i1,i2)  for /\  :
                        // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
                        interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
                        interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
                        interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
                        if (i1 + i2 + 1 < subdivisions) {
                            // face : (i1,i2)' for \/  :
                            // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
                            interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
                            interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
                            interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
                        }
                    }
                }
            }
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
        VertexData.CreatePolyhedron = function (options) {
            // provided polyhedron types :
            // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
            // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
            var polyhedra = [];
            polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
            polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
            polyhedra[2] = {
                vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
                face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
            };
            polyhedra[3] = {
                vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
                face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
            };
            polyhedra[4] = {
                vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
                face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
            };
            polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
            polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
            polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
            polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
            polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
            polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
            polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
            polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
            polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
            polyhedra[14] = {
                vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
                face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
            };
            var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
            var size = options.size;
            var sizeX = options.sizeX || size || 1;
            var sizeY = options.sizeY || size || 1;
            var sizeZ = options.sizeZ || size || 1;
            var data = options.custom || polyhedra[type];
            var nbfaces = data.face.length;
            var faceUV = options.faceUV || new Array(nbfaces);
            var faceColors = options.faceColors;
            var flat = (options.flat === undefined) ? true : options.flat;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var positions = [];
            var indices = [];
            var normals = [];
            var uvs = [];
            var colors = [];
            var index = 0;
            var faceIdx = 0; // face cursor in the array "indexes"
            var indexes = [];
            var i = 0;
            var f = 0;
            var u, v, ang, x, y, tmp;
            // default face colors and UV if undefined
            if (flat) {
                for (f = 0; f < nbfaces; f++) {
                    if (faceColors && faceColors[f] === undefined) {
                        faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                    }
                    if (faceUV && faceUV[f] === undefined) {
                        faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                    }
                }
            }
            if (!flat) {
                for (i = 0; i < data.vertex.length; i++) {
                    positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
                    uvs.push(0, 0);
                }
                for (f = 0; f < nbfaces; f++) {
                    for (i = 0; i < data.face[f].length - 2; i++) {
                        indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
                    }
                }
            }
            else {
                for (f = 0; f < nbfaces; f++) {
                    var fl = data.face[f].length; // number of vertices of the current face
                    ang = 2 * Math.PI / fl;
                    x = 0.5 * Math.tan(ang / 2);
                    y = 0.5;
                    // positions, uvs, colors
                    for (i = 0; i < fl; i++) {
                        // positions
                        positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
                        indexes.push(index);
                        index++;
                        // uvs
                        u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
                        v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
                        uvs.push(u, v);
                        tmp = x * Math.cos(ang) - y * Math.sin(ang);
                        y = x * Math.sin(ang) + y * Math.cos(ang);
                        x = tmp;
                        // colors
                        if (faceColors) {
                            colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
                        }
                    }
                    // indices from indexes
                    for (i = 0; i < fl - 2; i++) {
                        indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
                    }
                    faceIdx += fl;
                }
            }
            VertexData.ComputeNormals(positions, indices, normals);
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            var vertexData = new VertexData();
            vertexData.positions = positions;
            vertexData.indices = indices;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors && flat) {
                vertexData.colors = colors;
            }
            return vertexData;
        };
        // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
        VertexData.CreateTorusKnot = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var radius = options.radius || 2;
            var tube = options.tube || 0.5;
            var radialSegments = options.radialSegments || 32;
            var tubularSegments = options.tubularSegments || 32;
            var p = options.p || 2;
            var q = options.q || 3;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            // Helper
            var getPos = function (angle) {
                var cu = Math.cos(angle);
                var su = Math.sin(angle);
                var quOverP = q / p * angle;
                var cs = Math.cos(quOverP);
                var tx = radius * (2 + cs) * 0.5 * cu;
                var ty = radius * (2 + cs) * su * 0.5;
                var tz = radius * Math.sin(quOverP) * 0.5;
                return new BABYLON.Vector3(tx, ty, tz);
            };
            // Vertices
            var i;
            var j;
            for (i = 0; i <= radialSegments; i++) {
                var modI = i % radialSegments;
                var u = modI / radialSegments * 2 * p * Math.PI;
                var p1 = getPos(u);
                var p2 = getPos(u + 0.01);
                var tang = p2.subtract(p1);
                var n = p2.add(p1);
                var bitan = BABYLON.Vector3.Cross(tang, n);
                n = BABYLON.Vector3.Cross(bitan, tang);
                bitan.normalize();
                n.normalize();
                for (j = 0; j < tubularSegments; j++) {
                    var modJ = j % tubularSegments;
                    var v = modJ / tubularSegments * 2 * Math.PI;
                    var cx = -tube * Math.cos(v);
                    var cy = tube * Math.sin(v);
                    positions.push(p1.x + cx * n.x + cy * bitan.x);
                    positions.push(p1.y + cx * n.y + cy * bitan.y);
                    positions.push(p1.z + cx * n.z + cy * bitan.z);
                    uvs.push(i / radialSegments);
                    uvs.push(j / tubularSegments);
                }
            }
            for (i = 0; i < radialSegments; i++) {
                for (j = 0; j < tubularSegments; j++) {
                    var jNext = (j + 1) % tubularSegments;
                    var a = i * tubularSegments + j;
                    var b = (i + 1) * tubularSegments + j;
                    var c = (i + 1) * tubularSegments + jNext;
                    var d = i * tubularSegments + jNext;
                    indices.push(d);
                    indices.push(b);
                    indices.push(a);
                    indices.push(d);
                    indices.push(c);
                    indices.push(b);
                }
            }
            // Normals
            VertexData.ComputeNormals(positions, indices, normals);
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        // Tools
        /**
         * @param {any} - positions (number[] or Float32Array)
         * @param {any} - indices   (number[] or Uint16Array)
         * @param {any} - normals   (number[] or Float32Array)
         */
        VertexData.ComputeNormals = function (positions, indices, normals) {
            var index = 0;
            var p1p2x = 0.0;
            var p1p2y = 0.0;
            var p1p2z = 0.0;
            var p3p2x = 0.0;
            var p3p2y = 0.0;
            var p3p2z = 0.0;
            var faceNormalx = 0.0;
            var faceNormaly = 0.0;
            var faceNormalz = 0.0;
            var length = 0.0;
            var i1 = 0;
            var i2 = 0;
            var i3 = 0;
            for (index = 0; index < positions.length; index++) {
                normals[index] = 0.0;
            }
            // indice triplet = 1 face
            var nbFaces = indices.length / 3;
            for (index = 0; index < nbFaces; index++) {
                i1 = indices[index * 3]; // get the indexes of each vertex of the face
                i2 = indices[index * 3 + 1];
                i3 = indices[index * 3 + 2];
                p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
                p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
                p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
                p3p2x = positions[i3 * 3] - positions[i2 * 3];
                p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
                p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
                faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
                faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
                faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
                length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
                length = (length === 0) ? 1.0 : length;
                faceNormalx /= length; // normalize this normal
                faceNormaly /= length;
                faceNormalz /= length;
                normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
                normals[i1 * 3 + 1] += faceNormaly;
                normals[i1 * 3 + 2] += faceNormalz;
                normals[i2 * 3] += faceNormalx;
                normals[i2 * 3 + 1] += faceNormaly;
                normals[i2 * 3 + 2] += faceNormalz;
                normals[i3 * 3] += faceNormalx;
                normals[i3 * 3 + 1] += faceNormaly;
                normals[i3 * 3 + 2] += faceNormalz;
            }
            // last normalization of each normal
            for (index = 0; index < normals.length / 3; index++) {
                faceNormalx = normals[index * 3];
                faceNormaly = normals[index * 3 + 1];
                faceNormalz = normals[index * 3 + 2];
                length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
                length = (length === 0) ? 1.0 : length;
                faceNormalx /= length;
                faceNormaly /= length;
                faceNormalz /= length;
                normals[index * 3] = faceNormalx;
                normals[index * 3 + 1] = faceNormaly;
                normals[index * 3 + 2] = faceNormalz;
            }
        };
        VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
            var li = indices.length;
            var ln = normals.length;
            var i;
            var n;
            sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            switch (sideOrientation) {
                case BABYLON.Mesh.FRONTSIDE:
                    // nothing changed
                    break;
                case BABYLON.Mesh.BACKSIDE:
                    var tmp;
                    // indices
                    for (i = 0; i < li; i += 3) {
                        tmp = indices[i];
                        indices[i] = indices[i + 2];
                        indices[i + 2] = tmp;
                    }
                    // normals
                    for (n = 0; n < ln; n++) {
                        normals[n] = -normals[n];
                    }
                    break;
                case BABYLON.Mesh.DOUBLESIDE:
                    // positions
                    var lp = positions.length;
                    var l = lp / 3;
                    for (var p = 0; p < lp; p++) {
                        positions[lp + p] = positions[p];
                    }
                    // indices
                    for (i = 0; i < li; i += 3) {
                        indices[i + li] = indices[i + 2] + l;
                        indices[i + 1 + li] = indices[i + 1] + l;
                        indices[i + 2 + li] = indices[i] + l;
                    }
                    // normals
                    for (n = 0; n < ln; n++) {
                        normals[ln + n] = -normals[n];
                    }
                    // uvs
                    var lu = uvs.length;
                    for (var u = 0; u < lu; u++) {
                        uvs[u + lu] = uvs[u];
                    }
                    break;
            }
        };
        VertexData.ImportVertexData = function (parsedVertexData, geometry) {
            var vertexData = new VertexData();
            // positions
            var positions = parsedVertexData.positions;
            if (positions) {
                vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
            }
            // normals
            var normals = parsedVertexData.normals;
            if (normals) {
                vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
            }
            // uvs
            var uvs = parsedVertexData.uvs;
            if (uvs) {
                vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
            }
            // uv2s
            var uv2s = parsedVertexData.uv2s;
            if (uv2s) {
                vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
            }
            // uv3s
            var uv3s = parsedVertexData.uv3s;
            if (uv3s) {
                vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
            }
            // uv4s
            var uv4s = parsedVertexData.uv4s;
            if (uv4s) {
                vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
            }
            // uv5s
            var uv5s = parsedVertexData.uv5s;
            if (uv5s) {
                vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
            }
            // uv6s
            var uv6s = parsedVertexData.uv6s;
            if (uv6s) {
                vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
            }
            // colors
            var colors = parsedVertexData.colors;
            if (colors) {
                vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
            }
            // matricesIndices
            var matricesIndices = parsedVertexData.matricesIndices;
            if (matricesIndices) {
                vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
            }
            // matricesWeights
            var matricesWeights = parsedVertexData.matricesWeights;
            if (matricesWeights) {
                vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
            }
            // indices
            var indices = parsedVertexData.indices;
            if (indices) {
                vertexData.indices = indices;
            }
            geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
        };
        return VertexData;
    }());
    BABYLON.VertexData = VertexData;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.mesh.vertexData.js.map
 
var BABYLON;
(function (BABYLON) {
    var Tags = (function () {
        function Tags() {
        }
        Tags.EnableFor = function (obj) {
            obj._tags = obj._tags || {};
            obj.hasTags = function () {
                return Tags.HasTags(obj);
            };
            obj.addTags = function (tagsString) {
                return Tags.AddTagsTo(obj, tagsString);
            };
            obj.removeTags = function (tagsString) {
                return Tags.RemoveTagsFrom(obj, tagsString);
            };
            obj.matchesTagsQuery = function (tagsQuery) {
                return Tags.MatchesQuery(obj, tagsQuery);
            };
        };
        Tags.DisableFor = function (obj) {
            delete obj._tags;
            delete obj.hasTags;
            delete obj.addTags;
            delete obj.removeTags;
            delete obj.matchesTagsQuery;
        };
        Tags.HasTags = function (obj) {
            if (!obj._tags) {
                return false;
            }
            return !BABYLON.Tools.IsEmpty(obj._tags);
        };
        Tags.GetTags = function (obj, asString) {
            if (asString === void 0) { asString = true; }
            if (!obj._tags) {
                return null;
            }
            if (asString) {
                var tagsArray = [];
                for (var tag in obj._tags) {
                    if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
                        tagsArray.push(tag);
                    }
                }
                return tagsArray.join(" ");
            }
            else {
                return obj._tags;
            }
        };
        // the tags 'true' and 'false' are reserved and cannot be used as tags
        // a tag cannot start with '||', '&&', and '!'
        // it cannot contain whitespaces
        Tags.AddTagsTo = function (obj, tagsString) {
            if (!tagsString) {
                return;
            }
            if (typeof tagsString !== "string") {
                return;
            }
            var tags = tagsString.split(" ");
            tags.forEach(function (tag, index, array) {
                Tags._AddTagTo(obj, tag);
            });
        };
        Tags._AddTagTo = function (obj, tag) {
            tag = tag.trim();
            if (tag === "" || tag === "true" || tag === "false") {
                return;
            }
            if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
                return;
            }
            Tags.EnableFor(obj);
            obj._tags[tag] = true;
        };
        Tags.RemoveTagsFrom = function (obj, tagsString) {
            if (!Tags.HasTags(obj)) {
                return;
            }
            var tags = tagsString.split(" ");
            for (var t in tags) {
                Tags._RemoveTagFrom(obj, tags[t]);
            }
        };
        Tags._RemoveTagFrom = function (obj, tag) {
            delete obj._tags[tag];
        };
        Tags.MatchesQuery = function (obj, tagsQuery) {
            if (tagsQuery === undefined) {
                return true;
            }
            if (tagsQuery === "") {
                return Tags.HasTags(obj);
            }
            return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
        };
        return Tags;
    }());
    BABYLON.Tags = Tags;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tags.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var AndOrNotEvaluator = (function () {
            function AndOrNotEvaluator() {
            }
            AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
                if (!query.match(/\([^\(\)]*\)/g)) {
                    query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
                }
                else {
                    query = query.replace(/\([^\(\)]*\)/g, function (r) {
                        // remove parenthesis
                        r = r.slice(1, r.length - 1);
                        return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
                    });
                }
                if (query === "true") {
                    return true;
                }
                if (query === "false") {
                    return false;
                }
                return AndOrNotEvaluator.Eval(query, evaluateCallback);
            };
            AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
                evaluateCallback = evaluateCallback || (function (r) {
                    return r === "true" ? true : false;
                });
                var result;
                var or = parenthesisContent.split("||");
                for (var i in or) {
                    if (or.hasOwnProperty(i)) {
                        var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
                        var and = ori.split("&&");
                        if (and.length > 1) {
                            for (var j = 0; j < and.length; ++j) {
                                var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
                                if (andj !== "true" && andj !== "false") {
                                    if (andj[0] === "!") {
                                        result = !evaluateCallback(andj.substring(1));
                                    }
                                    else {
                                        result = evaluateCallback(andj);
                                    }
                                }
                                else {
                                    result = andj === "true" ? true : false;
                                }
                                if (!result) {
                                    ori = "false";
                                    break;
                                }
                            }
                        }
                        if (result || ori === "true") {
                            result = true;
                            break;
                        }
                        // result equals false (or undefined)
                        if (ori !== "true" && ori !== "false") {
                            if (ori[0] === "!") {
                                result = !evaluateCallback(ori.substring(1));
                            }
                            else {
                                result = evaluateCallback(ori);
                            }
                        }
                        else {
                            result = ori === "true" ? true : false;
                        }
                    }
                }
                // the whole parenthesis scope is replaced by 'true' or 'false'
                return result ? "true" : "false";
            };
            AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
                booleanString = booleanString.replace(/^[\s!]+/, function (r) {
                    // remove whitespaces
                    r = r.replace(/[\s]/g, function () { return ""; });
                    return r.length % 2 ? "!" : "";
                });
                booleanString = booleanString.trim();
                if (booleanString === "!true") {
                    booleanString = "false";
                }
                else if (booleanString === "!false") {
                    booleanString = "true";
                }
                return booleanString;
            };
            return AndOrNotEvaluator;
        }());
        Internals.AndOrNotEvaluator = AndOrNotEvaluator;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.andOrNotEvaluator.js.map
 
var BABYLON;
(function (BABYLON) {
    var PostProcessRenderPass = (function () {
        function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
            this._enabled = true;
            this._refCount = 0;
            this._name = name;
            this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
            this.setRenderList(renderList);
            this._renderTexture.onBeforeRenderObservable.add(beforeRender);
            this._renderTexture.onAfterRenderObservable.add(afterRender);
            this._scene = scene;
            this._renderList = renderList;
        }
        // private
        PostProcessRenderPass.prototype._incRefCount = function () {
            if (this._refCount === 0) {
                this._scene.customRenderTargets.push(this._renderTexture);
            }
            return ++this._refCount;
        };
        PostProcessRenderPass.prototype._decRefCount = function () {
            this._refCount--;
            if (this._refCount <= 0) {
                this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
            }
            return this._refCount;
        };
        PostProcessRenderPass.prototype._update = function () {
            this.setRenderList(this._renderList);
        };
        // public
        PostProcessRenderPass.prototype.setRenderList = function (renderList) {
            this._renderTexture.renderList = renderList;
        };
        PostProcessRenderPass.prototype.getRenderTexture = function () {
            return this._renderTexture;
        };
        return PostProcessRenderPass;
    }());
    BABYLON.PostProcessRenderPass = PostProcessRenderPass;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.postProcessRenderPass.js.map
 
var BABYLON;
(function (BABYLON) {
    var PostProcessRenderEffect = (function () {
        function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
            this._engine = engine;
            this._name = name;
            this._singleInstance = singleInstance || true;
            this._getPostProcess = getPostProcess;
            this._cameras = [];
            this._indicesForCamera = [];
            this._postProcesses = {};
            this._renderPasses = {};
            this._renderEffectAsPasses = {};
        }
        Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
            get: function () {
                for (var index in this._postProcesses) {
                    if (!this._postProcesses[index].isSupported) {
                        return false;
                    }
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        PostProcessRenderEffect.prototype._update = function () {
            for (var renderPassName in this._renderPasses) {
                this._renderPasses[renderPassName]._update();
            }
        };
        PostProcessRenderEffect.prototype.addPass = function (renderPass) {
            this._renderPasses[renderPass._name] = renderPass;
            this._linkParameters();
        };
        PostProcessRenderEffect.prototype.removePass = function (renderPass) {
            delete this._renderPasses[renderPass._name];
            this._linkParameters();
        };
        PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
            this._renderEffectAsPasses[renderEffect._name] = renderEffect;
            this._linkParameters();
        };
        PostProcessRenderEffect.prototype.getPass = function (passName) {
            for (var renderPassName in this._renderPasses) {
                if (renderPassName === passName) {
                    return this._renderPasses[passName];
                }
            }
        };
        PostProcessRenderEffect.prototype.emptyPasses = function () {
            this._renderPasses = {};
            this._linkParameters();
        };
        PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
            var cameraKey;
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            for (var i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.name;
                if (this._singleInstance) {
                    cameraKey = 0;
                }
                else {
                    cameraKey = cameraName;
                }
                this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
                var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
                if (!this._indicesForCamera[cameraName]) {
                    this._indicesForCamera[cameraName] = [];
                }
                this._indicesForCamera[cameraName].push(index);
                if (this._cameras.indexOf(camera) === -1) {
                    this._cameras[cameraName] = camera;
                }
                for (var passName in this._renderPasses) {
                    this._renderPasses[passName]._incRefCount();
                }
            }
            this._linkParameters();
        };
        PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            for (var i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.name;
                camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
                var index = this._cameras.indexOf(cameraName);
                this._indicesForCamera.splice(index, 1);
                this._cameras.splice(index, 1);
                for (var passName in this._renderPasses) {
                    this._renderPasses[passName]._decRefCount();
                }
            }
        };
        PostProcessRenderEffect.prototype._enable = function (cameras) {
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            for (var i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.name;
                for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
                    if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
                        cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
                    }
                }
                for (var passName in this._renderPasses) {
                    this._renderPasses[passName]._incRefCount();
                }
            }
        };
        PostProcessRenderEffect.prototype._disable = function (cameras) {
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            for (var i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.Name;
                camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
                for (var passName in this._renderPasses) {
                    this._renderPasses[passName]._decRefCount();
                }
            }
        };
        PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
            if (this._singleInstance) {
                return this._postProcesses[0];
            }
            else {
                return this._postProcesses[camera.name];
            }
        };
        PostProcessRenderEffect.prototype._linkParameters = function () {
            var _this = this;
            for (var index in this._postProcesses) {
                if (this.applyParameters) {
                    this.applyParameters(this._postProcesses[index]);
                }
                this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
                    _this._linkTextures(effect);
                });
            }
        };
        PostProcessRenderEffect.prototype._linkTextures = function (effect) {
            for (var renderPassName in this._renderPasses) {
                effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
            }
            for (var renderEffectName in this._renderEffectAsPasses) {
                effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
            }
        };
        return PostProcessRenderEffect;
    }());
    BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.postProcessRenderEffect.js.map
 
var BABYLON;
(function (BABYLON) {
    var PostProcessRenderPipeline = (function () {
        function PostProcessRenderPipeline(engine, name) {
            this._engine = engine;
            this._name = name;
            this._renderEffects = {};
            this._renderEffectsForIsolatedPass = {};
            this._cameras = [];
        }
        Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
            get: function () {
                for (var renderEffectName in this._renderEffects) {
                    if (!this._renderEffects[renderEffectName].isSupported) {
                        return false;
                    }
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
            this._renderEffects[renderEffect._name] = renderEffect;
        };
        PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
            var renderEffects = this._renderEffects[renderEffectName];
            if (!renderEffects) {
                return;
            }
            renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
        };
        PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
            var renderEffects = this._renderEffects[renderEffectName];
            if (!renderEffects) {
                return;
            }
            renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
        };
        PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            var indicesToDelete = [];
            var i;
            for (i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.name;
                if (this._cameras.indexOf(camera) === -1) {
                    this._cameras[cameraName] = camera;
                }
                else if (unique) {
                    indicesToDelete.push(i);
                }
            }
            for (i = 0; i < indicesToDelete.length; i++) {
                cameras.splice(indicesToDelete[i], 1);
            }
            for (var renderEffectName in this._renderEffects) {
                this._renderEffects[renderEffectName]._attachCameras(_cam);
            }
        };
        PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            for (var renderEffectName in this._renderEffects) {
                this._renderEffects[renderEffectName]._detachCameras(_cam);
            }
            for (var i = 0; i < _cam.length; i++) {
                this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
            }
        };
        PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
            var _this = this;
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            var pass = null;
            var renderEffectName;
            for (renderEffectName in this._renderEffects) {
                pass = this._renderEffects[renderEffectName].getPass(passName);
                if (pass != null) {
                    break;
                }
            }
            if (pass === null) {
                return;
            }
            for (renderEffectName in this._renderEffects) {
                this._renderEffects[renderEffectName]._disable(_cam);
            }
            pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
            for (var i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.name;
                this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
                this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
                this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
                this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
            }
        };
        PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
            var _this = this;
            var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
            for (var i = 0; i < _cam.length; i++) {
                var camera = _cam[i];
                var cameraName = camera.name;
                this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
                this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
            }
            for (var renderEffectName in this._renderEffects) {
                this._renderEffects[renderEffectName]._enable(_cam);
            }
        };
        PostProcessRenderPipeline.prototype._update = function () {
            for (var renderEffectName in this._renderEffects) {
                this._renderEffects[renderEffectName]._update();
            }
            for (var i = 0; i < this._cameras.length; i++) {
                var cameraName = this._cameras[i].name;
                if (this._renderEffectsForIsolatedPass[cameraName]) {
                    this._renderEffectsForIsolatedPass[cameraName]._update();
                }
            }
        };
        PostProcessRenderPipeline.prototype.dispose = function () {
            // Must be implemented by children 
        };
        PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
        PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
        return PostProcessRenderPipeline;
    }());
    BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
 
var BABYLON;
(function (BABYLON) {
    var PostProcessRenderPipelineManager = (function () {
        function PostProcessRenderPipelineManager() {
            this._renderPipelines = {};
        }
        PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
            this._renderPipelines[renderPipeline._name] = renderPipeline;
        };
        PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._attachCameras(cameras, unique);
        };
        PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._detachCameras(cameras);
        };
        PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._enableEffect(renderEffectName, cameras);
        };
        PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._disableEffect(renderEffectName, cameras);
        };
        PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._enableDisplayOnlyPass(passName, cameras);
        };
        PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._disableDisplayOnlyPass(cameras);
        };
        PostProcessRenderPipelineManager.prototype.update = function () {
            for (var renderPipelineName in this._renderPipelines) {
                var pipeline = this._renderPipelines[renderPipelineName];
                if (!pipeline.isSupported) {
                    pipeline.dispose();
                    delete this._renderPipelines[renderPipelineName];
                }
                else {
                    pipeline._update();
                }
            }
        };
        return PostProcessRenderPipelineManager;
    }());
    BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
 
var BABYLON;
(function (BABYLON) {
    var BoundingBoxRenderer = (function () {
        function BoundingBoxRenderer(scene) {
            this.frontColor = new BABYLON.Color3(1, 1, 1);
            this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
            this.showBackLines = true;
            this.renderList = new BABYLON.SmartArray(32);
            this._vertexBuffers = {};
            this._scene = scene;
        }
        BoundingBoxRenderer.prototype._prepareRessources = function () {
            if (this._colorShader) {
                return;
            }
            this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
                attributes: [BABYLON.VertexBuffer.PositionKind],
                uniforms: ["worldViewProjection", "color"]
            });
            var engine = this._scene.getEngine();
            var boxdata = BABYLON.VertexData.CreateBox(1.0);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
            this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
        };
        BoundingBoxRenderer.prototype.reset = function () {
            this.renderList.reset();
        };
        BoundingBoxRenderer.prototype.render = function () {
            if (this.renderList.length === 0) {
                return;
            }
            this._prepareRessources();
            if (!this._colorShader.isReady()) {
                return;
            }
            var engine = this._scene.getEngine();
            engine.setDepthWrite(false);
            this._colorShader._preBind();
            for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
                var boundingBox = this.renderList.data[boundingBoxIndex];
                var min = boundingBox.minimum;
                var max = boundingBox.maximum;
                var diff = max.subtract(min);
                var median = min.add(diff.scale(0.5));
                var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
                    .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
                    .multiply(boundingBox.getWorldMatrix());
                // VBOs
                engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
                if (this.showBackLines) {
                    // Back
                    engine.setDepthFunctionToGreaterOrEqual();
                    this._scene.resetCachedMaterial();
                    this._colorShader.setColor4("color", this.backColor.toColor4());
                    this._colorShader.bind(worldMatrix);
                    // Draw order
                    engine.draw(false, 0, 24);
                }
                // Front
                engine.setDepthFunctionToLess();
                this._scene.resetCachedMaterial();
                this._colorShader.setColor4("color", this.frontColor.toColor4());
                this._colorShader.bind(worldMatrix);
                // Draw order
                engine.draw(false, 0, 24);
            }
            this._colorShader.unbind();
            engine.setDepthFunctionToLessOrEqual();
            engine.setDepthWrite(true);
        };
        BoundingBoxRenderer.prototype.dispose = function () {
            if (!this._colorShader) {
                return;
            }
            this._colorShader.dispose();
            var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            this._scene.getEngine()._releaseBuffer(this._indexBuffer);
        };
        return BoundingBoxRenderer;
    }());
    BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boundingBoxRenderer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Condition = (function () {
        function Condition(actionManager) {
            this._actionManager = actionManager;
        }
        Condition.prototype.isValid = function () {
            return true;
        };
        Condition.prototype._getProperty = function (propertyPath) {
            return this._actionManager._getProperty(propertyPath);
        };
        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
            return this._actionManager._getEffectiveTarget(target, propertyPath);
        };
        Condition.prototype.serialize = function () {
        };
        Condition.prototype._serialize = function (serializedCondition) {
            return {
                type: 2,
                children: [],
                name: serializedCondition.name,
                properties: serializedCondition.properties
            };
        };
        return Condition;
    }());
    BABYLON.Condition = Condition;
    var ValueCondition = (function (_super) {
        __extends(ValueCondition, _super);
        function ValueCondition(actionManager, target, propertyPath, value, operator) {
            if (operator === void 0) { operator = ValueCondition.IsEqual; }
            _super.call(this, actionManager);
            this.propertyPath = propertyPath;
            this.value = value;
            this.operator = operator;
            this._target = target;
            this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        }
        Object.defineProperty(ValueCondition, "IsEqual", {
            get: function () {
                return ValueCondition._IsEqual;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ValueCondition, "IsDifferent", {
            get: function () {
                return ValueCondition._IsDifferent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ValueCondition, "IsGreater", {
            get: function () {
                return ValueCondition._IsGreater;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ValueCondition, "IsLesser", {
            get: function () {
                return ValueCondition._IsLesser;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        ValueCondition.prototype.isValid = function () {
            switch (this.operator) {
                case ValueCondition.IsGreater:
                    return this._effectiveTarget[this._property] > this.value;
                case ValueCondition.IsLesser:
                    return this._effectiveTarget[this._property] < this.value;
                case ValueCondition.IsEqual:
                case ValueCondition.IsDifferent:
                    var check;
                    if (this.value.equals) {
                        check = this.value.equals(this._effectiveTarget[this._property]);
                    }
                    else {
                        check = this.value === this._effectiveTarget[this._property];
                    }
                    return this.operator === ValueCondition.IsEqual ? check : !check;
            }
            return false;
        };
        ValueCondition.prototype.serialize = function () {
            return this._serialize({
                name: "ValueCondition",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
                    { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
                ]
            });
        };
        ValueCondition.GetOperatorName = function (operator) {
            switch (operator) {
                case ValueCondition._IsEqual: return "IsEqual";
                case ValueCondition._IsDifferent: return "IsDifferent";
                case ValueCondition._IsGreater: return "IsGreater";
                case ValueCondition._IsLesser: return "IsLesser";
                default: return "";
            }
        };
        // Statics
        ValueCondition._IsEqual = 0;
        ValueCondition._IsDifferent = 1;
        ValueCondition._IsGreater = 2;
        ValueCondition._IsLesser = 3;
        return ValueCondition;
    }(Condition));
    BABYLON.ValueCondition = ValueCondition;
    var PredicateCondition = (function (_super) {
        __extends(PredicateCondition, _super);
        function PredicateCondition(actionManager, predicate) {
            _super.call(this, actionManager);
            this.predicate = predicate;
        }
        PredicateCondition.prototype.isValid = function () {
            return this.predicate();
        };
        return PredicateCondition;
    }(Condition));
    BABYLON.PredicateCondition = PredicateCondition;
    var StateCondition = (function (_super) {
        __extends(StateCondition, _super);
        function StateCondition(actionManager, target, value) {
            _super.call(this, actionManager);
            this.value = value;
            this._target = target;
        }
        // Methods
        StateCondition.prototype.isValid = function () {
            return this._target.state === this.value;
        };
        StateCondition.prototype.serialize = function () {
            return this._serialize({
                name: "StateCondition",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "value", value: this.value }
                ]
            });
        };
        return StateCondition;
    }(Condition));
    BABYLON.StateCondition = StateCondition;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.condition.js.map
 
var BABYLON;
(function (BABYLON) {
    var Action = (function () {
        function Action(triggerOptions, condition) {
            this.triggerOptions = triggerOptions;
            if (triggerOptions.parameter) {
                this.trigger = triggerOptions.trigger;
                this._triggerParameter = triggerOptions.parameter;
            }
            else {
                this.trigger = triggerOptions;
            }
            this._nextActiveAction = this;
            this._condition = condition;
        }
        // Methods
        Action.prototype._prepare = function () {
        };
        Action.prototype.getTriggerParameter = function () {
            return this._triggerParameter;
        };
        Action.prototype._executeCurrent = function (evt) {
            if (this._nextActiveAction._condition) {
                var condition = this._nextActiveAction._condition;
                var currentRenderId = this._actionManager.getScene().getRenderId();
                // We cache the current evaluation for the current frame
                if (condition._evaluationId === currentRenderId) {
                    if (!condition._currentResult) {
                        return;
                    }
                }
                else {
                    condition._evaluationId = currentRenderId;
                    if (!condition.isValid()) {
                        condition._currentResult = false;
                        return;
                    }
                    condition._currentResult = true;
                }
            }
            this._nextActiveAction.execute(evt);
            this.skipToNextActiveAction();
        };
        Action.prototype.execute = function (evt) {
        };
        Action.prototype.skipToNextActiveAction = function () {
            if (this._nextActiveAction._child) {
                if (!this._nextActiveAction._child._actionManager) {
                    this._nextActiveAction._child._actionManager = this._actionManager;
                }
                this._nextActiveAction = this._nextActiveAction._child;
            }
            else {
                this._nextActiveAction = this;
            }
        };
        Action.prototype.then = function (action) {
            this._child = action;
            action._actionManager = this._actionManager;
            action._prepare();
            return action;
        };
        Action.prototype._getProperty = function (propertyPath) {
            return this._actionManager._getProperty(propertyPath);
        };
        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
            return this._actionManager._getEffectiveTarget(target, propertyPath);
        };
        Action.prototype.serialize = function (parent) {
        };
        // Called by BABYLON.Action objects in serialize(...). Internal use
        Action.prototype._serialize = function (serializedAction, parent) {
            var serializationObject = {
                type: 1,
                children: [],
                name: serializedAction.name,
                properties: serializedAction.properties || []
            };
            // Serialize child
            if (this._child) {
                this._child.serialize(serializationObject);
            }
            // Check if "this" has a condition
            if (this._condition) {
                var serializedCondition = this._condition.serialize();
                serializedCondition.children.push(serializationObject);
                if (parent) {
                    parent.children.push(serializedCondition);
                }
                return serializedCondition;
            }
            if (parent) {
                parent.children.push(serializationObject);
            }
            return serializationObject;
        };
        Action._SerializeValueAsString = function (value) {
            if (typeof value === "number") {
                return value.toString();
            }
            if (typeof value === "boolean") {
                return value ? "true" : "false";
            }
            if (value instanceof BABYLON.Vector2) {
                return value.x + ", " + value.y;
            }
            if (value instanceof BABYLON.Vector3) {
                return value.x + ", " + value.y + ", " + value.z;
            }
            if (value instanceof BABYLON.Color3) {
                return value.r + ", " + value.g + ", " + value.b;
            }
            if (value instanceof BABYLON.Color4) {
                return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
            }
            return value; // string
        };
        Action._GetTargetProperty = function (target) {
            return {
                name: "target",
                targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
                    : target instanceof BABYLON.Light ? "LightProperties"
                        : target instanceof BABYLON.Camera ? "CameraProperties"
                            : "SceneProperties",
                value: target instanceof BABYLON.Scene ? "Scene" : target.name
            };
        };
        return Action;
    }());
    BABYLON.Action = Action;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.action.js.map
 
var BABYLON;
(function (BABYLON) {
    /**
     * ActionEvent is the event beint sent when an action is triggered.
     */
    var ActionEvent = (function () {
        /**
         * @constructor
         * @param source The mesh or sprite that triggered the action.
         * @param pointerX The X mouse cursor position at the time of the event
         * @param pointerY The Y mouse cursor position at the time of the event
         * @param meshUnderPointer The mesh that is currently pointed at (can be null)
         * @param sourceEvent the original (browser) event that triggered the ActionEvent
         */
        function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
            this.source = source;
            this.pointerX = pointerX;
            this.pointerY = pointerY;
            this.meshUnderPointer = meshUnderPointer;
            this.sourceEvent = sourceEvent;
            this.additionalData = additionalData;
        }
        /**
         * Helper function to auto-create an ActionEvent from a source mesh.
         * @param source The source mesh that triggered the event
         * @param evt {Event} The original (browser) event
         */
        ActionEvent.CreateNew = function (source, evt, additionalData) {
            var scene = source.getScene();
            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
        };
        /**
         * Helper function to auto-create an ActionEvent from a source mesh.
         * @param source The source sprite that triggered the event
         * @param scene Scene associated with the sprite
         * @param evt {Event} The original (browser) event
         */
        ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
        };
        /**
         * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
         * @param scene the scene where the event occurred
         * @param evt {Event} The original (browser) event
         */
        ActionEvent.CreateNewFromScene = function (scene, evt) {
            return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
        };
        ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
            return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
        };
        return ActionEvent;
    }());
    BABYLON.ActionEvent = ActionEvent;
    /**
     * Action Manager manages all events to be triggered on a given mesh or the global scene.
     * A single scene can have many Action Managers to handle predefined actions on specific meshes.
     */
    var ActionManager = (function () {
        function ActionManager(scene) {
            // Members
            this.actions = new Array();
            this.hoverCursor = '';
            this._scene = scene;
            scene._actionManagers.push(this);
        }
        Object.defineProperty(ActionManager, "NothingTrigger", {
            get: function () {
                return ActionManager._NothingTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnPickTrigger", {
            get: function () {
                return ActionManager._OnPickTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
            get: function () {
                return ActionManager._OnLeftPickTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnRightPickTrigger", {
            get: function () {
                return ActionManager._OnRightPickTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
            get: function () {
                return ActionManager._OnCenterPickTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnPickDownTrigger", {
            get: function () {
                return ActionManager._OnPickDownTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnPickUpTrigger", {
            get: function () {
                return ActionManager._OnPickUpTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnPickOutTrigger", {
            /// This trigger will only be raised if you also declared a OnPickDown
            get: function () {
                return ActionManager._OnPickOutTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnLongPressTrigger", {
            get: function () {
                return ActionManager._OnLongPressTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
            get: function () {
                return ActionManager._OnPointerOverTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
            get: function () {
                return ActionManager._OnPointerOutTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
            get: function () {
                return ActionManager._OnEveryFrameTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
            get: function () {
                return ActionManager._OnIntersectionEnterTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
            get: function () {
                return ActionManager._OnIntersectionExitTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
            get: function () {
                return ActionManager._OnKeyDownTrigger;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
            get: function () {
                return ActionManager._OnKeyUpTrigger;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        ActionManager.prototype.dispose = function () {
            var index = this._scene._actionManagers.indexOf(this);
            if (index > -1) {
                this._scene._actionManagers.splice(index, 1);
            }
        };
        ActionManager.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Does this action manager handles actions of any of the given triggers
         * @param {number[]} triggers - the triggers to be tested
         * @return {boolean} whether one (or more) of the triggers is handeled
         */
        ActionManager.prototype.hasSpecificTriggers = function (triggers) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (triggers.indexOf(action.trigger) > -1) {
                    return true;
                }
            }
            return false;
        };
        /**
         * Does this action manager handles actions of a given trigger
         * @param {number} trigger - the trigger to be tested
         * @return {boolean} whether the trigger is handeled
         */
        ActionManager.prototype.hasSpecificTrigger = function (trigger) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (action.trigger === trigger) {
                    return true;
                }
            }
            return false;
        };
        Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
            /**
             * Does this action manager has pointer triggers
             * @return {boolean} whether or not it has pointer triggers
             */
            get: function () {
                for (var index = 0; index < this.actions.length; index++) {
                    var action = this.actions[index];
                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
            /**
             * Does this action manager has pick triggers
             * @return {boolean} whether or not it has pick triggers
             */
            get: function () {
                for (var index = 0; index < this.actions.length; index++) {
                    var action = this.actions[index];
                    if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Registers an action to this action manager
         * @param {BABYLON.Action} action - the action to be registered
         * @return {BABYLON.Action} the action amended (prepared) after registration
         */
        ActionManager.prototype.registerAction = function (action) {
            if (action.trigger === ActionManager.OnEveryFrameTrigger) {
                if (this.getScene().actionManager !== this) {
                    BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
                    return null;
                }
            }
            this.actions.push(action);
            action._actionManager = this;
            action._prepare();
            return action;
        };
        /**
         * Process a specific trigger
         * @param {number} trigger - the trigger to process
         * @param evt {BABYLON.ActionEvent} the event details to be processed
         */
        ActionManager.prototype.processTrigger = function (trigger, evt) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (action.trigger === trigger) {
                    if (trigger === ActionManager.OnKeyUpTrigger
                        || trigger === ActionManager.OnKeyDownTrigger) {
                        var parameter = action.getTriggerParameter();
                        if (parameter) {
                            var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
                            var actualkey = String.fromCharCode(unicode).toLowerCase();
                            if (actualkey !== parameter.toLowerCase()) {
                                continue;
                            }
                        }
                    }
                    action._executeCurrent(evt);
                }
            }
        };
        ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
            var properties = propertyPath.split(".");
            for (var index = 0; index < properties.length - 1; index++) {
                target = target[properties[index]];
            }
            return target;
        };
        ActionManager.prototype._getProperty = function (propertyPath) {
            var properties = propertyPath.split(".");
            return properties[properties.length - 1];
        };
        ActionManager.prototype.serialize = function (name) {
            var root = {
                children: [],
                name: name,
                type: 3,
                properties: [] // Empty for root but required
            };
            for (var i = 0; i < this.actions.length; i++) {
                var triggerObject = {
                    type: 0,
                    children: [],
                    name: ActionManager.GetTriggerName(this.actions[i].trigger),
                    properties: []
                };
                var triggerOptions = this.actions[i].triggerOptions;
                if (triggerOptions && typeof triggerOptions !== "number") {
                    if (triggerOptions.parameter instanceof BABYLON.Node) {
                        triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
                    }
                    else {
                        var parameter = {};
                        BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
                        if (triggerOptions.parameter.mesh) {
                            parameter._meshId = triggerOptions.parameter.mesh.id;
                        }
                        triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
                    }
                }
                // Serialize child action, recursively
                this.actions[i].serialize(triggerObject);
                // Add serialized trigger
                root.children.push(triggerObject);
            }
            return root;
        };
        ActionManager.Parse = function (parsedActions, object, scene) {
            var actionManager = new BABYLON.ActionManager(scene);
            if (object === null)
                scene.actionManager = actionManager;
            else
                object.actionManager = actionManager;
            // instanciate a new object
            var instanciate = function (name, params) {
                var newInstance = Object.create(BABYLON[name].prototype);
                newInstance.constructor.apply(newInstance, params);
                return newInstance;
            };
            var parseParameter = function (name, value, target, propertyPath) {
                if (propertyPath === null) {
                    // String, boolean or float
                    var floatValue = parseFloat(value);
                    if (value === "true" || value === "false")
                        return value === "true";
                    else
                        return isNaN(floatValue) ? value : floatValue;
                }
                var effectiveTarget = propertyPath.split(".");
                var values = value.split(",");
                // Get effective Target
                for (var i = 0; i < effectiveTarget.length; i++) {
                    target = target[effectiveTarget[i]];
                }
                // Return appropriate value with its type
                if (typeof (target) === "boolean")
                    return values[0] === "true";
                if (typeof (target) === "string")
                    return values[0];
                // Parameters with multiple values such as Vector3 etc.
                var split = new Array();
                for (var i = 0; i < values.length; i++)
                    split.push(parseFloat(values[i]));
                if (target instanceof BABYLON.Vector3)
                    return BABYLON.Vector3.FromArray(split);
                if (target instanceof BABYLON.Vector4)
                    return BABYLON.Vector4.FromArray(split);
                if (target instanceof BABYLON.Color3)
                    return BABYLON.Color3.FromArray(split);
                if (target instanceof BABYLON.Color4)
                    return BABYLON.Color4.FromArray(split);
                return parseFloat(values[0]);
            };
            // traverse graph per trigger
            var traverse = function (parsedAction, trigger, condition, action, combineArray) {
                if (combineArray === void 0) { combineArray = null; }
                if (parsedAction.detached)
                    return;
                var parameters = new Array();
                var target = null;
                var propertyPath = null;
                var combine = parsedAction.combine && parsedAction.combine.length > 0;
                // Parameters
                if (parsedAction.type === 2)
                    parameters.push(actionManager);
                else
                    parameters.push(trigger);
                if (combine) {
                    var actions = new Array();
                    for (var j = 0; j < parsedAction.combine.length; j++) {
                        traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
                    }
                    parameters.push(actions);
                }
                else {
                    for (var i = 0; i < parsedAction.properties.length; i++) {
                        var value = parsedAction.properties[i].value;
                        var name = parsedAction.properties[i].name;
                        var targetType = parsedAction.properties[i].targetType;
                        if (name === "target")
                            if (targetType !== null && targetType === "SceneProperties")
                                value = target = scene;
                            else
                                value = target = scene.getNodeByName(value);
                        else if (name === "parent")
                            value = scene.getNodeByName(value);
                        else if (name === "sound")
                            value = scene.getSoundByName(value);
                        else if (name !== "propertyPath") {
                            if (parsedAction.type === 2 && name === "operator")
                                value = BABYLON.ValueCondition[value];
                            else
                                value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
                        }
                        else {
                            propertyPath = value;
                        }
                        parameters.push(value);
                    }
                }
                if (combineArray === null) {
                    parameters.push(condition);
                }
                else {
                    parameters.push(null);
                }
                // If interpolate value action
                if (parsedAction.name === "InterpolateValueAction") {
                    var param = parameters[parameters.length - 2];
                    parameters[parameters.length - 1] = param;
                    parameters[parameters.length - 2] = condition;
                }
                // Action or condition(s) and not CombineAction
                var newAction = instanciate(parsedAction.name, parameters);
                if (newAction instanceof BABYLON.Condition && condition !== null) {
                    var nothing = new BABYLON.DoNothingAction(trigger, condition);
                    if (action)
                        action.then(nothing);
                    else
                        actionManager.registerAction(nothing);
                    action = nothing;
                }
                if (combineArray === null) {
                    if (newAction instanceof BABYLON.Condition) {
                        condition = newAction;
                        newAction = action;
                    }
                    else {
                        condition = null;
                        if (action)
                            action.then(newAction);
                        else
                            actionManager.registerAction(newAction);
                    }
                }
                else {
                    combineArray.push(newAction);
                }
                for (var i = 0; i < parsedAction.children.length; i++)
                    traverse(parsedAction.children[i], trigger, condition, newAction, null);
            };
            // triggers
            for (var i = 0; i < parsedActions.children.length; i++) {
                var triggerParams;
                var trigger = parsedActions.children[i];
                if (trigger.properties.length > 0) {
                    var param = trigger.properties[0].value;
                    var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
                    if (value._meshId) {
                        value.mesh = scene.getMeshByID(value._meshId);
                    }
                    triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
                }
                else
                    triggerParams = BABYLON.ActionManager[trigger.name];
                for (var j = 0; j < trigger.children.length; j++) {
                    if (!trigger.detached)
                        traverse(trigger.children[j], triggerParams, null, null);
                }
            }
        };
        ActionManager.GetTriggerName = function (trigger) {
            switch (trigger) {
                case 0: return "NothingTrigger";
                case 1: return "OnPickTrigger";
                case 2: return "OnLeftPickTrigger";
                case 3: return "OnRightPickTrigger";
                case 4: return "OnCenterPickTrigger";
                case 5: return "OnPickDownTrigger";
                case 6: return "OnPickUpTrigger";
                case 7: return "OnLongPressTrigger";
                case 8: return "OnPointerOverTrigger";
                case 9: return "OnPointerOutTrigger";
                case 10: return "OnEveryFrameTrigger";
                case 11: return "OnIntersectionEnterTrigger";
                case 12: return "OnIntersectionExitTrigger";
                case 13: return "OnKeyDownTrigger";
                case 14: return "OnKeyUpTrigger";
                case 15: return "OnPickOutTrigger";
                default: return "";
            }
        };
        // Statics
        ActionManager._NothingTrigger = 0;
        ActionManager._OnPickTrigger = 1;
        ActionManager._OnLeftPickTrigger = 2;
        ActionManager._OnRightPickTrigger = 3;
        ActionManager._OnCenterPickTrigger = 4;
        ActionManager._OnPickDownTrigger = 5;
        ActionManager._OnPickUpTrigger = 6;
        ActionManager._OnLongPressTrigger = 7;
        ActionManager._OnPointerOverTrigger = 8;
        ActionManager._OnPointerOutTrigger = 9;
        ActionManager._OnEveryFrameTrigger = 10;
        ActionManager._OnIntersectionEnterTrigger = 11;
        ActionManager._OnIntersectionExitTrigger = 12;
        ActionManager._OnKeyDownTrigger = 13;
        ActionManager._OnKeyUpTrigger = 14;
        ActionManager._OnPickOutTrigger = 15;
        ActionManager.DragMovementThreshold = 10; // in pixels
        ActionManager.LongPressDelay = 500; // in milliseconds
        return ActionManager;
    }());
    BABYLON.ActionManager = ActionManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.actionManager.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var InterpolateValueAction = (function (_super) {
        __extends(InterpolateValueAction, _super);
        function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
            if (duration === void 0) { duration = 1000; }
            _super.call(this, triggerOptions, condition);
            this.propertyPath = propertyPath;
            this.value = value;
            this.duration = duration;
            this.stopOtherAnimations = stopOtherAnimations;
            this.onInterpolationDone = onInterpolationDone;
            this._target = this._effectiveTarget = target;
        }
        InterpolateValueAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        };
        InterpolateValueAction.prototype.execute = function () {
            var scene = this._actionManager.getScene();
            var keys = [
                {
                    frame: 0,
                    value: this._effectiveTarget[this._property]
                }, {
                    frame: 100,
                    value: this.value
                }
            ];
            var dataType;
            if (typeof this.value === "number") {
                dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
            }
            else if (this.value instanceof BABYLON.Color3) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
            }
            else if (this.value instanceof BABYLON.Vector3) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
            }
            else if (this.value instanceof BABYLON.Matrix) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
            }
            else if (this.value instanceof BABYLON.Quaternion) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
            }
            else {
                BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
                return;
            }
            var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            animation.setKeys(keys);
            if (this.stopOtherAnimations) {
                scene.stopAnimation(this._effectiveTarget);
            }
            scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
        };
        InterpolateValueAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "InterpolateValueAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
                    { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
                    { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
                ]
            }, parent);
        };
        return InterpolateValueAction;
    }(BABYLON.Action));
    BABYLON.InterpolateValueAction = InterpolateValueAction;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.interpolateValueAction.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var SwitchBooleanAction = (function (_super) {
        __extends(SwitchBooleanAction, _super);
        function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
            _super.call(this, triggerOptions, condition);
            this.propertyPath = propertyPath;
            this._target = this._effectiveTarget = target;
        }
        SwitchBooleanAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        };
        SwitchBooleanAction.prototype.execute = function () {
            this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
        };
        SwitchBooleanAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SwitchBooleanAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath }
                ]
            }, parent);
        };
        return SwitchBooleanAction;
    }(BABYLON.Action));
    BABYLON.SwitchBooleanAction = SwitchBooleanAction;
    var SetStateAction = (function (_super) {
        __extends(SetStateAction, _super);
        function SetStateAction(triggerOptions, target, value, condition) {
            _super.call(this, triggerOptions, condition);
            this.value = value;
            this._target = target;
        }
        SetStateAction.prototype.execute = function () {
            this._target.state = this.value;
        };
        SetStateAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SetStateAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "value", value: this.value }
                ]
            }, parent);
        };
        return SetStateAction;
    }(BABYLON.Action));
    BABYLON.SetStateAction = SetStateAction;
    var SetValueAction = (function (_super) {
        __extends(SetValueAction, _super);
        function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
            _super.call(this, triggerOptions, condition);
            this.propertyPath = propertyPath;
            this.value = value;
            this._target = this._effectiveTarget = target;
        }
        SetValueAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        };
        SetValueAction.prototype.execute = function () {
            this._effectiveTarget[this._property] = this.value;
            if (this._target.markAsDirty) {
                this._target.markAsDirty(this._property);
            }
        };
        SetValueAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SetValueAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
                ]
            }, parent);
        };
        return SetValueAction;
    }(BABYLON.Action));
    BABYLON.SetValueAction = SetValueAction;
    var IncrementValueAction = (function (_super) {
        __extends(IncrementValueAction, _super);
        function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
            _super.call(this, triggerOptions, condition);
            this.propertyPath = propertyPath;
            this.value = value;
            this._target = this._effectiveTarget = target;
        }
        IncrementValueAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
            if (typeof this._effectiveTarget[this._property] !== "number") {
                BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
            }
        };
        IncrementValueAction.prototype.execute = function () {
            this._effectiveTarget[this._property] += this.value;
            if (this._target.markAsDirty) {
                this._target.markAsDirty(this._property);
            }
        };
        IncrementValueAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "IncrementValueAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
                ]
            }, parent);
        };
        return IncrementValueAction;
    }(BABYLON.Action));
    BABYLON.IncrementValueAction = IncrementValueAction;
    var PlayAnimationAction = (function (_super) {
        __extends(PlayAnimationAction, _super);
        function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
            _super.call(this, triggerOptions, condition);
            this.from = from;
            this.to = to;
            this.loop = loop;
            this._target = target;
        }
        PlayAnimationAction.prototype._prepare = function () {
        };
        PlayAnimationAction.prototype.execute = function () {
            var scene = this._actionManager.getScene();
            scene.beginAnimation(this._target, this.from, this.to, this.loop);
        };
        PlayAnimationAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "PlayAnimationAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "from", value: String(this.from) },
                    { name: "to", value: String(this.to) },
                    { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
                ]
            }, parent);
        };
        return PlayAnimationAction;
    }(BABYLON.Action));
    BABYLON.PlayAnimationAction = PlayAnimationAction;
    var StopAnimationAction = (function (_super) {
        __extends(StopAnimationAction, _super);
        function StopAnimationAction(triggerOptions, target, condition) {
            _super.call(this, triggerOptions, condition);
            this._target = target;
        }
        StopAnimationAction.prototype._prepare = function () {
        };
        StopAnimationAction.prototype.execute = function () {
            var scene = this._actionManager.getScene();
            scene.stopAnimation(this._target);
        };
        StopAnimationAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "StopAnimationAction",
                properties: [BABYLON.Action._GetTargetProperty(this._target)]
            }, parent);
        };
        return StopAnimationAction;
    }(BABYLON.Action));
    BABYLON.StopAnimationAction = StopAnimationAction;
    var DoNothingAction = (function (_super) {
        __extends(DoNothingAction, _super);
        function DoNothingAction(triggerOptions, condition) {
            if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
            _super.call(this, triggerOptions, condition);
        }
        DoNothingAction.prototype.execute = function () {
        };
        DoNothingAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "DoNothingAction",
                properties: []
            }, parent);
        };
        return DoNothingAction;
    }(BABYLON.Action));
    BABYLON.DoNothingAction = DoNothingAction;
    var CombineAction = (function (_super) {
        __extends(CombineAction, _super);
        function CombineAction(triggerOptions, children, condition) {
            _super.call(this, triggerOptions, condition);
            this.children = children;
        }
        CombineAction.prototype._prepare = function () {
            for (var index = 0; index < this.children.length; index++) {
                this.children[index]._actionManager = this._actionManager;
                this.children[index]._prepare();
            }
        };
        CombineAction.prototype.execute = function (evt) {
            for (var index = 0; index < this.children.length; index++) {
                this.children[index].execute(evt);
            }
        };
        CombineAction.prototype.serialize = function (parent) {
            var serializationObject = _super.prototype._serialize.call(this, {
                name: "CombineAction",
                properties: [],
                combine: []
            }, parent);
            for (var i = 0; i < this.children.length; i++) {
                serializationObject.combine.push(this.children[i].serialize(null));
            }
            return serializationObject;
        };
        return CombineAction;
    }(BABYLON.Action));
    BABYLON.CombineAction = CombineAction;
    var ExecuteCodeAction = (function (_super) {
        __extends(ExecuteCodeAction, _super);
        function ExecuteCodeAction(triggerOptions, func, condition) {
            _super.call(this, triggerOptions, condition);
            this.func = func;
        }
        ExecuteCodeAction.prototype.execute = function (evt) {
            this.func(evt);
        };
        return ExecuteCodeAction;
    }(BABYLON.Action));
    BABYLON.ExecuteCodeAction = ExecuteCodeAction;
    var SetParentAction = (function (_super) {
        __extends(SetParentAction, _super);
        function SetParentAction(triggerOptions, target, parent, condition) {
            _super.call(this, triggerOptions, condition);
            this._target = target;
            this._parent = parent;
        }
        SetParentAction.prototype._prepare = function () {
        };
        SetParentAction.prototype.execute = function () {
            if (this._target.parent === this._parent) {
                return;
            }
            var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
            invertParentWorldMatrix.invert();
            this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
            this._target.parent = this._parent;
        };
        SetParentAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SetParentAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    BABYLON.Action._GetTargetProperty(this._parent),
                ]
            }, parent);
        };
        return SetParentAction;
    }(BABYLON.Action));
    BABYLON.SetParentAction = SetParentAction;
    var PlaySoundAction = (function (_super) {
        __extends(PlaySoundAction, _super);
        function PlaySoundAction(triggerOptions, sound, condition) {
            _super.call(this, triggerOptions, condition);
            this._sound = sound;
        }
        PlaySoundAction.prototype._prepare = function () {
        };
        PlaySoundAction.prototype.execute = function () {
            if (this._sound !== undefined)
                this._sound.play();
        };
        PlaySoundAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "PlaySoundAction",
                properties: [{ name: "sound", value: this._sound.name }]
            }, parent);
        };
        return PlaySoundAction;
    }(BABYLON.Action));
    BABYLON.PlaySoundAction = PlaySoundAction;
    var StopSoundAction = (function (_super) {
        __extends(StopSoundAction, _super);
        function StopSoundAction(triggerOptions, sound, condition) {
            _super.call(this, triggerOptions, condition);
            this._sound = sound;
        }
        StopSoundAction.prototype._prepare = function () {
        };
        StopSoundAction.prototype.execute = function () {
            if (this._sound !== undefined)
                this._sound.stop();
        };
        StopSoundAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "StopSoundAction",
                properties: [{ name: "sound", value: this._sound.name }]
            }, parent);
        };
        return StopSoundAction;
    }(BABYLON.Action));
    BABYLON.StopSoundAction = StopSoundAction;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.directActions.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Geometry = (function () {
        function Geometry(id, scene, vertexData, updatable, mesh) {
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this._totalVertices = 0;
            this._isDisposed = false;
            this.id = id;
            this._engine = scene.getEngine();
            this._meshes = [];
            this._scene = scene;
            //Init vertex buffer cache
            this._vertexBuffers = {};
            this._indices = [];
            // vertexData
            if (vertexData) {
                this.setAllVerticesData(vertexData, updatable);
            }
            else {
                this._totalVertices = 0;
                this._indices = [];
            }
            // applyToMesh
            if (mesh) {
                if (mesh instanceof BABYLON.LinesMesh) {
                    this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
                    this.updateExtend();
                }
                this.applyToMesh(mesh);
                mesh.computeWorldMatrix(true);
            }
        }
        Object.defineProperty(Geometry.prototype, "boundingBias", {
            /**
             *  The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
             * @returns The Bias Vector
             */
            get: function () {
                return this._boundingBias;
            },
            set: function (value) {
                if (this._boundingBias && this._boundingBias.equals(value)) {
                    return;
                }
                this._boundingBias = value.clone();
                this.updateBoundingInfo(true, null);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Geometry.prototype, "extend", {
            get: function () {
                return this._extend;
            },
            enumerable: true,
            configurable: true
        });
        Geometry.prototype.getScene = function () {
            return this._scene;
        };
        Geometry.prototype.getEngine = function () {
            return this._engine;
        };
        Geometry.prototype.isReady = function () {
            return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
        };
        Object.defineProperty(Geometry.prototype, "doNotSerialize", {
            get: function () {
                for (var index = 0; index < this._meshes.length; index++) {
                    if (!this._meshes[index].doNotSerialize) {
                        return false;
                    }
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
            vertexData.applyToGeometry(this, updatable);
            this.notifyUpdate();
        };
        Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
            var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
            this.setVerticesBuffer(buffer);
        };
        Geometry.prototype.setVerticesBuffer = function (buffer) {
            var kind = buffer.getKind();
            if (this._vertexBuffers[kind]) {
                this._vertexBuffers[kind].dispose();
            }
            this._vertexBuffers[kind] = buffer;
            if (kind === BABYLON.VertexBuffer.PositionKind) {
                var data = buffer.getData();
                var stride = buffer.getStrideSize();
                this._totalVertices = data.length / stride;
                this.updateExtend(data, stride);
                var meshes = this._meshes;
                var numOfMeshes = meshes.length;
                for (var index = 0; index < numOfMeshes; index++) {
                    var mesh = meshes[index];
                    mesh._resetPointsArrayCache();
                    mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
                    mesh._createGlobalSubMesh();
                    mesh.computeWorldMatrix(true);
                }
            }
            this.notifyUpdate(kind);
        };
        Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
            var vertexBuffer = this.getVertexBuffer(kind);
            if (!vertexBuffer) {
                return;
            }
            vertexBuffer.updateDirectly(data, offset);
            this.notifyUpdate(kind);
        };
        Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
            var vertexBuffer = this.getVertexBuffer(kind);
            if (!vertexBuffer) {
                return;
            }
            vertexBuffer.update(data);
            if (kind === BABYLON.VertexBuffer.PositionKind) {
                var stride = vertexBuffer.getStrideSize();
                this._totalVertices = data.length / stride;
                this.updateBoundingInfo(updateExtends, data);
            }
            this.notifyUpdate(kind);
        };
        Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
            if (updateExtends) {
                this.updateExtend(data);
            }
            var meshes = this._meshes;
            var numOfMeshes = meshes.length;
            for (var index = 0; index < numOfMeshes; index++) {
                var mesh = meshes[index];
                mesh._resetPointsArrayCache();
                if (updateExtends) {
                    mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
                    for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
                        var subMesh = mesh.subMeshes[subIndex];
                        subMesh.refreshBoundingInfo();
                    }
                }
            }
        };
        Geometry.prototype.getTotalVertices = function () {
            if (!this.isReady()) {
                return 0;
            }
            return this._totalVertices;
        };
        Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
            var vertexBuffer = this.getVertexBuffer(kind);
            if (!vertexBuffer) {
                return null;
            }
            var orig = vertexBuffer.getData();
            if (!copyWhenShared || this._meshes.length === 1) {
                return orig;
            }
            else {
                var len = orig.length;
                var copy = [];
                for (var i = 0; i < len; i++) {
                    copy.push(orig[i]);
                }
                return copy;
            }
        };
        Geometry.prototype.getVertexBuffer = function (kind) {
            if (!this.isReady()) {
                return null;
            }
            return this._vertexBuffers[kind];
        };
        Geometry.prototype.getVertexBuffers = function () {
            if (!this.isReady()) {
                return null;
            }
            return this._vertexBuffers;
        };
        Geometry.prototype.isVerticesDataPresent = function (kind) {
            if (!this._vertexBuffers) {
                if (this._delayInfo) {
                    return this._delayInfo.indexOf(kind) !== -1;
                }
                return false;
            }
            return this._vertexBuffers[kind] !== undefined;
        };
        Geometry.prototype.getVerticesDataKinds = function () {
            var result = [];
            var kind;
            if (!this._vertexBuffers && this._delayInfo) {
                for (kind in this._delayInfo) {
                    result.push(kind);
                }
            }
            else {
                for (kind in this._vertexBuffers) {
                    result.push(kind);
                }
            }
            return result;
        };
        Geometry.prototype.setIndices = function (indices, totalVertices) {
            if (this._indexBuffer) {
                this._engine._releaseBuffer(this._indexBuffer);
            }
            this._indices = indices;
            if (this._meshes.length !== 0 && this._indices) {
                this._indexBuffer = this._engine.createIndexBuffer(this._indices);
            }
            if (totalVertices !== undefined) {
                this._totalVertices = totalVertices;
            }
            var meshes = this._meshes;
            var numOfMeshes = meshes.length;
            for (var index = 0; index < numOfMeshes; index++) {
                meshes[index]._createGlobalSubMesh();
            }
            this.notifyUpdate();
        };
        Geometry.prototype.getTotalIndices = function () {
            if (!this.isReady()) {
                return 0;
            }
            return this._indices.length;
        };
        Geometry.prototype.getIndices = function (copyWhenShared) {
            if (!this.isReady()) {
                return null;
            }
            var orig = this._indices;
            if (!copyWhenShared || this._meshes.length === 1) {
                return orig;
            }
            else {
                var len = orig.length;
                var copy = [];
                for (var i = 0; i < len; i++) {
                    copy.push(orig[i]);
                }
                return copy;
            }
        };
        Geometry.prototype.getIndexBuffer = function () {
            if (!this.isReady()) {
                return null;
            }
            return this._indexBuffer;
        };
        Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
            var meshes = this._meshes;
            var index = meshes.indexOf(mesh);
            if (index === -1) {
                return;
            }
            for (var kind in this._vertexBuffers) {
                this._vertexBuffers[kind].dispose();
            }
            if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
                this._indexBuffer = null;
            }
            meshes.splice(index, 1);
            mesh._geometry = null;
            if (meshes.length === 0 && shouldDispose) {
                this.dispose();
            }
        };
        Geometry.prototype.applyToMesh = function (mesh) {
            if (mesh._geometry === this) {
                return;
            }
            var previousGeometry = mesh._geometry;
            if (previousGeometry) {
                previousGeometry.releaseForMesh(mesh);
            }
            var meshes = this._meshes;
            // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
            mesh._geometry = this;
            this._scene.pushGeometry(this);
            meshes.push(mesh);
            if (this.isReady()) {
                this._applyToMesh(mesh);
            }
            else {
                mesh._boundingInfo = this._boundingInfo;
            }
        };
        Geometry.prototype.updateExtend = function (data, stride) {
            if (data === void 0) { data = null; }
            if (!data) {
                data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
            }
            this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
        };
        Geometry.prototype._applyToMesh = function (mesh) {
            var numOfMeshes = this._meshes.length;
            // vertexBuffers
            for (var kind in this._vertexBuffers) {
                if (numOfMeshes === 1) {
                    this._vertexBuffers[kind].create();
                }
                this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
                if (kind === BABYLON.VertexBuffer.PositionKind) {
                    mesh._resetPointsArrayCache();
                    if (!this._extend) {
                        this.updateExtend(this._vertexBuffers[kind].getData());
                    }
                    mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
                    mesh._createGlobalSubMesh();
                    //bounding info was just created again, world matrix should be applied again.
                    mesh._updateBoundingInfo();
                }
            }
            // indexBuffer
            if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
                this._indexBuffer = this._engine.createIndexBuffer(this._indices);
            }
            if (this._indexBuffer) {
                this._indexBuffer.references = numOfMeshes;
            }
        };
        Geometry.prototype.notifyUpdate = function (kind) {
            if (this.onGeometryUpdated) {
                this.onGeometryUpdated(this, kind);
            }
        };
        Geometry.prototype.load = function (scene, onLoaded) {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                return;
            }
            if (this.isReady()) {
                if (onLoaded) {
                    onLoaded();
                }
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
            this._queueLoad(scene, onLoaded);
        };
        Geometry.prototype._queueLoad = function (scene, onLoaded) {
            var _this = this;
            scene._addPendingData(this);
            BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
                _this._delayLoadingFunction(JSON.parse(data), _this);
                _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
                _this._delayInfo = [];
                scene._removePendingData(_this);
                var meshes = _this._meshes;
                var numOfMeshes = meshes.length;
                for (var index = 0; index < numOfMeshes; index++) {
                    _this._applyToMesh(meshes[index]);
                }
                if (onLoaded) {
                    onLoaded();
                }
            }, function () { }, scene.database);
        };
        /**
         * Invert the geometry to move from a right handed system to a left handed one.
         */
        Geometry.prototype.toLeftHanded = function () {
            // Flip faces
            var tIndices = this.getIndices(false);
            if (tIndices != null && tIndices.length > 0) {
                for (var i = 0; i < tIndices.length; i += 3) {
                    var tTemp = tIndices[i + 0];
                    tIndices[i + 0] = tIndices[i + 2];
                    tIndices[i + 2] = tTemp;
                }
                this.setIndices(tIndices);
            }
            // Negate position.z
            var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
            if (tPositions != null && tPositions.length > 0) {
                for (var i = 0; i < tPositions.length; i += 3) {
                    tPositions[i + 2] = -tPositions[i + 2];
                }
                this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
            }
            // Negate normal.z
            var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
            if (tNormals != null && tNormals.length > 0) {
                for (var i = 0; i < tNormals.length; i += 3) {
                    tNormals[i + 2] = -tNormals[i + 2];
                }
                this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
            }
        };
        Geometry.prototype.isDisposed = function () {
            return this._isDisposed;
        };
        Geometry.prototype.dispose = function () {
            var meshes = this._meshes;
            var numOfMeshes = meshes.length;
            var index;
            for (index = 0; index < numOfMeshes; index++) {
                this.releaseForMesh(meshes[index]);
            }
            this._meshes = [];
            for (var kind in this._vertexBuffers) {
                this._vertexBuffers[kind].dispose();
            }
            this._vertexBuffers = {};
            this._totalVertices = 0;
            if (this._indexBuffer) {
                this._engine._releaseBuffer(this._indexBuffer);
            }
            this._indexBuffer = null;
            this._indices = [];
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this.delayLoadingFile = null;
            this._delayLoadingFunction = null;
            this._delayInfo = [];
            this._boundingInfo = null;
            this._scene.removeGeometry(this);
            this._isDisposed = true;
        };
        Geometry.prototype.copy = function (id) {
            var vertexData = new BABYLON.VertexData();
            vertexData.indices = [];
            var indices = this.getIndices();
            for (var index = 0; index < indices.length; index++) {
                vertexData.indices.push(indices[index]);
            }
            var updatable = false;
            var stopChecking = false;
            var kind;
            for (kind in this._vertexBuffers) {
                // using slice() to make a copy of the array and not just reference it
                var data = this.getVerticesData(kind);
                if (data instanceof Float32Array) {
                    vertexData.set(new Float32Array(data), kind);
                }
                else {
                    vertexData.set(data.slice(0), kind);
                }
                if (!stopChecking) {
                    updatable = this.getVertexBuffer(kind).isUpdatable();
                    stopChecking = !updatable;
                }
            }
            var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
            geometry.delayLoadState = this.delayLoadState;
            geometry.delayLoadingFile = this.delayLoadingFile;
            geometry._delayLoadingFunction = this._delayLoadingFunction;
            for (kind in this._delayInfo) {
                geometry._delayInfo = geometry._delayInfo || [];
                geometry._delayInfo.push(kind);
            }
            // Bounding info
            geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
            return geometry;
        };
        Geometry.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.id = this.id;
            if (BABYLON.Tags.HasTags(this)) {
                serializationObject.tags = BABYLON.Tags.GetTags(this);
            }
            return serializationObject;
        };
        Geometry.prototype.serializeVerticeData = function () {
            var serializationObject = this.serialize();
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
                serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
                serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
                serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
                serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
                serializationObject.matricesIndices._isExpanded = true;
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
            }
            serializationObject.indices = this.getIndices();
            return serializationObject;
        };
        // Statics
        Geometry.ExtractFromMesh = function (mesh, id) {
            var geometry = mesh._geometry;
            if (!geometry) {
                return null;
            }
            return geometry.copy(id);
        };
        /**
         * You should now use Tools.RandomId(), this method is still here for legacy reasons.
         * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
         * Be aware Math.random() could cause collisions, but:
         * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
         */
        Geometry.RandomId = function () {
            return BABYLON.Tools.RandomId();
        };
        Geometry.ImportGeometry = function (parsedGeometry, mesh) {
            var scene = mesh.getScene();
            // Geometry
            var geometryId = parsedGeometry.geometryId;
            if (geometryId) {
                var geometry = scene.getGeometryByID(geometryId);
                if (geometry) {
                    geometry.applyToMesh(mesh);
                }
            }
            else if (parsedGeometry instanceof ArrayBuffer) {
                var binaryInfo = mesh._binaryInfo;
                if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
                    var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
                }
                if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
                    var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
                }
                if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
                    var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
                }
                if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
                    var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
                }
                if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
                    var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
                }
                if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
                    var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
                }
                if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
                    var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
                }
                if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
                    var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
                }
                if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
                    var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
                }
                if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
                    var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
                }
                if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
                    var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
                }
                if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
                    var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
                    mesh.setIndices(indicesData);
                }
                if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
                    var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
                    mesh.subMeshes = [];
                    for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
                        var materialIndex = subMeshesData[(i * 5) + 0];
                        var verticesStart = subMeshesData[(i * 5) + 1];
                        var verticesCount = subMeshesData[(i * 5) + 2];
                        var indexStart = subMeshesData[(i * 5) + 3];
                        var indexCount = subMeshesData[(i * 5) + 4];
                        var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
                    }
                }
            }
            else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
                mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
                mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
                if (parsedGeometry.uvs) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
                }
                if (parsedGeometry.uvs2) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
                }
                if (parsedGeometry.uvs3) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
                }
                if (parsedGeometry.uvs4) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
                }
                if (parsedGeometry.uvs5) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
                }
                if (parsedGeometry.uvs6) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
                }
                if (parsedGeometry.colors) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
                }
                if (parsedGeometry.matricesIndices) {
                    if (!parsedGeometry.matricesIndices._isExpanded) {
                        var floatIndices = [];
                        for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
                            var matricesIndex = parsedGeometry.matricesIndices[i];
                            floatIndices.push(matricesIndex & 0x000000FF);
                            floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
                            floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
                            floatIndices.push(matricesIndex >> 24);
                        }
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
                    }
                    else {
                        delete parsedGeometry.matricesIndices._isExpanded;
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
                    }
                }
                if (parsedGeometry.matricesIndicesExtra) {
                    if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
                        var floatIndices = [];
                        for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
                            var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
                            floatIndices.push(matricesIndex & 0x000000FF);
                            floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
                            floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
                            floatIndices.push(matricesIndex >> 24);
                        }
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
                    }
                    else {
                        delete parsedGeometry.matricesIndices._isExpanded;
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
                    }
                }
                if (parsedGeometry.matricesWeights) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
                }
                if (parsedGeometry.matricesWeightsExtra) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
                }
                mesh.setIndices(parsedGeometry.indices);
            }
            // SubMeshes
            if (parsedGeometry.subMeshes) {
                mesh.subMeshes = [];
                for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
                    var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
                    var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
                }
            }
            // Flat shading
            if (mesh._shouldGenerateFlatShading) {
                mesh.convertToFlatShadedMesh();
                delete mesh._shouldGenerateFlatShading;
            }
            // Update
            mesh.computeWorldMatrix(true);
            // Octree
            if (scene['_selectionOctree']) {
                scene['_selectionOctree'].addMesh(mesh);
            }
        };
        Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
            if (scene.getGeometryByID(parsedVertexData.id)) {
                return null; // null since geometry could be something else than a box...
            }
            var geometry = new Geometry(parsedVertexData.id, scene);
            BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
            if (parsedVertexData.delayLoadingFile) {
                geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
                geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
                geometry._delayInfo = [];
                if (parsedVertexData.hasUVs) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
                }
                if (parsedVertexData.hasUVs2) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (parsedVertexData.hasUVs3) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
                }
                if (parsedVertexData.hasUVs4) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
                }
                if (parsedVertexData.hasUVs5) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
                }
                if (parsedVertexData.hasUVs6) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
                }
                if (parsedVertexData.hasColors) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
                }
                if (parsedVertexData.hasMatricesIndices) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                }
                if (parsedVertexData.hasMatricesWeights) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                }
                geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
            }
            else {
                BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
            }
            scene.pushGeometry(geometry, true);
            return geometry;
        };
        return Geometry;
    }());
    BABYLON.Geometry = Geometry;
    /////// Primitives //////////////////////////////////////////////
    var Geometry;
    (function (Geometry) {
        var Primitives;
        (function (Primitives) {
            /// Abstract class
            var _Primitive = (function (_super) {
                __extends(_Primitive, _super);
                function _Primitive(id, scene, _canBeRegenerated, mesh) {
                    _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
                    this._canBeRegenerated = _canBeRegenerated;
                    this._beingRegenerated = true;
                    this.regenerate();
                    this._beingRegenerated = false;
                }
                _Primitive.prototype.canBeRegenerated = function () {
                    return this._canBeRegenerated;
                };
                _Primitive.prototype.regenerate = function () {
                    if (!this._canBeRegenerated) {
                        return;
                    }
                    this._beingRegenerated = true;
                    this.setAllVerticesData(this._regenerateVertexData(), false);
                    this._beingRegenerated = false;
                };
                _Primitive.prototype.asNewGeometry = function (id) {
                    return _super.prototype.copy.call(this, id);
                };
                // overrides
                _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
                    if (!this._beingRegenerated) {
                        return;
                    }
                    _super.prototype.setAllVerticesData.call(this, vertexData, false);
                };
                _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
                    if (!this._beingRegenerated) {
                        return;
                    }
                    _super.prototype.setVerticesData.call(this, kind, data, false);
                };
                // to override
                // protected
                _Primitive.prototype._regenerateVertexData = function () {
                    throw new Error("Abstract method");
                };
                _Primitive.prototype.copy = function (id) {
                    throw new Error("Must be overriden in sub-classes.");
                };
                _Primitive.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.canBeRegenerated = this.canBeRegenerated();
                    return serializationObject;
                };
                return _Primitive;
            }(Geometry));
            Primitives._Primitive = _Primitive;
            var Ribbon = (function (_super) {
                __extends(Ribbon, _super);
                // Members
                function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.pathArray = pathArray;
                    this.closeArray = closeArray;
                    this.closePath = closePath;
                    this.offset = offset;
                    this.side = side;
                }
                Ribbon.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
                };
                Ribbon.prototype.copy = function (id) {
                    return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
                };
                return Ribbon;
            }(_Primitive));
            Primitives.Ribbon = Ribbon;
            var Box = (function (_super) {
                __extends(Box, _super);
                // Members
                function Box(id, scene, size, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.size = size;
                    this.side = side;
                }
                Box.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
                };
                Box.prototype.copy = function (id) {
                    return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
                };
                Box.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.size = this.size;
                    return serializationObject;
                };
                Box.Parse = function (parsedBox, scene) {
                    if (scene.getGeometryByID(parsedBox.id)) {
                        return null; // null since geometry could be something else than a box...
                    }
                    var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
                    scene.pushGeometry(box, true);
                    return box;
                };
                return Box;
            }(_Primitive));
            Primitives.Box = Box;
            var Sphere = (function (_super) {
                __extends(Sphere, _super);
                function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.segments = segments;
                    this.diameter = diameter;
                    this.side = side;
                }
                Sphere.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
                };
                Sphere.prototype.copy = function (id) {
                    return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
                };
                Sphere.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.segments = this.segments;
                    serializationObject.diameter = this.diameter;
                    return serializationObject;
                };
                Sphere.Parse = function (parsedSphere, scene) {
                    if (scene.getGeometryByID(parsedSphere.id)) {
                        return null; // null since geometry could be something else than a sphere...
                    }
                    var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
                    scene.pushGeometry(sphere, true);
                    return sphere;
                };
                return Sphere;
            }(_Primitive));
            Primitives.Sphere = Sphere;
            var Disc = (function (_super) {
                __extends(Disc, _super);
                // Members
                function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.radius = radius;
                    this.tessellation = tessellation;
                    this.side = side;
                }
                Disc.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
                };
                Disc.prototype.copy = function (id) {
                    return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
                };
                return Disc;
            }(_Primitive));
            Primitives.Disc = Disc;
            var Cylinder = (function (_super) {
                __extends(Cylinder, _super);
                function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
                    if (subdivisions === void 0) { subdivisions = 1; }
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.height = height;
                    this.diameterTop = diameterTop;
                    this.diameterBottom = diameterBottom;
                    this.tessellation = tessellation;
                    this.subdivisions = subdivisions;
                    this.side = side;
                }
                Cylinder.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
                };
                Cylinder.prototype.copy = function (id) {
                    return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
                };
                Cylinder.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.height = this.height;
                    serializationObject.diameterTop = this.diameterTop;
                    serializationObject.diameterBottom = this.diameterBottom;
                    serializationObject.tessellation = this.tessellation;
                    return serializationObject;
                };
                Cylinder.Parse = function (parsedCylinder, scene) {
                    if (scene.getGeometryByID(parsedCylinder.id)) {
                        return null; // null since geometry could be something else than a cylinder...
                    }
                    var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
                    scene.pushGeometry(cylinder, true);
                    return cylinder;
                };
                return Cylinder;
            }(_Primitive));
            Primitives.Cylinder = Cylinder;
            var Torus = (function (_super) {
                __extends(Torus, _super);
                function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.diameter = diameter;
                    this.thickness = thickness;
                    this.tessellation = tessellation;
                    this.side = side;
                }
                Torus.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
                };
                Torus.prototype.copy = function (id) {
                    return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
                };
                Torus.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.diameter = this.diameter;
                    serializationObject.thickness = this.thickness;
                    serializationObject.tessellation = this.tessellation;
                    return serializationObject;
                };
                Torus.Parse = function (parsedTorus, scene) {
                    if (scene.getGeometryByID(parsedTorus.id)) {
                        return null; // null since geometry could be something else than a torus...
                    }
                    var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
                    scene.pushGeometry(torus, true);
                    return torus;
                };
                return Torus;
            }(_Primitive));
            Primitives.Torus = Torus;
            var Ground = (function (_super) {
                __extends(Ground, _super);
                function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.width = width;
                    this.height = height;
                    this.subdivisions = subdivisions;
                }
                Ground.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
                };
                Ground.prototype.copy = function (id) {
                    return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
                };
                Ground.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.width = this.width;
                    serializationObject.height = this.height;
                    serializationObject.subdivisions = this.subdivisions;
                    return serializationObject;
                };
                Ground.Parse = function (parsedGround, scene) {
                    if (scene.getGeometryByID(parsedGround.id)) {
                        return null; // null since geometry could be something else than a ground...
                    }
                    var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
                    scene.pushGeometry(ground, true);
                    return ground;
                };
                return Ground;
            }(_Primitive));
            Primitives.Ground = Ground;
            var TiledGround = (function (_super) {
                __extends(TiledGround, _super);
                function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.xmin = xmin;
                    this.zmin = zmin;
                    this.xmax = xmax;
                    this.zmax = zmax;
                    this.subdivisions = subdivisions;
                    this.precision = precision;
                }
                TiledGround.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
                };
                TiledGround.prototype.copy = function (id) {
                    return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
                };
                return TiledGround;
            }(_Primitive));
            Primitives.TiledGround = TiledGround;
            var Plane = (function (_super) {
                __extends(Plane, _super);
                function Plane(id, scene, size, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.size = size;
                    this.side = side;
                }
                Plane.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
                };
                Plane.prototype.copy = function (id) {
                    return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
                };
                Plane.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.size = this.size;
                    return serializationObject;
                };
                Plane.Parse = function (parsedPlane, scene) {
                    if (scene.getGeometryByID(parsedPlane.id)) {
                        return null; // null since geometry could be something else than a ground...
                    }
                    var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
                    scene.pushGeometry(plane, true);
                    return plane;
                };
                return Plane;
            }(_Primitive));
            Primitives.Plane = Plane;
            var TorusKnot = (function (_super) {
                __extends(TorusKnot, _super);
                function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
                    if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
                    _super.call(this, id, scene, canBeRegenerated, mesh);
                    this.radius = radius;
                    this.tube = tube;
                    this.radialSegments = radialSegments;
                    this.tubularSegments = tubularSegments;
                    this.p = p;
                    this.q = q;
                    this.side = side;
                }
                TorusKnot.prototype._regenerateVertexData = function () {
                    return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
                };
                TorusKnot.prototype.copy = function (id) {
                    return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
                };
                TorusKnot.prototype.serialize = function () {
                    var serializationObject = _super.prototype.serialize.call(this);
                    serializationObject.radius = this.radius;
                    serializationObject.tube = this.tube;
                    serializationObject.radialSegments = this.radialSegments;
                    serializationObject.tubularSegments = this.tubularSegments;
                    serializationObject.p = this.p;
                    serializationObject.q = this.q;
                    return serializationObject;
                };
                ;
                TorusKnot.Parse = function (parsedTorusKnot, scene) {
                    if (scene.getGeometryByID(parsedTorusKnot.id)) {
                        return null; // null since geometry could be something else than a ground...
                    }
                    var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
                    BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
                    scene.pushGeometry(torusKnot, true);
                    return torusKnot;
                };
                return TorusKnot;
            }(_Primitive));
            Primitives.TorusKnot = TorusKnot;
        })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
    })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.geometry.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var GroundMesh = (function (_super) {
        __extends(GroundMesh, _super);
        function GroundMesh(name, scene) {
            _super.call(this, name, scene);
            this.generateOctree = false;
            this._worldInverse = new BABYLON.Matrix();
        }
        Object.defineProperty(GroundMesh.prototype, "subdivisions", {
            get: function () {
                return Math.min(this._subdivisionsX, this._subdivisionsY);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
            get: function () {
                return this._subdivisionsX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
            get: function () {
                return this._subdivisionsY;
            },
            enumerable: true,
            configurable: true
        });
        GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
            if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
            this._subdivisionsX = chunksCount;
            this._subdivisionsY = chunksCount;
            this.subdivide(chunksCount);
            this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
        };
        /**
         * Returns a height (y) value in the Worl system :
         * the ground altitude at the coordinates (x, z) expressed in the World system.
         * Returns the ground y position if (x, z) are outside the ground surface.
         * Not pertinent if the ground is rotated.
         */
        GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
            // express x and y in the ground local system
            x -= this.position.x;
            z -= this.position.z;
            x /= this.scaling.x;
            z /= this.scaling.z;
            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
                return this.position.y;
            }
            if (!this._heightQuads || this._heightQuads.length == 0) {
                this._initHeightQuads();
                this._computeHeightQuads();
            }
            var facet = this._getFacetAt(x, z);
            var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
            // return y in the World system
            return y * this.scaling.y + this.position.y;
        };
        /**
         * Returns a normalized vector (Vector3) orthogonal to the ground
         * at the ground coordinates (x, z) expressed in the World system.
         * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
         * Not pertinent if the ground is rotated.
         */
        GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
            var normal = new BABYLON.Vector3(0, 1, 0);
            this.getNormalAtCoordinatesToRef(x, z, normal);
            return normal;
        };
        /**
         * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
         * at the ground coordinates (x, z) expressed in the World system.
         * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
         * Not pertinent if the ground is rotated.
         */
        GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
            // express x and y in the ground local system
            x -= this.position.x;
            z -= this.position.z;
            x /= this.scaling.x;
            z /= this.scaling.z;
            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
                return;
            }
            if (!this._heightQuads || this._heightQuads.length == 0) {
                this._initHeightQuads();
                this._computeHeightQuads();
            }
            var facet = this._getFacetAt(x, z);
            ref.x = facet.x;
            ref.y = facet.y;
            ref.z = facet.z;
        };
        /**
        * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
        * if the ground has been updated.
        * This can be used in the render loop
        */
        GroundMesh.prototype.updateCoordinateHeights = function () {
            if (!this._heightQuads || this._heightQuads.length == 0) {
                this._initHeightQuads();
            }
            this._computeHeightQuads();
        };
        // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
        GroundMesh.prototype._getFacetAt = function (x, z) {
            // retrieve col and row from x, z coordinates in the ground local system
            var subdivisionsX = this._subdivisionsX;
            var subdivisionsY = this._subdivisionsY;
            var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
            var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
            var quad = this._heightQuads[row * this._subdivisionsX + col];
            var facet;
            if (z < quad.slope.x * x + quad.slope.y) {
                facet = quad.facet1;
            }
            else {
                facet = quad.facet2;
            }
            return facet;
        };
        //  Creates and populates the heightMap array with "facet" elements :
        // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
        // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
        // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
        // facet2 :  Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
        GroundMesh.prototype._initHeightQuads = function () {
            var subdivisionsX = this._subdivisionsX;
            var subdivisionsY = this._subdivisionsY;
            this._heightQuads = new Array();
            for (var row = 0; row < subdivisionsY; row++) {
                for (var col = 0; col < subdivisionsX; col++) {
                    var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
                    this._heightQuads[row * subdivisionsX + col] = quad;
                }
            }
        };
        // Compute each quad element values and update the the heightMap array :
        // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
        // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
        // facet2 :  Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
        GroundMesh.prototype._computeHeightQuads = function () {
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var v1 = BABYLON.Tmp.Vector3[3];
            var v2 = BABYLON.Tmp.Vector3[2];
            var v3 = BABYLON.Tmp.Vector3[1];
            var v4 = BABYLON.Tmp.Vector3[0];
            var v1v2 = BABYLON.Tmp.Vector3[4];
            var v1v3 = BABYLON.Tmp.Vector3[5];
            var v1v4 = BABYLON.Tmp.Vector3[6];
            var norm1 = BABYLON.Tmp.Vector3[7];
            var norm2 = BABYLON.Tmp.Vector3[8];
            var i = 0;
            var j = 0;
            var k = 0;
            var cd = 0; // 2D slope coefficient : z = cd * x + h
            var h = 0;
            var d1 = 0; // facet plane equation : ax + by + cz + d = 0
            var d2 = 0;
            var subdivisionsX = this._subdivisionsX;
            var subdivisionsY = this._subdivisionsY;
            for (var row = 0; row < subdivisionsY; row++) {
                for (var col = 0; col < subdivisionsX; col++) {
                    i = col * 3;
                    j = row * (subdivisionsX + 1) * 3;
                    k = (row + 1) * (subdivisionsX + 1) * 3;
                    v1.x = positions[j + i];
                    v1.y = positions[j + i + 1];
                    v1.z = positions[j + i + 2];
                    v2.x = positions[j + i + 3];
                    v2.y = positions[j + i + 4];
                    v2.z = positions[j + i + 5];
                    v3.x = positions[k + i];
                    v3.y = positions[k + i + 1];
                    v3.z = positions[k + i + 2];
                    v4.x = positions[k + i + 3];
                    v4.y = positions[k + i + 4];
                    v4.z = positions[k + i + 5];
                    // 2D slope V1V4
                    cd = (v4.z - v1.z) / (v4.x - v1.x);
                    h = v1.z - cd * v1.x; // v1 belongs to the slope
                    // facet equations :
                    // we compute each facet normal vector
                    // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
                    // we compute the value d by applying the equation to v1 which belongs to the plane
                    // then we store the facet equation in a Vector4
                    v2.subtractToRef(v1, v1v2);
                    v3.subtractToRef(v1, v1v3);
                    v4.subtractToRef(v1, v1v4);
                    BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
                    BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
                    norm1.normalize();
                    norm2.normalize();
                    d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
                    d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
                    var quad = this._heightQuads[row * subdivisionsX + col];
                    quad.slope.copyFromFloats(cd, h);
                    quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
                    quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
                }
            }
        };
        return GroundMesh;
    }(BABYLON.Mesh));
    BABYLON.GroundMesh = GroundMesh;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.groundMesh.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var LinesMesh = (function (_super) {
        __extends(LinesMesh, _super);
        function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
            if (parent === void 0) { parent = null; }
            _super.call(this, name, scene, parent, source, doNotCloneChildren);
            this.color = new BABYLON.Color3(1, 1, 1);
            this.alpha = 1;
            this._positionBuffer = {};
            if (source) {
                this.color = source.color.clone();
                this.alpha = source.alpha;
            }
            this._intersectionThreshold = 0.1;
            this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
                attributes: [BABYLON.VertexBuffer.PositionKind],
                uniforms: ["worldViewProjection", "color"],
                needAlphaBlending: true
            });
            this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
        }
        Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
            /**
             * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
             * This margin is expressed in world space coordinates, so its value may vary.
             * Default value is 0.1
             * @returns the intersection Threshold value.
             */
            get: function () {
                return this._intersectionThreshold;
            },
            /**
             * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
             * This margin is expressed in world space coordinates, so its value may vary.
             * @param value the new threshold to apply
             */
            set: function (value) {
                if (this._intersectionThreshold === value) {
                    return;
                }
                this._intersectionThreshold = value;
                if (this.geometry) {
                    this.geometry.boundingBias = new BABYLON.Vector2(0, value);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LinesMesh.prototype, "material", {
            get: function () {
                return this._colorShader;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        LinesMesh.prototype.createInstance = function (name) {
            BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
            return null;
        };
        LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
            var engine = this.getScene().getEngine();
            this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
            // VBOs
            engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
            // Color
            this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
        };
        LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
            if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
                return;
            }
            var engine = this.getScene().getEngine();
            // Draw order
            engine.draw(false, subMesh.indexStart, subMesh.indexCount);
        };
        LinesMesh.prototype.dispose = function (doNotRecurse) {
            this._colorShader.dispose();
            _super.prototype.dispose.call(this, doNotRecurse);
        };
        LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
            return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
        };
        return LinesMesh;
    }(BABYLON.Mesh));
    BABYLON.LinesMesh = LinesMesh;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.linesMesh.js.map
 
var BABYLON;
(function (BABYLON) {
    var DefaultLoadingScreen = (function () {
        function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
            var _this = this;
            if (_loadingText === void 0) { _loadingText = ""; }
            if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
            this._renderingCanvas = _renderingCanvas;
            this._loadingText = _loadingText;
            this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
            // Resize
            this._resizeLoadingUI = function () {
                var canvasRect = _this._renderingCanvas.getBoundingClientRect();
                _this._loadingDiv.style.position = "absolute";
                _this._loadingDiv.style.left = canvasRect.left + "px";
                _this._loadingDiv.style.top = canvasRect.top + "px";
                _this._loadingDiv.style.width = canvasRect.width + "px";
                _this._loadingDiv.style.height = canvasRect.height + "px";
            };
        }
        DefaultLoadingScreen.prototype.displayLoadingUI = function () {
            var _this = this;
            if (this._loadingDiv) {
                // Do not add a loading screen if there is already one  
                return;
            }
            this._loadingDiv = document.createElement("div");
            this._loadingDiv.id = "babylonjsLoadingDiv";
            this._loadingDiv.style.opacity = "0";
            this._loadingDiv.style.transition = "opacity 1.5s ease";
            // Loading text
            this._loadingTextDiv = document.createElement("div");
            this._loadingTextDiv.style.position = "absolute";
            this._loadingTextDiv.style.left = "0";
            this._loadingTextDiv.style.top = "50%";
            this._loadingTextDiv.style.marginTop = "80px";
            this._loadingTextDiv.style.width = "100%";
            this._loadingTextDiv.style.height = "20px";
            this._loadingTextDiv.style.fontFamily = "Arial";
            this._loadingTextDiv.style.fontSize = "14px";
            this._loadingTextDiv.style.color = "white";
            this._loadingTextDiv.style.textAlign = "center";
            this._loadingTextDiv.innerHTML = "Loading";
            this._loadingDiv.appendChild(this._loadingTextDiv);
            //set the predefined text
            this._loadingTextDiv.innerHTML = this._loadingText;
            // Loading img
            var imgBack = new Image();
            imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
            imgBack.style.position = "absolute";
            imgBack.style.left = "50%";
            imgBack.style.top = "50%";
            imgBack.style.marginLeft = "-50px";
            imgBack.style.marginTop = "-50px";
            imgBack.style.transition = "transform 1.0s ease";
            imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
            var deg = 360;
            var onTransitionEnd = function () {
                deg += 360;
                imgBack.style.transform = "rotateZ(" + deg + "deg)";
                imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
            };
            imgBack.addEventListener("transitionend", onTransitionEnd);
            imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
            this._loadingDiv.appendChild(imgBack);
            // front image
            var imgFront = new Image();
            imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
            imgFront.style.position = "absolute";
            imgFront.style.left = "50%";
            imgFront.style.top = "50%";
            imgFront.style.marginLeft = "-50px";
            imgFront.style.marginTop = "-50px";
            this._loadingDiv.appendChild(imgFront);
            this._resizeLoadingUI();
            window.addEventListener("resize", this._resizeLoadingUI);
            this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
            document.body.appendChild(this._loadingDiv);
            setTimeout(function () {
                _this._loadingDiv.style.opacity = "1";
                imgBack.style.transform = "rotateZ(360deg)";
                imgBack.style.webkitTransform = "rotateZ(360deg)";
            }, 0);
        };
        DefaultLoadingScreen.prototype.hideLoadingUI = function () {
            var _this = this;
            if (!this._loadingDiv) {
                return;
            }
            var onTransitionEnd = function () {
                if (!_this._loadingDiv) {
                    return;
                }
                document.body.removeChild(_this._loadingDiv);
                window.removeEventListener("resize", _this._resizeLoadingUI);
                _this._loadingDiv = null;
            };
            this._loadingDiv.style.opacity = "0";
            this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
        };
        Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
            set: function (text) {
                this._loadingText = text;
                if (this._loadingTextDiv) {
                    this._loadingTextDiv.innerHTML = this._loadingText;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
            get: function () {
                return this._loadingDivBackgroundColor;
            },
            set: function (color) {
                this._loadingDivBackgroundColor = color;
                if (!this._loadingDiv) {
                    return;
                }
                this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
            },
            enumerable: true,
            configurable: true
        });
        return DefaultLoadingScreen;
    }());
    BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.loadingScreen.js.map
 
var BABYLON;
(function (BABYLON) {
    var AudioEngine = (function () {
        function AudioEngine() {
            this._audioContext = null;
            this._audioContextInitialized = false;
            this.canUseWebAudio = false;
            this.WarnedWebAudioUnsupported = false;
            this.unlocked = false;
            this.isMP3supported = false;
            this.isOGGsupported = false;
            if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                this.canUseWebAudio = true;
            }
            var audioElem = document.createElement('audio');
            if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
                this.isMP3supported = true;
            }
            if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
                this.isOGGsupported = true;
            }
            if (/iPad|iPhone|iPod/.test(navigator.platform)) {
                this._unlockiOSaudio();
            }
            else {
                this.unlocked = true;
            }
        }
        Object.defineProperty(AudioEngine.prototype, "audioContext", {
            get: function () {
                if (!this._audioContextInitialized) {
                    this._initializeAudioContext();
                }
                return this._audioContext;
            },
            enumerable: true,
            configurable: true
        });
        AudioEngine.prototype._unlockiOSaudio = function () {
            var _this = this;
            var unlockaudio = function () {
                var buffer = _this.audioContext.createBuffer(1, 1, 22050);
                var source = _this.audioContext.createBufferSource();
                source.buffer = buffer;
                source.connect(_this.audioContext.destination);
                source.start(0);
                setTimeout(function () {
                    if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
                        _this.unlocked = true;
                        window.removeEventListener('touchend', unlockaudio, false);
                        if (_this.onAudioUnlocked) {
                            _this.onAudioUnlocked();
                        }
                    }
                }, 0);
            };
            window.addEventListener('touchend', unlockaudio, false);
        };
        AudioEngine.prototype._initializeAudioContext = function () {
            try {
                if (this.canUseWebAudio) {
                    this._audioContext = new AudioContext();
                    // create a global volume gain node 
                    this.masterGain = this._audioContext.createGain();
                    this.masterGain.gain.value = 1;
                    this.masterGain.connect(this._audioContext.destination);
                    this._audioContextInitialized = true;
                }
            }
            catch (e) {
                this.canUseWebAudio = false;
                BABYLON.Tools.Error("Web Audio: " + e.message);
            }
        };
        AudioEngine.prototype.dispose = function () {
            if (this.canUseWebAudio && this._audioContextInitialized) {
                if (this._connectedAnalyser) {
                    this._connectedAnalyser.stopDebugCanvas();
                    this._connectedAnalyser.dispose();
                    this.masterGain.disconnect();
                    this.masterGain.connect(this._audioContext.destination);
                    this._connectedAnalyser = null;
                }
                this.masterGain.gain.value = 1;
            }
            this.WarnedWebAudioUnsupported = false;
        };
        AudioEngine.prototype.getGlobalVolume = function () {
            if (this.canUseWebAudio && this._audioContextInitialized) {
                return this.masterGain.gain.value;
            }
            else {
                return -1;
            }
        };
        AudioEngine.prototype.setGlobalVolume = function (newVolume) {
            if (this.canUseWebAudio && this._audioContextInitialized) {
                this.masterGain.gain.value = newVolume;
            }
        };
        AudioEngine.prototype.connectToAnalyser = function (analyser) {
            if (this._connectedAnalyser) {
                this._connectedAnalyser.stopDebugCanvas();
            }
            if (this.canUseWebAudio && this._audioContextInitialized) {
                this._connectedAnalyser = analyser;
                this.masterGain.disconnect();
                this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
            }
        };
        return AudioEngine;
    }());
    BABYLON.AudioEngine = AudioEngine;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.audioEngine.js.map
 
var BABYLON;
(function (BABYLON) {
    var Sound = (function () {
        /**
        * Create a sound and attach it to a scene
        * @param name Name of your sound
        * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
        * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
        * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
        */
        function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
            var _this = this;
            this.autoplay = false;
            this.loop = false;
            this.useCustomAttenuation = false;
            this.spatialSound = false;
            this.refDistance = 1;
            this.rolloffFactor = 1;
            this.maxDistance = 100;
            this.distanceModel = "linear";
            this._panningModel = "equalpower";
            this._playbackRate = 1;
            this._streaming = false;
            this._startTime = 0;
            this._startOffset = 0;
            this._position = BABYLON.Vector3.Zero();
            this._localDirection = new BABYLON.Vector3(1, 0, 0);
            this._volume = 1;
            this._isLoaded = false;
            this._isReadyToPlay = false;
            this.isPlaying = false;
            this.isPaused = false;
            this._isDirectional = false;
            // Used if you'd like to create a directional sound.
            // If not set, the sound will be omnidirectional
            this._coneInnerAngle = 360;
            this._coneOuterAngle = 360;
            this._coneOuterGain = 0;
            this._isOutputConnected = false;
            this._urlType = "Unknown";
            this.name = name;
            this._scene = scene;
            this._readyToPlayCallback = readyToPlayCallback;
            // Default custom attenuation function is a linear attenuation
            this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
                if (currentDistance < maxDistance) {
                    return currentVolume * (1 - currentDistance / maxDistance);
                }
                else {
                    return 0;
                }
            };
            if (options) {
                this.autoplay = options.autoplay || false;
                this.loop = options.loop || false;
                // if volume === 0, we need another way to check this option
                if (options.volume !== undefined) {
                    this._volume = options.volume;
                }
                this.spatialSound = options.spatialSound || false;
                this.maxDistance = options.maxDistance || 100;
                this.useCustomAttenuation = options.useCustomAttenuation || false;
                this.rolloffFactor = options.rolloffFactor || 1;
                this.refDistance = options.refDistance || 1;
                this.distanceModel = options.distanceModel || "linear";
                this._playbackRate = options.playbackRate || 1;
                this._streaming = options.streaming || false;
            }
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
                this._soundGain.gain.value = this._volume;
                this._inputAudioNode = this._soundGain;
                this._ouputAudioNode = this._soundGain;
                if (this.spatialSound) {
                    this._createSpatialParameters();
                }
                this._scene.mainSoundTrack.AddSound(this);
                var validParameter = true;
                // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
                if (urlOrArrayBuffer) {
                    if (typeof (urlOrArrayBuffer) === "string")
                        this._urlType = "String";
                    if (Array.isArray(urlOrArrayBuffer))
                        this._urlType = "Array";
                    if (urlOrArrayBuffer instanceof ArrayBuffer)
                        this._urlType = "ArrayBuffer";
                    var urls = [];
                    var codecSupportedFound = false;
                    switch (this._urlType) {
                        case "ArrayBuffer":
                            if (urlOrArrayBuffer.byteLength > 0) {
                                codecSupportedFound = true;
                                this._soundLoaded(urlOrArrayBuffer);
                            }
                            break;
                        case "String":
                            urls.push(urlOrArrayBuffer);
                        case "Array":
                            if (urls.length === 0)
                                urls = urlOrArrayBuffer;
                            // If we found a supported format, we load it immediately and stop the loop
                            for (var i = 0; i < urls.length; i++) {
                                var url = urls[i];
                                if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
                                    codecSupportedFound = true;
                                }
                                if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
                                    codecSupportedFound = true;
                                }
                                if (url.indexOf(".wav", url.length - 4) !== -1) {
                                    codecSupportedFound = true;
                                }
                                if (codecSupportedFound) {
                                    // Loading sound using XHR2
                                    if (!this._streaming) {
                                        BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
                                    }
                                    else {
                                        this._htmlAudioElement = new Audio(url);
                                        this._htmlAudioElement.controls = false;
                                        this._htmlAudioElement.loop = this.loop;
                                        this._htmlAudioElement.crossOrigin = "anonymous";
                                        this._htmlAudioElement.preload = "auto";
                                        this._htmlAudioElement.addEventListener("canplaythrough", function () {
                                            _this._isReadyToPlay = true;
                                            if (_this.autoplay) {
                                                _this.play();
                                            }
                                            if (_this._readyToPlayCallback) {
                                                _this._readyToPlayCallback();
                                            }
                                        });
                                        document.body.appendChild(this._htmlAudioElement);
                                    }
                                    break;
                                }
                            }
                            break;
                        default:
                            validParameter = false;
                            break;
                    }
                    if (!validParameter) {
                        BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
                    }
                    else {
                        if (!codecSupportedFound) {
                            this._isReadyToPlay = true;
                            // Simulating a ready to play event to avoid breaking code path
                            if (this._readyToPlayCallback) {
                                window.setTimeout(function () {
                                    _this._readyToPlayCallback();
                                }, 1000);
                            }
                        }
                    }
                }
            }
            else {
                // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
                this._scene.mainSoundTrack.AddSound(this);
                if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
                    BABYLON.Tools.Error("Web Audio is not supported by your browser.");
                    BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
                }
                // Simulating a ready to play event to avoid breaking code for non web audio browsers
                if (this._readyToPlayCallback) {
                    window.setTimeout(function () {
                        _this._readyToPlayCallback();
                    }, 1000);
                }
            }
        }
        Sound.prototype.dispose = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
                if (this.isPlaying) {
                    this.stop();
                }
                this._isReadyToPlay = false;
                if (this.soundTrackId === -1) {
                    this._scene.mainSoundTrack.RemoveSound(this);
                }
                else {
                    this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
                }
                if (this._soundGain) {
                    this._soundGain.disconnect();
                    this._soundGain = null;
                }
                if (this._soundPanner) {
                    this._soundPanner.disconnect();
                    this._soundPanner = null;
                }
                if (this._soundSource) {
                    this._soundSource.disconnect();
                    this._soundSource = null;
                }
                this._audioBuffer = null;
                if (this._htmlAudioElement) {
                    this._htmlAudioElement.pause();
                    this._htmlAudioElement.src = "";
                    document.body.removeChild(this._htmlAudioElement);
                }
                if (this._connectedMesh) {
                    this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
                    this._connectedMesh = null;
                }
            }
        };
        Sound.prototype._soundLoaded = function (audioData) {
            var _this = this;
            this._isLoaded = true;
            BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
                _this._audioBuffer = buffer;
                _this._isReadyToPlay = true;
                if (_this.autoplay) {
                    _this.play();
                }
                if (_this._readyToPlayCallback) {
                    _this._readyToPlayCallback();
                }
            }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
        };
        Sound.prototype.setAudioBuffer = function (audioBuffer) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                this._audioBuffer = audioBuffer;
                this._isReadyToPlay = true;
            }
        };
        Sound.prototype.updateOptions = function (options) {
            if (options) {
                this.loop = options.loop || this.loop;
                this.maxDistance = options.maxDistance || this.maxDistance;
                this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
                this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
                this.refDistance = options.refDistance || this.refDistance;
                this.distanceModel = options.distanceModel || this.distanceModel;
                this._playbackRate = options.playbackRate || this._playbackRate;
                this._updateSpatialParameters();
                if (this.isPlaying) {
                    if (this._streaming) {
                        this._htmlAudioElement.playbackRate = this._playbackRate;
                    }
                    else {
                        this._soundSource.playbackRate.value = this._playbackRate;
                    }
                }
            }
        };
        Sound.prototype._createSpatialParameters = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (this._scene.headphone) {
                    this._panningModel = "HRTF";
                }
                this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
                this._updateSpatialParameters();
                this._soundPanner.connect(this._ouputAudioNode);
                this._inputAudioNode = this._soundPanner;
            }
        };
        Sound.prototype._updateSpatialParameters = function () {
            if (this.spatialSound) {
                if (this.useCustomAttenuation) {
                    // Tricks to disable in a way embedded Web Audio attenuation 
                    this._soundPanner.distanceModel = "linear";
                    this._soundPanner.maxDistance = Number.MAX_VALUE;
                    this._soundPanner.refDistance = 1;
                    this._soundPanner.rolloffFactor = 1;
                    this._soundPanner.panningModel = this._panningModel;
                }
                else {
                    this._soundPanner.distanceModel = this.distanceModel;
                    this._soundPanner.maxDistance = this.maxDistance;
                    this._soundPanner.refDistance = this.refDistance;
                    this._soundPanner.rolloffFactor = this.rolloffFactor;
                    this._soundPanner.panningModel = this._panningModel;
                }
            }
        };
        Sound.prototype.switchPanningModelToHRTF = function () {
            this._panningModel = "HRTF";
            this._switchPanningModel();
        };
        Sound.prototype.switchPanningModelToEqualPower = function () {
            this._panningModel = "equalpower";
            this._switchPanningModel();
        };
        Sound.prototype._switchPanningModel = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
                this._soundPanner.panningModel = this._panningModel;
            }
        };
        Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (this._isOutputConnected) {
                    this._ouputAudioNode.disconnect();
                }
                this._ouputAudioNode.connect(soundTrackAudioNode);
                this._isOutputConnected = true;
            }
        };
        /**
        * Transform this sound into a directional source
        * @param coneInnerAngle Size of the inner cone in degree
        * @param coneOuterAngle Size of the outer cone in degree
        * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
        */
        Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
            if (coneOuterAngle < coneInnerAngle) {
                BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
                return;
            }
            this._coneInnerAngle = coneInnerAngle;
            this._coneOuterAngle = coneOuterAngle;
            this._coneOuterGain = coneOuterGain;
            this._isDirectional = true;
            if (this.isPlaying && this.loop) {
                this.stop();
                this.play();
            }
        };
        Sound.prototype.setPosition = function (newPosition) {
            this._position = newPosition;
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
                this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
            }
        };
        Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
            this._localDirection = newLocalDirection;
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
                this._updateDirection();
            }
        };
        Sound.prototype._updateDirection = function () {
            var mat = this._connectedMesh.getWorldMatrix();
            var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
            direction.normalize();
            this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
        };
        Sound.prototype.updateDistanceFromListener = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
                var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
                this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
            }
        };
        Sound.prototype.setAttenuationFunction = function (callback) {
            this._customAttenuationFunction = callback;
        };
        /**
        * Play the sound
        * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
        * @param offset (optional) Start the sound setting it at a specific time
        */
        Sound.prototype.play = function (time, offset) {
            var _this = this;
            if (this._isReadyToPlay && this._scene.audioEnabled) {
                try {
                    if (this._startOffset < 0) {
                        time = -this._startOffset;
                        this._startOffset = 0;
                    }
                    var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
                    if (!this._soundSource || !this._streamingSource) {
                        if (this.spatialSound) {
                            this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
                            if (this._isDirectional) {
                                this._soundPanner.coneInnerAngle = this._coneInnerAngle;
                                this._soundPanner.coneOuterAngle = this._coneOuterAngle;
                                this._soundPanner.coneOuterGain = this._coneOuterGain;
                                if (this._connectedMesh) {
                                    this._updateDirection();
                                }
                                else {
                                    this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
                                }
                            }
                        }
                    }
                    if (this._streaming) {
                        if (!this._streamingSource) {
                            this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
                            this._htmlAudioElement.onended = function () { _this._onended(); };
                            this._htmlAudioElement.playbackRate = this._playbackRate;
                        }
                        this._streamingSource.disconnect();
                        this._streamingSource.connect(this._inputAudioNode);
                        this._htmlAudioElement.play();
                    }
                    else {
                        this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
                        this._soundSource.buffer = this._audioBuffer;
                        this._soundSource.connect(this._inputAudioNode);
                        this._soundSource.loop = this.loop;
                        this._soundSource.playbackRate.value = this._playbackRate;
                        this._soundSource.onended = function () { _this._onended(); };
                        this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
                    }
                    this._startTime = startTime;
                    this.isPlaying = true;
                    this.isPaused = false;
                }
                catch (ex) {
                    BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
                }
            }
        };
        Sound.prototype._onended = function () {
            this.isPlaying = false;
            if (this.onended) {
                this.onended();
            }
        };
        /**
        * Stop the sound
        * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
        */
        Sound.prototype.stop = function (time) {
            if (this.isPlaying) {
                if (this._streaming) {
                    this._htmlAudioElement.pause();
                    // Test needed for Firefox or it will generate an Invalid State Error
                    if (this._htmlAudioElement.currentTime > 0) {
                        this._htmlAudioElement.currentTime = 0;
                    }
                }
                else {
                    var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
                    this._soundSource.stop(stopTime);
                    this._soundSource.onended = null;
                    if (!this.isPaused) {
                        this._startOffset = 0;
                    }
                }
                this.isPlaying = false;
            }
        };
        Sound.prototype.pause = function () {
            if (this.isPlaying) {
                this.isPaused = true;
                if (this._streaming) {
                    this._htmlAudioElement.pause();
                }
                else {
                    this.stop(0);
                    this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
                }
            }
        };
        Sound.prototype.setVolume = function (newVolume, time) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (time) {
                    this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
                    this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
                    this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
                }
                else {
                    this._soundGain.gain.value = newVolume;
                }
            }
            this._volume = newVolume;
        };
        Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
            this._playbackRate = newPlaybackRate;
            if (this.isPlaying) {
                if (this._streaming) {
                    this._htmlAudioElement.playbackRate = this._playbackRate;
                }
                else {
                    this._soundSource.playbackRate.value = this._playbackRate;
                }
            }
        };
        Sound.prototype.getVolume = function () {
            return this._volume;
        };
        Sound.prototype.attachToMesh = function (meshToConnectTo) {
            var _this = this;
            if (this._connectedMesh) {
                this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
                this._registerFunc = null;
            }
            this._connectedMesh = meshToConnectTo;
            if (!this.spatialSound) {
                this.spatialSound = true;
                this._createSpatialParameters();
                if (this.isPlaying && this.loop) {
                    this.stop();
                    this.play();
                }
            }
            this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
            this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
            meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
        };
        Sound.prototype.detachFromMesh = function () {
            if (this._connectedMesh) {
                this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
                this._registerFunc = null;
                this._connectedMesh = null;
            }
        };
        Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
            this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
                this._updateDirection();
            }
        };
        Sound.prototype.clone = function () {
            var _this = this;
            if (!this._streaming) {
                var setBufferAndRun = function () {
                    if (_this._isReadyToPlay) {
                        clonedSound._audioBuffer = _this.getAudioBuffer();
                        clonedSound._isReadyToPlay = true;
                        if (clonedSound.autoplay) {
                            clonedSound.play();
                        }
                    }
                    else {
                        window.setTimeout(setBufferAndRun, 300);
                    }
                };
                var currentOptions = {
                    autoplay: this.autoplay, loop: this.loop,
                    volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
                    useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
                    refDistance: this.refDistance, distanceModel: this.distanceModel
                };
                var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
                if (this.useCustomAttenuation) {
                    clonedSound.setAttenuationFunction(this._customAttenuationFunction);
                }
                clonedSound.setPosition(this._position);
                clonedSound.setPlaybackRate(this._playbackRate);
                setBufferAndRun();
                return clonedSound;
            }
            else {
                return null;
            }
        };
        Sound.prototype.getAudioBuffer = function () {
            return this._audioBuffer;
        };
        Sound.prototype.serialize = function () {
            var serializationObject = {
                name: this.name,
                url: this.name,
                autoplay: this.autoplay,
                loop: this.loop,
                volume: this._volume,
                spatialSound: this.spatialSound,
                maxDistance: this.maxDistance,
                rolloffFactor: this.rolloffFactor,
                refDistance: this.refDistance,
                distanceModel: this.distanceModel,
                playbackRate: this._playbackRate,
                panningModel: this._panningModel,
                soundTrackId: this.soundTrackId
            };
            if (this.spatialSound) {
                if (this._connectedMesh)
                    serializationObject.connectedMeshId = this._connectedMesh.id;
                serializationObject.position = this._position.asArray();
                serializationObject.refDistance = this.refDistance;
                serializationObject.distanceModel = this.distanceModel;
                serializationObject.isDirectional = this._isDirectional;
                serializationObject.localDirectionToMesh = this._localDirection.asArray();
                serializationObject.coneInnerAngle = this._coneInnerAngle;
                serializationObject.coneOuterAngle = this._coneOuterAngle;
                serializationObject.coneOuterGain = this._coneOuterGain;
            }
            return serializationObject;
        };
        Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
            var soundName = parsedSound.name;
            var soundUrl;
            if (parsedSound.url) {
                soundUrl = rootUrl + parsedSound.url;
            }
            else {
                soundUrl = rootUrl + soundName;
            }
            var options = {
                autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
                spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
                rolloffFactor: parsedSound.rolloffFactor,
                refDistance: parsedSound.refDistance,
                distanceModel: parsedSound.distanceModel,
                playbackRate: parsedSound.playbackRate
            };
            var newSound;
            if (!sourceSound) {
                newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
                scene._addPendingData(newSound);
            }
            else {
                var setBufferAndRun = function () {
                    if (sourceSound._isReadyToPlay) {
                        newSound._audioBuffer = sourceSound.getAudioBuffer();
                        newSound._isReadyToPlay = true;
                        if (newSound.autoplay) {
                            newSound.play();
                        }
                    }
                    else {
                        window.setTimeout(setBufferAndRun, 300);
                    }
                };
                newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
                setBufferAndRun();
            }
            if (parsedSound.position) {
                var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
                newSound.setPosition(soundPosition);
            }
            if (parsedSound.isDirectional) {
                newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
                if (parsedSound.localDirectionToMesh) {
                    var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
                    newSound.setLocalDirectionToMesh(localDirectionToMesh);
                }
            }
            if (parsedSound.connectedMeshId) {
                var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
                if (connectedMesh) {
                    newSound.attachToMesh(connectedMesh);
                }
            }
            return newSound;
        };
        return Sound;
    }());
    BABYLON.Sound = Sound;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.sound.js.map
 
var BABYLON;
(function (BABYLON) {
    var SoundTrack = (function () {
        function SoundTrack(scene, options) {
            this.id = -1;
            this._isMainTrack = false;
            this._isInitialized = false;
            this._scene = scene;
            this.soundCollection = new Array();
            this._options = options;
            if (!this._isMainTrack) {
                this._scene.soundTracks.push(this);
                this.id = this._scene.soundTracks.length - 1;
            }
        }
        SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
                this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
                if (this._options) {
                    if (this._options.volume) {
                        this._outputAudioNode.gain.value = this._options.volume;
                    }
                    if (this._options.mainTrack) {
                        this._isMainTrack = this._options.mainTrack;
                    }
                }
                this._isInitialized = true;
            }
        };
        SoundTrack.prototype.dispose = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (this._connectedAnalyser) {
                    this._connectedAnalyser.stopDebugCanvas();
                }
                while (this.soundCollection.length) {
                    this.soundCollection[0].dispose();
                }
                if (this._outputAudioNode) {
                    this._outputAudioNode.disconnect();
                }
                this._outputAudioNode = null;
            }
        };
        SoundTrack.prototype.AddSound = function (sound) {
            if (!this._isInitialized) {
                this._initializeSoundTrackAudioGraph();
            }
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                sound.connectToSoundTrackAudioNode(this._outputAudioNode);
            }
            if (sound.soundTrackId) {
                if (sound.soundTrackId === -1) {
                    this._scene.mainSoundTrack.RemoveSound(sound);
                }
                else {
                    this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
                }
            }
            this.soundCollection.push(sound);
            sound.soundTrackId = this.id;
        };
        SoundTrack.prototype.RemoveSound = function (sound) {
            var index = this.soundCollection.indexOf(sound);
            if (index !== -1) {
                this.soundCollection.splice(index, 1);
            }
        };
        SoundTrack.prototype.setVolume = function (newVolume) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                this._outputAudioNode.gain.value = newVolume;
            }
        };
        SoundTrack.prototype.switchPanningModelToHRTF = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                for (var i = 0; i < this.soundCollection.length; i++) {
                    this.soundCollection[i].switchPanningModelToHRTF();
                }
            }
        };
        SoundTrack.prototype.switchPanningModelToEqualPower = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                for (var i = 0; i < this.soundCollection.length; i++) {
                    this.soundCollection[i].switchPanningModelToEqualPower();
                }
            }
        };
        SoundTrack.prototype.connectToAnalyser = function (analyser) {
            if (this._connectedAnalyser) {
                this._connectedAnalyser.stopDebugCanvas();
            }
            this._connectedAnalyser = analyser;
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                this._outputAudioNode.disconnect();
                this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
            }
        };
        return SoundTrack;
    }());
    BABYLON.SoundTrack = SoundTrack;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.soundtrack.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * Special Glow Blur post process only blurring the alpha channel
     * It enforces keeping the most luminous color in the color channel.
     */
    var GlowBlurPostProcess = (function (_super) {
        __extends(GlowBlurPostProcess, _super);
        function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
            this.direction = direction;
            this.blurWidth = blurWidth;
            this.onApplyObservable.add(function (effect) {
                effect.setFloat2("screenSize", _this.width, _this.height);
                effect.setVector2("direction", _this.direction);
                effect.setFloat("blurWidth", _this.blurWidth);
            });
        }
        return GlowBlurPostProcess;
    }(BABYLON.PostProcess));
    /**
     * The highlight layer Helps adding a glow effect around a mesh.
     *
     * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
     * glowy meshes to your scene.
     *
     * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
     */
    var HighlightLayer = (function () {
        /**
         * Instantiates a new highlight Layer and references it to the scene..
         * @param name The name of the layer
         * @param scene The scene to use the layer in
         * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
         */
        function HighlightLayer(name, scene, options) {
            this._vertexBuffers = {};
            this._mainTextureDesiredSize = { width: 0, height: 0 };
            this._meshes = {};
            this._maxSize = 0;
            this._shouldRender = false;
            this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
            this._excludedMeshes = {};
            /**
             * Specifies whether or not the inner glow is ACTIVE in the layer.
             */
            this.innerGlow = true;
            /**
             * Specifies whether or not the outer glow is ACTIVE in the layer.
             */
            this.outerGlow = true;
            /**
             * Specifies wether the highlight layer is enabled or not.
             */
            this.isEnabled = true;
            /**
             * An event triggered when the highlight layer has been disposed.
             * @type {BABYLON.Observable}
             */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
             * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
             * @type {BABYLON.Observable}
             */
            this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
            /**
             * An event triggered when the highlight layer is being blurred.
             * @type {BABYLON.Observable}
             */
            this.onBeforeBlurObservable = new BABYLON.Observable();
            /**
             * An event triggered when the highlight layer has been blurred.
             * @type {BABYLON.Observable}
             */
            this.onAfterBlurObservable = new BABYLON.Observable();
            /**
             * An event triggered when the glowing blurred texture is being merged in the scene.
             * @type {BABYLON.Observable}
             */
            this.onBeforeComposeObservable = new BABYLON.Observable();
            /**
             * An event triggered when the glowing blurred texture has been merged in the scene.
             * @type {BABYLON.Observable}
             */
            this.onAfterComposeObservable = new BABYLON.Observable();
            /**
             * An event triggered when the highlight layer changes its size.
             * @type {BABYLON.Observable}
             */
            this.onSizeChangedObservable = new BABYLON.Observable();
            this._scene = scene;
            var engine = scene.getEngine();
            this._engine = engine;
            this._maxSize = this._engine.getCaps().maxTextureSize;
            this._scene.highlightLayers.push(this);
            // Warn on stencil.
            if (!this._engine.isStencilEnable) {
                BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
            }
            // Adapt options
            this._options = options || {
                mainTextureRatio: 0.25,
                blurTextureSizeRatio: 0.5,
                blurHorizontalSize: 1,
                blurVerticalSize: 1,
                alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
            };
            this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
            this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
            this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
            this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
            this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
            // Effect
            this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
            // Render target
            this.setMainTextureSize();
            // Create Textures and post processes
            this.createTextureAndPostProcesses();
        }
        Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
            /**
             * Gets the horizontal size of the blur.
             */
            get: function () {
                return this._horizontalBlurPostprocess.blurWidth;
            },
            /**
             * Specifies the horizontal size of the blur.
             */
            set: function (value) {
                this._horizontalBlurPostprocess.blurWidth = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
            /**
             * Gets the vertical size of the blur.
             */
            get: function () {
                return this._verticalBlurPostprocess.blurWidth;
            },
            /**
             * Specifies the vertical size of the blur.
             */
            set: function (value) {
                this._verticalBlurPostprocess.blurWidth = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(HighlightLayer.prototype, "camera", {
            /**
             * Gets the camera attached to the layer.
             */
            get: function () {
                return this._options.camera;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Creates the render target textures and post processes used in the highlight layer.
         */
        HighlightLayer.prototype.createTextureAndPostProcesses = function () {
            var _this = this;
            var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
            var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
            blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
            blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
            this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
                width: this._mainTextureDesiredSize.width,
                height: this._mainTextureDesiredSize.height
            }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._mainTexture.activeCamera = this._options.camera;
            this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._mainTexture.anisotropicFilteringLevel = 1;
            this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._mainTexture.renderParticles = false;
            this._mainTexture.renderList = null;
            this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
                width: blurTextureWidth,
                height: blurTextureHeight
            }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture.anisotropicFilteringLevel = 16;
            this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            this._blurTexture.renderParticles = false;
            this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
            this._downSamplePostprocess.onApplyObservable.add(function (effect) {
                effect.setTexture("textureSampler", _this._mainTexture);
            });
            if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
                this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
                });
                this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
                });
            }
            else {
                this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
                });
                this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
                });
            }
            this._mainTexture.onAfterUnbindObservable.add(function () {
                _this.onBeforeBlurObservable.notifyObservers(_this);
                _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
                _this.onAfterBlurObservable.notifyObservers(_this);
            });
            // Custom render function
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                var scene = _this._scene;
                var engine = scene.getEngine();
                // Culling
                engine.setState(subMesh.getMaterial().backFaceCulling);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                // Excluded Mesh
                if (_this._excludedMeshes[mesh.id]) {
                    return;
                }
                ;
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
                var highlightLayerMesh = _this._meshes[mesh.id];
                var material = subMesh.getMaterial();
                var emissiveTexture = null;
                if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
                    emissiveTexture = material.emissiveTexture;
                }
                if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
                    engine.enableEffect(_this._glowMapGenerationEffect);
                    mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
                    _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
                    if (highlightLayerMesh) {
                        _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
                    }
                    else {
                        _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
                    }
                    // Alpha test
                    if (material && material.needAlphaTesting()) {
                        var alphaTexture = material.getAlphaTestTexture();
                        _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
                        _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                    }
                    // Glow emissive only
                    if (emissiveTexture) {
                        _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
                        _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
                    }
                    // Bones
                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
                        _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
                }
                else {
                    // Need to reset refresh rate of the shadowMap
                    _this._mainTexture.resetRefreshCounter();
                }
            };
            this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
                _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
                var index;
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
                for (index = 0; index < transparentSubMeshes.length; index++) {
                    renderSubMesh(transparentSubMeshes.data[index]);
                }
            };
            this._mainTexture.onClearObservable.add(function (engine) {
                engine.clear(HighlightLayer.neutralColor, true, true, true);
            });
        };
        /**
         * Checks for the readiness of the element composing the layer.
         * @param subMesh the mesh to check for
         * @param useInstances specify wether or not to use instances to render the mesh
         * @param emissiveTexture the associated emissive texture used to generate the glow
         * @return true if ready otherwise, false
         */
        HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
            if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
                return false;
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var mesh = subMesh.getMesh();
            var material = subMesh.getMaterial();
            var uv1 = false;
            var uv2 = false;
            // Alpha test
            if (material && material.needAlphaTesting()) {
                var alphaTexture = material.getAlphaTestTexture();
                if (alphaTexture) {
                    defines.push("#define ALPHATEST");
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
                        alphaTexture.coordinatesIndex === 1) {
                        defines.push("#define DIFFUSEUV2");
                        uv2 = true;
                    }
                    else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                        defines.push("#define DIFFUSEUV1");
                        uv1 = true;
                    }
                }
            }
            // Emissive
            if (emissiveTexture) {
                defines.push("#define EMISSIVE");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
                    emissiveTexture.coordinatesIndex === 1) {
                    defines.push("#define EMISSIVEUV2");
                    uv2 = true;
                }
                else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    defines.push("#define EMISSIVEUV1");
                    uv1 = true;
                }
            }
            if (uv1) {
                attribs.push(BABYLON.VertexBuffer.UVKind);
                defines.push("#define UV1");
            }
            if (uv2) {
                attribs.push(BABYLON.VertexBuffer.UV2Kind);
                defines.push("#define UV2");
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Instances
            if (useInstances) {
                defines.push("#define INSTANCES");
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
            // Get correct effect      
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
            }
            return this._glowMapGenerationEffect.isReady();
        };
        /**
         * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
         */
        HighlightLayer.prototype.render = function () {
            var currentEffect = this._glowMapMergeEffect;
            // Check
            if (!currentEffect.isReady() || !this._blurTexture.isReady())
                return;
            var engine = this._scene.getEngine();
            this.onBeforeComposeObservable.notifyObservers(this);
            // Render
            engine.enableEffect(currentEffect);
            engine.setState(false);
            // Cache
            var previousStencilBuffer = engine.getStencilBuffer();
            var previousStencilFunction = engine.getStencilFunction();
            var previousStencilMask = engine.getStencilMask();
            var previousAlphaMode = engine.getAlphaMode();
            // Texture
            currentEffect.setTexture("textureSampler", this._blurTexture);
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
            // Draw order
            engine.setAlphaMode(this._options.alphaBlendingMode);
            engine.setStencilMask(0x00);
            engine.setStencilBuffer(true);
            engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
            if (this.outerGlow) {
                currentEffect.setFloat("offset", 0);
                engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
                engine.draw(true, 0, 6);
            }
            if (this.innerGlow) {
                currentEffect.setFloat("offset", 1);
                engine.setStencilFunction(BABYLON.Engine.EQUAL);
                engine.draw(true, 0, 6);
            }
            // Restore Cache
            engine.setStencilFunction(previousStencilFunction);
            engine.setStencilMask(previousStencilMask);
            engine.setAlphaMode(previousAlphaMode);
            engine.setStencilBuffer(previousStencilBuffer);
            this.onAfterComposeObservable.notifyObservers(this);
            // Handle size changes.
            var size = this._mainTexture.getSize();
            this.setMainTextureSize();
            if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
                // Recreate RTT and post processes on size change.
                this.onSizeChangedObservable.notifyObservers(this);
                this.disposeTextureAndPostProcesses();
                this.createTextureAndPostProcesses();
            }
        };
        /**
         * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
         * @param mesh The mesh to exclude from the highlight layer
         */
        HighlightLayer.prototype.addExcludedMesh = function (mesh) {
            var meshExcluded = this._excludedMeshes[mesh.id];
            if (!meshExcluded) {
                this._excludedMeshes[mesh.id] = {
                    mesh: mesh,
                    beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
                        mesh.getEngine().setStencilBuffer(false);
                    }),
                    afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
                        mesh.getEngine().setStencilBuffer(true);
                    }),
                };
            }
        };
        /**
          * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
          * @param mesh The mesh to highlight
          */
        HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
            var meshExcluded = this._excludedMeshes[mesh.id];
            if (meshExcluded) {
                mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
                mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
            }
            this._excludedMeshes[mesh.id] = undefined;
        };
        /**
         * Add a mesh in the highlight layer in order to make it glow with the chosen color.
         * @param mesh The mesh to highlight
         * @param color The color of the highlight
         * @param glowEmissiveOnly Extract the glow from the emissive texture
         */
        HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
            var _this = this;
            if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
            var meshHighlight = this._meshes[mesh.id];
            if (meshHighlight) {
                meshHighlight.color = color;
            }
            else {
                this._meshes[mesh.id] = {
                    mesh: mesh,
                    color: color,
                    // Lambda required for capture due to Observable this context
                    observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
                        if (_this._excludedMeshes[mesh.id]) {
                            _this.defaultStencilReference(mesh);
                        }
                        else {
                            mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
                        }
                    }),
                    observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
                    glowEmissiveOnly: glowEmissiveOnly
                };
            }
            this._shouldRender = true;
        };
        /**
         * Remove a mesh from the highlight layer in order to make it stop glowing.
         * @param mesh The mesh to highlight
         */
        HighlightLayer.prototype.removeMesh = function (mesh) {
            var meshHighlight = this._meshes[mesh.id];
            if (meshHighlight) {
                mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
                mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
            }
            this._meshes[mesh.id] = undefined;
            this._shouldRender = false;
            for (var meshHighlightToCheck in this._meshes) {
                if (meshHighlightToCheck) {
                    this._shouldRender = true;
                    break;
                }
            }
        };
        /**
         * Returns true if the layer contains information to display, otherwise false.
         */
        HighlightLayer.prototype.shouldRender = function () {
            return this.isEnabled && this._shouldRender;
        };
        /**
         * Sets the main texture desired size which is the closest power of two
         * of the engine canvas size.
         */
        HighlightLayer.prototype.setMainTextureSize = function () {
            if (this._options.mainTextureFixedSize) {
                this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
                this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
            }
            else {
                this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
                this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
                this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
                this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
            }
        };
        /**
         * Force the stencil to the normal expected value for none glowing parts
         */
        HighlightLayer.prototype.defaultStencilReference = function (mesh) {
            mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
        };
        /**
         * Dispose only the render target textures and post process.
         */
        HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
            this._blurTexture.dispose();
            this._mainTexture.dispose();
            this._downSamplePostprocess.dispose();
            this._horizontalBlurPostprocess.dispose();
            this._verticalBlurPostprocess.dispose();
        };
        /**
         * Dispose the highlight layer and free resources.
         */
        HighlightLayer.prototype.dispose = function () {
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            // Clean textures and post processes
            this.disposeTextureAndPostProcesses();
            // Clean mesh references 
            for (var id in this._meshes) {
                var meshHighlight = this._meshes[id];
                if (meshHighlight && meshHighlight.mesh) {
                    meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
                    meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
                }
            }
            this._meshes = null;
            for (var id in this._excludedMeshes) {
                var meshHighlight = this._excludedMeshes[id];
                if (meshHighlight) {
                    meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
                    meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
                }
            }
            this._excludedMeshes = null;
            // Remove from scene
            var index = this._scene.highlightLayers.indexOf(this, 0);
            if (index > -1) {
                this._scene.highlightLayers.splice(index, 1);
            }
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onBeforeRenderMainTextureObservable.clear();
            this.onBeforeBlurObservable.clear();
            this.onBeforeComposeObservable.clear();
            this.onAfterComposeObservable.clear();
            this.onSizeChangedObservable.clear();
        };
        /**
         * The neutral color used during the preparation of the glow effect.
         * This is black by default as the blend operation is a blend operation.
         */
        HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
        /**
         * Stencil value used for glowing meshes.
         */
        HighlightLayer.glowingMeshStencilReference = 0x02;
        /**
         * Stencil value used for the other meshes in the scene.
         */
        HighlightLayer.normalMeshStencilReference = 0x01;
        return HighlightLayer;
    }());
    BABYLON.HighlightLayer = HighlightLayer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.highlightlayer.js.map
 
var BABYLON;
(function (BABYLON) {
    var SIMDVector3 = (function () {
        function SIMDVector3() {
        }
        SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
            SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
        };
        SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
            var m = transformation.m;
            var m0 = SIMD.Float32x4.load(m, 0);
            var m1 = SIMD.Float32x4.load(m, 4);
            var m2 = SIMD.Float32x4.load(m, 8);
            var m3 = SIMD.Float32x4.load(m, 12);
            var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
            r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
            result.x = SIMD.Float32x4.extractLane(r, 0);
            result.y = SIMD.Float32x4.extractLane(r, 1);
            result.z = SIMD.Float32x4.extractLane(r, 2);
        };
        return SIMDVector3;
    }());
    var SIMDMatrix = (function () {
        function SIMDMatrix() {
        }
        SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
            var tm = this.m;
            var om = other.m;
            var m0 = SIMD.Float32x4.load(om, 0);
            var m1 = SIMD.Float32x4.load(om, 4);
            var m2 = SIMD.Float32x4.load(om, 8);
            var m3 = SIMD.Float32x4.load(om, 12);
            for (var i = 0; i < 16; i += 4) {
                SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
            }
            return this;
        };
        SIMDMatrix.prototype.invertToRefSIMD = function (other) {
            var src = this.m;
            var dest = other.m;
            // Load the 4 rows
            var src0 = SIMD.Float32x4.load(src, 0);
            var src1 = SIMD.Float32x4.load(src, 4);
            var src2 = SIMD.Float32x4.load(src, 8);
            var src3 = SIMD.Float32x4.load(src, 12);
            // Transpose the source matrix.  Sort of.  Not a true transpose operation
            var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
            var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
            var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
            row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
            tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
            var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
            var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
            row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
            // This is a true transposition, but it will lead to an incorrect result
            //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
            //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
            //row0  = shuffle(tmp1, tmp2, 0, 2, 4, 6);
            //row1  = shuffle(tmp1, tmp2, 1, 3, 5, 7);
            //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
            //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
            //row2  = shuffle(tmp1, tmp2, 0, 2, 4, 6);
            //row3  = shuffle(tmp1, tmp2, 1, 3, 5, 7);
            // ----
            tmp1 = SIMD.Float32x4.mul(row2, row3);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
            var minor0 = SIMD.Float32x4.mul(row1, tmp1);
            var minor1 = SIMD.Float32x4.mul(row0, tmp1);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
            minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
            minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
            minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
            // ----
            tmp1 = SIMD.Float32x4.mul(row1, row2);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
            minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
            var minor3 = SIMD.Float32x4.mul(row0, tmp1);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
            minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
            minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
            minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
            // ----
            tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
            row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
            minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
            var minor2 = SIMD.Float32x4.mul(row0, tmp1);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
            minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
            minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
            minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
            // ----
            tmp1 = SIMD.Float32x4.mul(row0, row1);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
            minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
            minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
            minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
            minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
            // ----
            tmp1 = SIMD.Float32x4.mul(row0, row3);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
            minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
            minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
            minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
            minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
            // ----
            tmp1 = SIMD.Float32x4.mul(row0, row2);
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
            minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
            minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
            tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
            minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
            minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
            // Compute determinant
            var det = SIMD.Float32x4.mul(row0, minor0);
            det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
            det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
            tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
            det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
            det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
            // These shuffles aren't necessary if the faulty transposition is done
            // up at the top of this function.
            //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
            //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
            //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
            //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
            // Compute final values by multiplying with 1/det
            SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
            SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
            SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
            SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
            return this;
        };
        SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
            var out = result.m;
            var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
            var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
            var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
            // cc.kmVec3Subtract(f, pCenter, pEye);
            var f = SIMD.Float32x4.sub(center, eye);
            // cc.kmVec3Normalize(f, f);    
            var tmp = SIMD.Float32x4.mul(f, f);
            tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
            f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
            // cc.kmVec3Assign(up, pUp);
            // cc.kmVec3Normalize(up, up);
            tmp = SIMD.Float32x4.mul(up, up);
            tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
            up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
            // cc.kmVec3Cross(s, f, up);
            var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
            // cc.kmVec3Normalize(s, s);
            tmp = SIMD.Float32x4.mul(s, s);
            tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
            s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
            // cc.kmVec3Cross(u, s, f);
            var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
            // cc.kmVec3Normalize(s, s);
            tmp = SIMD.Float32x4.mul(s, s);
            tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
            s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
            var zero = SIMD.Float32x4.splat(0.0);
            s = SIMD.Float32x4.neg(s);
            var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
            var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
            var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
            var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
            var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
            var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
            var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
            SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
            b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
            SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
            b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
            SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
            b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
            SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
        };
        return SIMDMatrix;
    }());
    var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
    var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
    var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
    var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
    var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
    var SIMDHelper = (function () {
        function SIMDHelper() {
        }
        Object.defineProperty(SIMDHelper, "IsEnabled", {
            get: function () {
                return SIMDHelper._isEnabled;
            },
            enumerable: true,
            configurable: true
        });
        SIMDHelper.DisableSIMD = function () {
            // Replace functions
            BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
            BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
            BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
            BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
            SIMDHelper._isEnabled = false;
        };
        SIMDHelper.EnableSIMD = function () {
            if (self.SIMD === undefined) {
                return;
            }
            // check if polyfills needed
            if (!self.Math.fround) {
                self.Math.fround = (function (array) { return function (x) {
                    return array[0] = x, array[0];
                }; })(new Float32Array(1));
            }
            if (!self.Math.imul) {
                self.Math.imul = function (a, b) {
                    var ah = (a >>> 16) & 0xffff;
                    var al = a & 0xffff;
                    var bh = (b >>> 16) & 0xffff;
                    var bl = b & 0xffff;
                    // the shift by 0 fixes the sign on the high part
                    // the final |0 converts the unsigned value into a signed value
                    return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
                };
            }
            // Replace functions
            BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
            BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
            BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
            BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
            SIMDHelper._isEnabled = true;
        };
        SIMDHelper._isEnabled = false;
        return SIMDHelper;
    }());
    BABYLON.SIMDHelper = SIMDHelper;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.math.SIMD.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
  * This class describe a rectangle that were added to the map.
  * You have access to its coordinates either in pixel or normalized (UV)
  */
    var PackedRect = (function () {
        function PackedRect(root, parent, pos, size) {
            this._pos = pos;
            this._size = size;
            this._root = root;
            this._parent = parent;
            this._contentSize = null;
            this._bottomNode = null;
            this._leftNode = null;
            this._initialSize = null;
            this._rightNode = null;
        }
        Object.defineProperty(PackedRect.prototype, "pos", {
            /**
             * @returns the position of this node into the map
             */
            get: function () {
                return this._pos;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PackedRect.prototype, "contentSize", {
            /**
             * @returns the size of the rectangle this node handles
             */
            get: function () {
                return this._contentSize;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PackedRect.prototype, "UVs", {
            /**
             * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
             * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
             */
            get: function () {
                return this.getUVsForCustomSize(this._root._size);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
         * This method will return the UVs for this part by given the custom size of what you really use
         * @param customSize must be less/equal to the allocated size, UV will be compute from this
         */
        PackedRect.prototype.getUVsForCustomSize = function (customSize) {
            var mainWidth = this._root._size.width;
            var mainHeight = this._root._size.height;
            var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
            var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
            var uvs = new Array();
            uvs.push(topLeft);
            uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
            uvs.push(rightBottom);
            uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
            return uvs;
        };
        /**
         * Free this rectangle from the map.
         * Call this method when you no longer need the rectangle to be in the map.
         */
        PackedRect.prototype.freeContent = function () {
            if (!this.contentSize) {
                return;
            }
            this._contentSize = null;
            // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
            this.attemptDefrag();
        };
        Object.defineProperty(PackedRect.prototype, "isUsed", {
            get: function () {
                return this._contentSize != null || this._leftNode != null;
            },
            enumerable: true,
            configurable: true
        });
        PackedRect.prototype.findAndSplitNode = function (contentSize) {
            var node = this.findNode(contentSize);
            // Not enough space...
            if (!node) {
                return null;
            }
            node.splitNode(contentSize);
            return node;
        };
        PackedRect.prototype.findNode = function (size) {
            var resNode = null;
            // If this node is used, recurse to each of his subNodes to find an available one in its branch
            if (this.isUsed) {
                if (this._leftNode) {
                    resNode = this._leftNode.findNode(size);
                }
                if (!resNode && this._rightNode) {
                    resNode = this._rightNode.findNode(size);
                }
                if (!resNode && this._bottomNode) {
                    resNode = this._bottomNode.findNode(size);
                }
            }
            else if (this._initialSize) {
                if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
                    resNode = this;
                }
                else {
                    return null;
                }
            }
            else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
                resNode = this;
            }
            return resNode;
        };
        PackedRect.prototype.splitNode = function (contentSize) {
            // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
            if (!this._contentSize && this._initialSize) {
                this._contentSize = contentSize.clone();
                this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
                return this._leftNode.splitNode(contentSize);
            }
            else {
                this._contentSize = contentSize.clone();
                this._initialSize = contentSize.clone();
                if (contentSize.width !== this._size.width) {
                    this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
                }
                if (contentSize.height !== this._size.height) {
                    this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
                }
                return this;
            }
        };
        PackedRect.prototype.attemptDefrag = function () {
            if (!this.isUsed && this.isRecursiveFree) {
                this.clearNode();
                if (this._parent) {
                    this._parent.attemptDefrag();
                }
            }
        };
        PackedRect.prototype.clearNode = function () {
            this._initialSize = null;
            this._rightNode = null;
            this._bottomNode = null;
        };
        Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
            get: function () {
                return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
            },
            enumerable: true,
            configurable: true
        });
        PackedRect.prototype.evalFreeSize = function (size) {
            var levelSize = 0;
            if (!this.isUsed) {
                if (this._initialSize) {
                    levelSize = this._initialSize.surface;
                }
                else {
                    levelSize = this._size.surface;
                }
            }
            if (this._rightNode) {
                levelSize += this._rightNode.evalFreeSize(0);
            }
            if (this._bottomNode) {
                levelSize += this._bottomNode.evalFreeSize(0);
            }
            return levelSize + size;
        };
        return PackedRect;
    }());
    BABYLON.PackedRect = PackedRect;
    /**
     * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
     * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
     * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
     */
    var RectPackingMap = (function (_super) {
        __extends(RectPackingMap, _super);
        /**
         * Create an instance of the object with a dimension using the given size
         * @param size The dimension of the rectangle that will contain all the sub ones.
         */
        function RectPackingMap(size) {
            _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
            this._root = this;
        }
        /**
         * Add a rectangle, finding the best location to store it into the map
         * @param size the dimension of the rectangle to store
         * @return the Node containing the rectangle information, or null if we couldn't find a free spot
         */
        RectPackingMap.prototype.addRect = function (size) {
            var node = this.findAndSplitNode(size);
            return node;
        };
        Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
            /**
             * Return the current space free normalized between [0;1]
             * @returns {}
             */
            get: function () {
                var freeSize = 0;
                freeSize = this.evalFreeSize(freeSize);
                return freeSize / (this._size.width * this._size.height);
            },
            enumerable: true,
            configurable: true
        });
        return RectPackingMap;
    }(PackedRect));
    BABYLON.RectPackingMap = RectPackingMap;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.rectPackingMap.js.map
 
var BABYLON;
(function (BABYLON) {
    var DynamicFloatArrayElementInfo = (function () {
        function DynamicFloatArrayElementInfo() {
        }
        return DynamicFloatArrayElementInfo;
    }());
    BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
    /**
    * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
    * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
    * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
    * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
    * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
     * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
    */
    var DynamicFloatArray = (function () {
        /**
         * Construct an instance of the dynamic float array
         * @param stride size of one element in float (i.e. not bytes!)
         * @param initialElementCount the number of available entries at construction
         */
        function DynamicFloatArray(stride, initialElementCount) {
            this.compareValueOffset = null;
            this.sortingAscending = true;
            this._stride = stride;
            this.buffer = new Float32Array(stride * initialElementCount);
            this._lastUsed = 0;
            this._firstFree = 0;
            this._allEntries = new Array(initialElementCount);
            this._freeEntries = new Array(initialElementCount);
            for (var i = 0; i < initialElementCount; i++) {
                var element = new DynamicFloatArrayElementInfo();
                element.offset = i * stride;
                this._allEntries[i] = element;
                this._freeEntries[initialElementCount - i - 1] = element;
            }
        }
        /**
         * Allocate an element in the array.
         * @return the element info instance that contains the offset into the main buffer of the element's location.
         * Beware, this offset may change when you call pack()
         */
        DynamicFloatArray.prototype.allocElement = function () {
            if (this._freeEntries.length === 0) {
                this._growBuffer();
            }
            var el = this._freeEntries.pop();
            this._lastUsed = Math.max(el.offset, this._lastUsed);
            if (el.offset === this._firstFree) {
                if (this._freeEntries.length > 0) {
                    this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
                }
                else {
                    this._firstFree += this._stride;
                }
            }
            return el;
        };
        /**
         * Free the element corresponding to the given element info
         * @param elInfo the element that describe the allocated element
         */
        DynamicFloatArray.prototype.freeElement = function (elInfo) {
            this._firstFree = Math.min(elInfo.offset, this._firstFree);
            this._freeEntries.push(elInfo);
        };
        /**
         * This method will pack all the used elements into a linear sequence and put all the free space at the end.
         * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
         * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
         */
        DynamicFloatArray.prototype.pack = function () {
            // no free slot? no need to pack
            if (this._freeEntries.length === 0) {
                return this.buffer;
            }
            // If the buffer is already packed the last used will always be lower than the first free
            // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
            if (this._lastUsed < this._firstFree) {
                var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
                return elementsBuffer_1;
            }
            var s = this._stride;
            // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
            var lastFree = new DynamicFloatArrayElementInfo();
            lastFree.offset = this.totalElementCount * s;
            this._freeEntries.push(lastFree);
            var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
            var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
            var firstFreeSlotOffset = sortedFree[0].offset;
            var freeZoneSize = 1;
            var occupiedZoneSize = (this.usedElementCount + 1) * s;
            var prevOffset = sortedFree[0].offset;
            for (var i = 1; i < sortedFree.length; i++) {
                // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
                if (firstFreeSlotOffset >= occupiedZoneSize) {
                    break;
                }
                var curFree = sortedFree[i];
                var curOffset = curFree.offset;
                // Compute the distance between this offset and the previous
                var distance = curOffset - prevOffset;
                // If the distance is the stride size, they are adjacent, it good, move to the next
                if (distance === s) {
                    // Free zone is one element bigger
                    ++freeZoneSize;
                    // as we're about to iterate to the next, the cur becomes the previous...
                    prevOffset = curOffset;
                    continue;
                }
                // Distance is bigger, which means there's x element between the previous free and this one
                var usedRange = (distance / s) - 1;
                // Two cases the free zone is smaller than the data to move or bigger
                // Copy what can fit in the free zone
                var curMoveOffset = curOffset - s;
                var copyCount = Math.min(freeZoneSize, usedRange);
                for (var j = 0; j < copyCount; j++) {
                    var freeI = firstFreeSlotOffset / s;
                    var curI = curMoveOffset / s;
                    var moveEl = sortedAll[curI];
                    this._moveElement(moveEl, firstFreeSlotOffset);
                    var replacedEl = sortedAll[freeI];
                    // set the offset of the element we replaced with a value that will make it discard at the end of the method
                    replacedEl.offset = curMoveOffset;
                    // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
                    sortedAll[freeI] = moveEl;
                    sortedAll[curI] = replacedEl;
                    curMoveOffset -= s;
                    firstFreeSlotOffset += s;
                }
                // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
                if (freeZoneSize <= usedRange) {
                    firstFreeSlotOffset = curMoveOffset + s;
                    freeZoneSize = 1 + copyCount;
                }
                else {
                    freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
                }
                // as we're about to iterate to the next, the cur becomes the previous...
                prevOffset = curOffset;
            }
            var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
            this._lastUsed = firstFreeSlotOffset - s;
            this._firstFree = firstFreeSlotOffset;
            sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
            this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
            this._allEntries = sortedAll;
            return elementsBuffer;
        };
        DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
            for (var i = 0; i < this._stride; i++) {
                this.buffer[destOffset + i] = this.buffer[element.offset + i];
            }
            element.offset = destOffset;
        };
        DynamicFloatArray.prototype._growBuffer = function () {
            // Allocate the new buffer with 50% more entries, copy the content of the current one
            var newElCount = Math.floor(this.totalElementCount * 1.5);
            var newBuffer = new Float32Array(newElCount * this._stride);
            newBuffer.set(this.buffer);
            var curCount = this.totalElementCount;
            var addedCount = newElCount - this.totalElementCount;
            for (var i = 0; i < addedCount; i++) {
                var element = new DynamicFloatArrayElementInfo();
                element.offset = (curCount + i) * this.stride;
                this._allEntries.push(element);
                this._freeEntries[addedCount - i - 1] = element;
            }
            this._firstFree = curCount * this.stride;
            this.buffer = newBuffer;
        };
        Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
            /**
             * Get the total count of entries that can fit in the current buffer
             * @returns the elements count
             */
            get: function () {
                return this._allEntries.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
            /**
             * Get the count of free entries that can still be allocated without resizing the buffer
             * @returns the free elements count
             */
            get: function () {
                return this._freeEntries.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
            /**
             * Get the count of allocated elements
             * @returns the allocated elements count
             */
            get: function () {
                return this._allEntries.length - this._freeEntries.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DynamicFloatArray.prototype, "stride", {
            /**
             * Return the size of one element in float
             * @returns the size in float
             */
            get: function () {
                return this._stride;
            },
            enumerable: true,
            configurable: true
        });
        DynamicFloatArray.prototype.sort = function () {
            var _this = this;
            if (!this.compareValueOffset) {
                throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
            }
            var count = this.usedElementCount;
            // Do we have to (re)create the sort table?
            if (!this._sortTable || this._sortTable.length < count) {
                // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
                var newCount = Math.min(this.totalElementCount, count * 2);
                this._sortTable = new Array(newCount);
            }
            if (!this._sortedTable || this._sortedTable.length !== count) {
                this._sortedTable = new Array(count);
            }
            // Because, you know...
            this.pack();
            //let stride = this.stride;
            //for (let i = 0; i < count; i++) {
            //    let si = this._sortTable[i];
            //    if (!si) {
            //        si = new SortInfo();
            //        this._sortTable[i] = si;
            //    }
            //    si.entry = this._allEntries[i];
            //    si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
            //    si.swapedOffset = null;
            //    this._sortedTable[i] = si;
            //}
            var curOffset = 0;
            var stride = this.stride;
            for (var i = 0; i < count; i++, curOffset += stride) {
                var si = this._sortTable[i];
                if (!si) {
                    si = new SortInfo();
                    this._sortTable[i] = si;
                }
                si.compareData = this.buffer[curOffset + this.compareValueOffset];
                si.offset = curOffset;
                si.swapedOffset = null;
                this._sortedTable[i] = si;
            }
            // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
            if (this.sortingAscending) {
                this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
            }
            else {
                this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
            }
            var swapElements = function (src, dst) {
                for (var i = 0; i < stride; i++) {
                    var tps = _this.buffer[dst + i];
                    _this.buffer[dst + i] = _this.buffer[src + i];
                    _this.buffer[src + i] = tps;
                }
            };
            // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element: 
            //  it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise), 
            //  and I still want something with a good algorithm complexity.
            // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced, 
            //  we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
            // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
            // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there 
            //  until we find a SortInfo object without a swapedOffset which means we got the right location
            // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better 
            //  than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
            for (var i = 0; i < count; i++) {
                // Get the element to move
                var sourceSI = this._sortedTable[i];
                var destSI = this._sortTable[i];
                var sourceOff = sourceSI.offset;
                // If the source changed location, find the new one
                if (sourceSI.swapedOffset) {
                    // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
                    var curSI = sourceSI;
                    while (curSI.swapedOffset) {
                        curSI = this._sortTable[curSI.swapedOffset / stride];
                    }
                    // Finally get the right location
                    sourceOff = curSI.offset;
                }
                // Tag the element being replaced with its new location
                destSI.swapedOffset = sourceOff;
                // Swap elements (only if needed)
                if (sourceOff !== destSI.offset) {
                    swapElements(sourceOff, destSI.offset);
                }
                // Update the offset in the corresponding DFAE
                //sourceSI.entry.offset = destSI.entry.offset;
                this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
            }
            this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
            return true;
        };
        return DynamicFloatArray;
    }());
    BABYLON.DynamicFloatArray = DynamicFloatArray;
    var SortInfo = (function () {
        function SortInfo() {
            this.compareData = this.offset = this.swapedOffset = null;
        }
        return SortInfo;
    }());
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.dynamicFloatArray.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * This class given information about a given character.
     */
    var CharInfo = (function () {
        function CharInfo() {
        }
        return CharInfo;
    }());
    BABYLON.CharInfo = CharInfo;
    var FontTexture = (function (_super) {
        __extends(FontTexture, _super);
        /**
         * Create a new instance of the FontTexture class
         * @param name the name of the texture
         * @param font the font to use, use the W3C CSS notation
         * @param scene the scene that owns the texture
         * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
         * @param samplingMode the texture sampling mode
         * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
         */
        function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
            if (maxCharCount === void 0) { maxCharCount = 200; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (superSample === void 0) { superSample = false; }
            if (signedDistanceField === void 0) { signedDistanceField = false; }
            _super.call(this, null, scene, true, false, samplingMode);
            this._charInfos = {};
            this._curCharCount = 0;
            this._lastUpdateCharCount = -1;
            this._usedCounter = 1;
            this.name = name;
            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._sdfScale = 8;
            this._signedDistanceField = signedDistanceField;
            this._superSample = false;
            // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
            if (superSample || signedDistanceField) {
                var sfont = this.getSuperSampleFont(font);
                if (sfont) {
                    this._superSample = true;
                    font = sfont;
                }
            }
            // First canvas creation to determine the size of the texture to create
            this._canvas = document.createElement("canvas");
            this._context = this._canvas.getContext("2d");
            this._context.font = font;
            this._context.fillStyle = "white";
            this._context.textBaseline = "top";
            this._cachedFontId = null;
            var res = this.getFontHeight(font);
            this._lineHeightSuper = res.height + 4;
            this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
            this._offset = res.offset - 1;
            this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
            this._yMargin = this._xMargin;
            var maxCharWidth = this._context.measureText("W").width;
            this._spaceWidthSuper = this._context.measureText(" ").width;
            this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
            // This is an approximate size, but should always be able to fit at least the maxCharCount
            var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
            var edge = Math.sqrt(totalEstSurface);
            var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
            // Create the texture that will store the font characters
            this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
            var textureSize = this.getSize();
            this.hasAlpha = this._signedDistanceField === false;
            // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
            this._canvas = document.createElement("canvas");
            this._canvas.width = textureSize.width;
            this._canvas.height = textureSize.height;
            this._context = this._canvas.getContext("2d");
            this._context.textBaseline = "top";
            this._context.font = font;
            this._context.fillStyle = "white";
            this._context.imageSmoothingEnabled = false;
            this._context.clearRect(0, 0, textureSize.width, textureSize.height);
            // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
            //  into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
            // So you can see this context as an intermediate one, because it is.
            if (this._signedDistanceField) {
                var sdfC = document.createElement("canvas");
                var s = this._sdfScale;
                sdfC.width = maxCharWidth * s;
                sdfC.height = this._lineHeightSuper * s;
                var sdfCtx = sdfC.getContext("2d");
                sdfCtx.scale(s, s);
                sdfCtx.textBaseline = "top";
                sdfCtx.font = font;
                sdfCtx.fillStyle = "white";
                sdfCtx.imageSmoothingEnabled = false;
                this._sdfCanvas = sdfC;
                this._sdfContext = sdfCtx;
            }
            this._currentFreePosition = BABYLON.Vector2.Zero();
            // Add the basic ASCII based characters
            for (var i = 0x20; i < 0x7F; i++) {
                var c = String.fromCharCode(i);
                this.getChar(c);
            }
            this.update();
        }
        Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
            get: function () {
                return this._superSample;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
            get: function () {
                return this._signedDistanceField;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FontTexture.prototype, "spaceWidth", {
            get: function () {
                return this._spaceWidth;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FontTexture.prototype, "lineHeight", {
            get: function () {
                return this._lineHeight;
            },
            enumerable: true,
            configurable: true
        });
        FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
            if (supersample === void 0) { supersample = false; }
            if (signedDistanceField === void 0) { signedDistanceField = false; }
            var s = scene;
            if (!s.__fontTextureCache__) {
                s.__fontTextureCache__ = new BABYLON.StringDictionary();
            }
            var dic = s.__fontTextureCache__;
            var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
            var ft = dic.get(lfn);
            if (ft) {
                ++ft._usedCounter;
                return ft;
            }
            ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
            ft._cachedFontId = lfn;
            dic.add(lfn, ft);
            return ft;
        };
        FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
            if (supersample === void 0) { supersample = false; }
            if (signedDistanceField === void 0) { signedDistanceField = false; }
            var s = scene;
            var dic = s.__fontTextureCache__;
            if (!dic) {
                return;
            }
            var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
            var font = dic.get(lfn);
            if (--font._usedCounter === 0) {
                dic.remove(lfn);
                font.dispose();
            }
        };
        /**
         * Make sure the given char is present in the font map.
         * @param char the character to get or add
         * @return the CharInfo instance corresponding to the given character
         */
        FontTexture.prototype.getChar = function (char) {
            if (char.length !== 1) {
                return null;
            }
            var info = this._charInfos[char];
            if (info) {
                return info;
            }
            info = new CharInfo();
            var measure = this._context.measureText(char);
            var textureSize = this.getSize();
            // we reached the end of the current line?
            var width = Math.round(measure.width);
            if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
                this._currentFreePosition.x = 0;
                this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
                // No more room?
                if (this._currentFreePosition.y > textureSize.height) {
                    return this.getChar("!");
                }
            }
            // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
            if (this._signedDistanceField) {
                this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
                this._sdfContext.fillText(char, 0, -this._offset);
                var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
                var res = this._computeSDFChar(data);
                this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
            }
            else {
                // Draw the character in the HTML canvas
                this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
            }
            // Fill the CharInfo object
            info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
            info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
            if (this._signedDistanceField) {
                var off = 1 / textureSize.width;
                info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
                info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
            }
            info.charWidth = this._superSample ? (width / 2) : width;
            // Add the info structure
            this._charInfos[char] = info;
            this._curCharCount++;
            // Set the next position
            this._currentFreePosition.x += width + this._xMargin;
            return info;
        };
        FontTexture.prototype._computeSDFChar = function (source) {
            var scl = this._sdfScale;
            var sw = source.width;
            var sh = source.height;
            var dw = sw / scl;
            var dh = sh / scl;
            var roffx = 0;
            var roffy = 0;
            // We shouldn't look beyond half of the biggest between width and height
            var radius = scl;
            var br = radius - 1;
            var lookupSrc = function (dx, dy, offX, offY, lookVis) {
                var sx = dx * scl;
                var sy = dy * scl;
                // Looking out of the area? return true to make the test going on
                if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
                    return true;
                }
                // Get the pixel we want
                var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
                var res = (val > 0) === lookVis;
                if (!res) {
                    roffx = offX;
                    roffy = offY;
                }
                return res;
            };
            var lookupArea = function (dx, dy, lookVis) {
                // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
                if (lookupSrc(dx, dy, 0, br, lookVis) &&
                    lookupSrc(dx, dy, 0, -br, lookVis) &&
                    lookupSrc(dx, dy, -br, 0, lookVis) &&
                    lookupSrc(dx, dy, br, 0, lookVis)) {
                    return 0;
                }
                for (var i = 1; i <= radius; i++) {
                    // Quick test N, S, W, E
                    if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
                        return i * i; // Squared Distance is simple to compute in this case
                    }
                    // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
                    for (var j = 1; j <= i; j++) {
                        if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
                            !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
                            !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
                            !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
                            // We found the nearest texel having and opposite state, store the squared length
                            var res_1 = (i * i) + (j * j);
                            var count = 1;
                            // To improve quality we will  sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
                            if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
                                res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
                                res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
                                res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
                                res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
                                res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
                                res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
                                res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
                                ++count;
                            }
                            if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
                                res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
                                ++count;
                            }
                            // Compute the average based on the accumulated distance
                            return res_1 / count;
                        }
                    }
                }
                return 0;
            };
            var tmp = new Array(dw * dh);
            for (var y = 0; y < dh; y++) {
                for (var x = 0; x < dw; x++) {
                    var curState = lookupSrc(x, y, 0, 0, true);
                    var d = lookupArea(x, y, curState);
                    if (d === 0) {
                        d = radius * radius * 2;
                    }
                    tmp[(y * dw) + x] = curState ? d : -d;
                }
            }
            var res = this._context.createImageData(dw, dh);
            var size = dw * dh;
            for (var j = 0; j < size; j++) {
                var d = tmp[j];
                var sign = (d < 0) ? -1 : 1;
                d = Math.sqrt(Math.abs(d)) * sign;
                d *= 127.5 / radius;
                d += 127.5;
                if (d < 0) {
                    d = 0;
                }
                else if (d > 255) {
                    d = 255;
                }
                d += 0.5;
                res.data[j * 4 + 0] = d;
                res.data[j * 4 + 1] = d;
                res.data[j * 4 + 2] = d;
                res.data[j * 4 + 3] = 255;
            }
            return res;
        };
        FontTexture.prototype.measureText = function (text, tabulationSize) {
            if (tabulationSize === void 0) { tabulationSize = 4; }
            var maxWidth = 0;
            var curWidth = 0;
            var lineCount = 1;
            var charxpos = 0;
            // Parse each char of the string
            for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
                var char = text_1[_i];
                // Next line feed?
                if (char === "\n") {
                    maxWidth = Math.max(maxWidth, curWidth);
                    charxpos = 0;
                    curWidth = 0;
                    ++lineCount;
                    continue;
                }
                // Tabulation ?
                if (char === "\t") {
                    var nextPos = charxpos + tabulationSize;
                    nextPos = nextPos - (nextPos % tabulationSize);
                    curWidth += (nextPos - charxpos) * this.spaceWidth;
                    charxpos = nextPos;
                    continue;
                }
                if (char < " ") {
                    continue;
                }
                curWidth += this.getChar(char).charWidth;
                ++charxpos;
            }
            maxWidth = Math.max(maxWidth, curWidth);
            return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
        };
        FontTexture.prototype.getSuperSampleFont = function (font) {
            // Eternal thank to http://stackoverflow.com/a/10136041/802124
            var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
            var res = font.toLocaleLowerCase().match(regex);
            if (res == null) {
                return null;
            }
            var size = parseInt(res[4]);
            res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
            var newFont = "";
            for (var j = 1; j < res.length; j++) {
                if (res[j] != null) {
                    newFont += res[j] + " ";
                }
            }
            return newFont;
        };
        // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
        FontTexture.prototype.getFontHeight = function (font) {
            var fontDraw = document.createElement("canvas");
            var ctx = fontDraw.getContext('2d');
            ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
            ctx.textBaseline = 'top';
            ctx.fillStyle = 'white';
            ctx.font = font;
            ctx.fillText('jH|', 0, 0);
            var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
            var start = -1;
            var end = -1;
            for (var row = 0; row < fontDraw.height; row++) {
                for (var column = 0; column < fontDraw.width; column++) {
                    var index = (row * fontDraw.width + column) * 4;
                    if (pixels[index] === 0) {
                        if (column === fontDraw.width - 1 && start !== -1) {
                            end = row;
                            row = fontDraw.height;
                            break;
                        }
                        continue;
                    }
                    else {
                        if (start === -1) {
                            start = row;
                        }
                        break;
                    }
                }
            }
            return { height: (end - start) + 1, offset: start - 1 };
        };
        Object.defineProperty(FontTexture.prototype, "canRescale", {
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        FontTexture.prototype.getContext = function () {
            return this._context;
        };
        /**
         * Call this method when you've call getChar() at least one time, this will update the texture if needed.
         * Don't be afraid to call it, if no new character was added, this method simply does nothing.
         */
        FontTexture.prototype.update = function () {
            // Update only if there's new char added since the previous update
            if (this._lastUpdateCharCount < this._curCharCount) {
                this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
                this._lastUpdateCharCount = this._curCharCount;
            }
        };
        // cloning should be prohibited, there's no point to duplicate this texture at all
        FontTexture.prototype.clone = function () {
            return null;
        };
        /**
         * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
         * When the other party is done with this object, decCachedFontTextureCounter must be called.
         */
        FontTexture.prototype.incCachedFontTextureCounter = function () {
            ++this._usedCounter;
        };
        /**
         * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
         */
        FontTexture.prototype.decCachedFontTextureCounter = function () {
            var s = this.getScene();
            var dic = s.__fontTextureCache__;
            if (!dic) {
                return;
            }
            if (--this._usedCounter === 0) {
                dic.remove(this._cachedFontId);
                this.dispose();
            }
        };
        return FontTexture;
    }(BABYLON.Texture));
    BABYLON.FontTexture = FontTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.fontTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var MapTexture = (function (_super) {
        __extends(MapTexture, _super);
        function MapTexture(name, scene, size, samplingMode, useMipMap) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (useMipMap === void 0) { useMipMap = false; }
            _super.call(this, null, scene, !useMipMap, false, samplingMode);
            this.name = name;
            this._size = size;
            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            // Create the rectPackMap that will allocate portion of the texture
            this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
            // Create the texture that will store the content
            this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
        }
        /**
         * Allocate a rectangle of a given size in the texture map
         * @param size the size of the rectangle to allocation
         * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
         */
        MapTexture.prototype.allocateRect = function (size) {
            return this._rectPackingMap.addRect(size);
        };
        /**
         * Free a given rectangle from the texture map
         * @param rectInfo the instance corresponding to the rect to free.
         */
        MapTexture.prototype.freeRect = function (rectInfo) {
            if (rectInfo) {
                rectInfo.freeContent();
            }
        };
        Object.defineProperty(MapTexture.prototype, "freeSpace", {
            /**
             * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
             * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
             * @returns {}
             */
            get: function () {
                return this._rectPackingMap.freeSpace;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Bind the texture to the rendering engine to render in the zone of a given rectangle.
         * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
         * Don't forget to call unbindTexture when you're done rendering
         * @param rect the zone to render to
         * @param clear true to clear the portion's color/depth data
         */
        MapTexture.prototype.bindTextureForRect = function (rect, clear) {
            return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
        };
        /**
         * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
         * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
         * Don't forget to call unbindTexture when you're done rendering
         * @param pos the position into the texture
         * @param size the portion to fit the clip space to
         * @param clear true to clear the portion's color/depth data
         */
        MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
            var engine = this.getScene().getEngine();
            engine.bindFramebuffer(this._texture);
            this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
            if (clear) {
                // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
                engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
            }
        };
        /**
         * Unbind the texture map from the rendering engine.
         * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
         * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
         */
        MapTexture.prototype.unbindTexture = function (dumpForDebug) {
            // Dump ?
            if (dumpForDebug) {
                BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
            }
            var engine = this.getScene().getEngine();
            if (this._replacedViewport) {
                engine.setViewport(this._replacedViewport);
                this._replacedViewport = null;
            }
            engine.unBindFramebuffer(this._texture);
        };
        Object.defineProperty(MapTexture.prototype, "canRescale", {
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
        // Anyway, there's not much point to use this method for this kind of texture I guess
        MapTexture.prototype.clone = function () {
            return null;
        };
        return MapTexture;
    }(BABYLON.Texture));
    BABYLON.MapTexture = MapTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.mapTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var ShaderMaterial = (function (_super) {
        __extends(ShaderMaterial, _super);
        function ShaderMaterial(name, scene, shaderPath, options) {
            _super.call(this, name, scene);
            this._textures = {};
            this._textureArrays = {};
            this._floats = {};
            this._floatsArrays = {};
            this._colors3 = {};
            this._colors4 = {};
            this._vectors2 = {};
            this._vectors3 = {};
            this._vectors4 = {};
            this._matrices = {};
            this._matrices3x3 = {};
            this._matrices2x2 = {};
            this._vectors3Arrays = {};
            this._cachedWorldViewMatrix = new BABYLON.Matrix();
            this._shaderPath = shaderPath;
            options.needAlphaBlending = options.needAlphaBlending || false;
            options.needAlphaTesting = options.needAlphaTesting || false;
            options.attributes = options.attributes || ["position", "normal", "uv"];
            options.uniforms = options.uniforms || ["worldViewProjection"];
            options.samplers = options.samplers || [];
            options.defines = options.defines || [];
            this._options = options;
        }
        ShaderMaterial.prototype.needAlphaBlending = function () {
            return this._options.needAlphaBlending;
        };
        ShaderMaterial.prototype.needAlphaTesting = function () {
            return this._options.needAlphaTesting;
        };
        ShaderMaterial.prototype._checkUniform = function (uniformName) {
            if (this._options.uniforms.indexOf(uniformName) === -1) {
                this._options.uniforms.push(uniformName);
            }
        };
        ShaderMaterial.prototype.setTexture = function (name, texture) {
            if (this._options.samplers.indexOf(name) === -1) {
                this._options.samplers.push(name);
            }
            this._textures[name] = texture;
            return this;
        };
        ShaderMaterial.prototype.setTextureArray = function (name, textures) {
            if (this._options.samplers.indexOf(name) === -1) {
                this._options.samplers.push(name);
            }
            this._checkUniform(name);
            this._textureArrays[name] = textures;
            return this;
        };
        ShaderMaterial.prototype.setFloat = function (name, value) {
            this._checkUniform(name);
            this._floats[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setFloats = function (name, value) {
            this._checkUniform(name);
            this._floatsArrays[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setColor3 = function (name, value) {
            this._checkUniform(name);
            this._colors3[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setColor4 = function (name, value) {
            this._checkUniform(name);
            this._colors4[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setVector2 = function (name, value) {
            this._checkUniform(name);
            this._vectors2[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setVector3 = function (name, value) {
            this._checkUniform(name);
            this._vectors3[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setVector4 = function (name, value) {
            this._checkUniform(name);
            this._vectors4[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setMatrix = function (name, value) {
            this._checkUniform(name);
            this._matrices[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
            this._checkUniform(name);
            this._matrices3x3[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
            this._checkUniform(name);
            this._matrices2x2[name] = value;
            return this;
        };
        ShaderMaterial.prototype.setArray3 = function (name, value) {
            this._checkUniform(name);
            this._vectors3Arrays[name] = value;
            return this;
        };
        ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
            if (!mesh) {
                return true;
            }
            if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
                return false;
            }
            return false;
        };
        ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
            var scene = this.getScene();
            var engine = scene.getEngine();
            if (!this.checkReadyOnEveryCall) {
                if (this._renderId === scene.getRenderId()) {
                    if (this._checkCache(scene, mesh, useInstances)) {
                        return true;
                    }
                }
            }
            // Instances
            var defines = [];
            var fallbacks = new BABYLON.EffectFallbacks();
            if (useInstances) {
                defines.push("#define INSTANCES");
            }
            for (var index = 0; index < this._options.defines.length; index++) {
                defines.push(this._options.defines[index]);
            }
            // Bones
            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
                fallbacks.addCPUSkinningFallback(0, mesh);
            }
            // Alpha test
            if (engine.getAlphaTesting()) {
                defines.push("#define ALPHATEST");
            }
            var previousEffect = this._effect;
            var join = defines.join("\n");
            this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
            if (!this._effect.isReady()) {
                return false;
            }
            if (previousEffect !== this._effect) {
                scene.resetCachedMaterial();
            }
            this._renderId = scene.getRenderId();
            return true;
        };
        ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
            var scene = this.getScene();
            if (this._options.uniforms.indexOf("world") !== -1) {
                this._effect.setMatrix("world", world);
            }
            if (this._options.uniforms.indexOf("worldView") !== -1) {
                world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
            }
            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
                this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
            }
        };
        ShaderMaterial.prototype.bind = function (world, mesh) {
            // Std values
            this.bindOnlyWorldMatrix(world);
            if (this.getScene().getCachedMaterial() !== this) {
                if (this._options.uniforms.indexOf("view") !== -1) {
                    this._effect.setMatrix("view", this.getScene().getViewMatrix());
                }
                if (this._options.uniforms.indexOf("projection") !== -1) {
                    this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
                }
                if (this._options.uniforms.indexOf("viewProjection") !== -1) {
                    this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
                }
                // Bones
                BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
                var name;
                // Texture
                for (name in this._textures) {
                    this._effect.setTexture(name, this._textures[name]);
                }
                // Texture arrays
                for (name in this._textureArrays) {
                    this._effect.setTextureArray(name, this._textureArrays[name]);
                }
                // Float    
                for (name in this._floats) {
                    this._effect.setFloat(name, this._floats[name]);
                }
                // Float s   
                for (name in this._floatsArrays) {
                    this._effect.setArray(name, this._floatsArrays[name]);
                }
                // Color3        
                for (name in this._colors3) {
                    this._effect.setColor3(name, this._colors3[name]);
                }
                // Color4      
                for (name in this._colors4) {
                    var color = this._colors4[name];
                    this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
                }
                // Vector2        
                for (name in this._vectors2) {
                    this._effect.setVector2(name, this._vectors2[name]);
                }
                // Vector3        
                for (name in this._vectors3) {
                    this._effect.setVector3(name, this._vectors3[name]);
                }
                // Vector4        
                for (name in this._vectors4) {
                    this._effect.setVector4(name, this._vectors4[name]);
                }
                // Matrix      
                for (name in this._matrices) {
                    this._effect.setMatrix(name, this._matrices[name]);
                }
                // Matrix 3x3
                for (name in this._matrices3x3) {
                    this._effect.setMatrix3x3(name, this._matrices3x3[name]);
                }
                // Matrix 2x2
                for (name in this._matrices2x2) {
                    this._effect.setMatrix2x2(name, this._matrices2x2[name]);
                }
                // Vector3Array   
                for (name in this._vectors3Arrays) {
                    this._effect.setArray3(name, this._vectors3Arrays[name]);
                }
            }
            _super.prototype.bind.call(this, world, mesh);
        };
        ShaderMaterial.prototype.clone = function (name) {
            var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
            return newShaderMaterial;
        };
        ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeTextures) {
                var name;
                for (name in this._textures) {
                    this._textures[name].dispose();
                }
                for (name in this._textureArrays) {
                    var array = this._textureArrays[name];
                    for (var index = 0; index < array.length; index++) {
                        array[index].dispose();
                    }
                }
            }
            this._textures = {};
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        ShaderMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.ShaderMaterial";
            serializationObject.options = this._options;
            serializationObject.shaderPath = this._shaderPath;
            var name;
            // Texture
            serializationObject.textures = {};
            for (name in this._textures) {
                serializationObject.textures[name] = this._textures[name].serialize();
            }
            // Texture arrays
            serializationObject.textureArrays = {};
            for (name in this._textureArrays) {
                serializationObject.textureArrays[name] = [];
                var array = this._textureArrays[name];
                for (var index = 0; index < array.length; index++) {
                    serializationObject.textureArrays[name].push(array[index].serialize());
                }
            }
            // Float    
            serializationObject.floats = {};
            for (name in this._floats) {
                serializationObject.floats[name] = this._floats[name];
            }
            // Float s   
            serializationObject.floatArrays = {};
            for (name in this._floatsArrays) {
                serializationObject.floatArrays[name] = this._floatsArrays[name];
            }
            // Color3    
            serializationObject.colors3 = {};
            for (name in this._colors3) {
                serializationObject.colors3[name] = this._colors3[name].asArray();
            }
            // Color4  
            serializationObject.colors4 = {};
            for (name in this._colors4) {
                serializationObject.colors4[name] = this._colors4[name].asArray();
            }
            // Vector2  
            serializationObject.vectors2 = {};
            for (name in this._vectors2) {
                serializationObject.vectors2[name] = this._vectors2[name].asArray();
            }
            // Vector3        
            serializationObject.vectors3 = {};
            for (name in this._vectors3) {
                serializationObject.vectors3[name] = this._vectors3[name].asArray();
            }
            // Vector4        
            serializationObject.vectors4 = {};
            for (name in this._vectors4) {
                serializationObject.vectors4[name] = this._vectors4[name].asArray();
            }
            // Matrix      
            serializationObject.matrices = {};
            for (name in this._matrices) {
                serializationObject.matrices[name] = this._matrices[name].asArray();
            }
            // Matrix 3x3
            serializationObject.matrices3x3 = {};
            for (name in this._matrices3x3) {
                serializationObject.matrices3x3[name] = this._matrices3x3[name];
            }
            // Matrix 2x2
            serializationObject.matrices2x2 = {};
            for (name in this._matrices2x2) {
                serializationObject.matrices2x2[name] = this._matrices2x2[name];
            }
            // Vector3Array
            serializationObject.vectors3Arrays = {};
            for (name in this._vectors3Arrays) {
                serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
            }
            return serializationObject;
        };
        ShaderMaterial.Parse = function (source, scene, rootUrl) {
            var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
            var name;
            // Texture
            for (name in source.textures) {
                material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
            }
            // Texture arrays
            for (name in source.textureArrays) {
                var array = source.textureArrays[name];
                var textureArray = new Array();
                for (var index = 0; index < array.length; index++) {
                    textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
                }
                material.setTextureArray(name, textureArray);
            }
            // Float    
            for (name in source.floats) {
                material.setFloat(name, source.floats[name]);
            }
            // Float s   
            for (name in source.floatsArrays) {
                material.setFloats(name, source.floatsArrays[name]);
            }
            // Color3        
            for (name in source.colors3) {
                material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
            }
            // Color4      
            for (name in source.colors4) {
                material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
            }
            // Vector2        
            for (name in source.vectors2) {
                material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
            }
            // Vector3        
            for (name in source.vectors3) {
                material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
            }
            // Vector4        
            for (name in source.vectors4) {
                material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
            }
            // Matrix      
            for (name in source.matrices) {
                material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
            }
            // Matrix 3x3
            for (name in source.matrices3x3) {
                material.setMatrix3x3(name, source.matrices3x3[name]);
            }
            // Matrix 2x2
            for (name in source.matrices2x2) {
                material.setMatrix2x2(name, source.matrices2x2[name]);
            }
            // Vector3Array
            for (name in source.vectors3Arrays) {
                material.setArray3(name, source.vectors3Arrays[name]);
            }
            return material;
        };
        return ShaderMaterial;
    }(BABYLON.Material));
    BABYLON.ShaderMaterial = ShaderMaterial;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.shaderMaterial.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
        // All values and structures referenced from:
        // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
        var DDS_MAGIC = 0x20534444;
        var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
        var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
        var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
        var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
        function FourCCToInt32(value) {
            return value.charCodeAt(0) +
                (value.charCodeAt(1) << 8) +
                (value.charCodeAt(2) << 16) +
                (value.charCodeAt(3) << 24);
        }
        function Int32ToFourCC(value) {
            return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
        }
        var FOURCC_DXT1 = FourCCToInt32("DXT1");
        var FOURCC_DXT3 = FourCCToInt32("DXT3");
        var FOURCC_DXT5 = FourCCToInt32("DXT5");
        var headerLengthInt = 31; // The header length in 32 bit ints
        // Offsets into the header array
        var off_magic = 0;
        var off_size = 1;
        var off_flags = 2;
        var off_height = 3;
        var off_width = 4;
        var off_mipmapCount = 7;
        var off_pfFlags = 20;
        var off_pfFourCC = 21;
        var off_RGBbpp = 22;
        var off_RMask = 23;
        var off_GMask = 24;
        var off_BMask = 25;
        var off_AMask = 26;
        var off_caps1 = 27;
        var off_caps2 = 28;
        ;
        var DDSTools = (function () {
            function DDSTools() {
            }
            DDSTools.GetDDSInfo = function (arrayBuffer) {
                var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
                var mipmapCount = 1;
                if (header[off_flags] & DDSD_MIPMAPCOUNT) {
                    mipmapCount = Math.max(1, header[off_mipmapCount]);
                }
                return {
                    width: header[off_width],
                    height: header[off_height],
                    mipmapCount: mipmapCount,
                    isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
                    isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
                    isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
                    isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
                };
            };
            DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
                var byteArray = new Uint8Array(dataLength);
                var srcData = new Uint8Array(arrayBuffer);
                var index = 0;
                for (var y = height - 1; y >= 0; y--) {
                    for (var x = 0; x < width; x++) {
                        var srcPos = dataOffset + (x + y * width) * 4;
                        byteArray[index + 2] = srcData[srcPos];
                        byteArray[index + 1] = srcData[srcPos + 1];
                        byteArray[index] = srcData[srcPos + 2];
                        byteArray[index + 3] = srcData[srcPos + 3];
                        index += 4;
                    }
                }
                return byteArray;
            };
            DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
                var byteArray = new Uint8Array(dataLength);
                var srcData = new Uint8Array(arrayBuffer);
                var index = 0;
                for (var y = height - 1; y >= 0; y--) {
                    for (var x = 0; x < width; x++) {
                        var srcPos = dataOffset + (x + y * width) * 3;
                        byteArray[index + 2] = srcData[srcPos];
                        byteArray[index + 1] = srcData[srcPos + 1];
                        byteArray[index] = srcData[srcPos + 2];
                        index += 3;
                    }
                }
                return byteArray;
            };
            DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
                var byteArray = new Uint8Array(dataLength);
                var srcData = new Uint8Array(arrayBuffer);
                var index = 0;
                for (var y = height - 1; y >= 0; y--) {
                    for (var x = 0; x < width; x++) {
                        var srcPos = dataOffset + (x + y * width);
                        byteArray[index] = srcData[srcPos];
                        index++;
                    }
                }
                return byteArray;
            };
            DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
                var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
                if (header[off_magic] != DDS_MAGIC) {
                    BABYLON.Tools.Error("Invalid magic number in DDS header");
                    return;
                }
                if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
                    BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
                    return;
                }
                if (info.isFourCC) {
                    fourCC = header[off_pfFourCC];
                    switch (fourCC) {
                        case FOURCC_DXT1:
                            blockBytes = 8;
                            internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
                            break;
                        case FOURCC_DXT3:
                            blockBytes = 16;
                            internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
                            break;
                        case FOURCC_DXT5:
                            blockBytes = 16;
                            internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
                            break;
                        default:
                            console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
                            return;
                    }
                }
                mipmapCount = 1;
                if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
                    mipmapCount = Math.max(1, header[off_mipmapCount]);
                }
                var bpp = header[off_RGBbpp];
                for (var face = 0; face < faces; face++) {
                    var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
                    width = header[off_width];
                    height = header[off_height];
                    dataOffset = header[off_size] + 4;
                    for (i = 0; i < mipmapCount; ++i) {
                        if (info.isRGB) {
                            if (bpp === 24) {
                                dataLength = width * height * 3;
                                byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
                                gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
                            }
                            else {
                                dataLength = width * height * 4;
                                byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
                                gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
                            }
                        }
                        else if (info.isLuminance) {
                            var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
                            var unpaddedRowSize = width;
                            var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
                            dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
                            byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
                            gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
                        }
                        else {
                            dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
                            byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
                            gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
                        }
                        dataOffset += dataLength;
                        width *= 0.5;
                        height *= 0.5;
                        width = Math.max(1.0, width);
                        height = Math.max(1.0, height);
                    }
                }
            };
            return DDSTools;
        }());
        Internals.DDSTools = DDSTools;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.dds.js.map
 
var BABYLON;
(function (BABYLON) {
    var CannonJSPlugin = (function () {
        function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
            if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
            if (iterations === void 0) { iterations = 10; }
            this._useDeltaForWorldStep = _useDeltaForWorldStep;
            this.name = "CannonJSPlugin";
            this._physicsMaterials = [];
            this._fixedTimeStep = 1 / 60;
            //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
            this._currentCollisionGroup = 2;
            this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
            this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
            this._tmpPosition = BABYLON.Vector3.Zero();
            this._tmpQuaternion = new BABYLON.Quaternion();
            this._tmpDeltaPosition = BABYLON.Vector3.Zero();
            this._tmpDeltaRotation = new BABYLON.Quaternion();
            this._tmpUnityRotation = new BABYLON.Quaternion();
            if (!this.isSupported()) {
                BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
                return;
            }
            this.world = new CANNON.World();
            this.world.broadphase = new CANNON.NaiveBroadphase();
            this.world.solver.iterations = iterations;
        }
        CannonJSPlugin.prototype.setGravity = function (gravity) {
            this.world.gravity.copy(gravity);
        };
        CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
            this._fixedTimeStep = timeStep;
        };
        CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
            this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
        };
        CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
            var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
            var impulse = new CANNON.Vec3(force.x, force.y, force.z);
            impostor.physicsBody.applyImpulse(impulse, worldPoint);
        };
        CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
            var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
            var impulse = new CANNON.Vec3(force.x, force.y, force.z);
            impostor.physicsBody.applyImpulse(impulse, worldPoint);
        };
        CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
            //parent-child relationship. Does this impostor has a parent impostor?
            if (impostor.parent) {
                if (impostor.physicsBody) {
                    this.removePhysicsBody(impostor);
                    //TODO is that needed?
                    impostor.forceUpdate();
                }
                return;
            }
            //should a new body be created for this impostor?
            if (impostor.isBodyInitRequired()) {
                var shape = this._createShape(impostor);
                //unregister events, if body is being changed
                var oldBody = impostor.physicsBody;
                if (oldBody) {
                    this.removePhysicsBody(impostor);
                }
                //create the body and material
                var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
                var bodyCreationObject = {
                    mass: impostor.getParam("mass"),
                    material: material
                };
                // A simple extend, in case native options were used.
                var nativeOptions = impostor.getParam("nativeOptions");
                for (var key in nativeOptions) {
                    if (nativeOptions.hasOwnProperty(key)) {
                        bodyCreationObject[key] = nativeOptions[key];
                    }
                }
                impostor.physicsBody = new CANNON.Body(bodyCreationObject);
                impostor.physicsBody.addEventListener("collide", impostor.onCollide);
                this.world.addEventListener("preStep", impostor.beforeStep);
                this.world.addEventListener("postStep", impostor.afterStep);
                impostor.physicsBody.addShape(shape);
                this.world.add(impostor.physicsBody);
                //try to keep the body moving in the right direction by taking old properties.
                //Should be tested!
                if (oldBody) {
                    ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
                        impostor.physicsBody[param].copy(oldBody[param]);
                    });
                }
                this._processChildMeshes(impostor);
            }
            //now update the body's transformation
            this._updatePhysicsBodyTransformation(impostor);
        };
        CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
            var _this = this;
            var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
            if (meshChildren.length) {
                var processMesh = function (localPosition, mesh) {
                    var childImpostor = mesh.getPhysicsImpostor();
                    if (childImpostor) {
                        var parent = childImpostor.parent;
                        if (parent !== mainImpostor) {
                            var localPosition = mesh.position;
                            if (childImpostor.physicsBody) {
                                _this.removePhysicsBody(childImpostor);
                                childImpostor.physicsBody = null;
                            }
                            childImpostor.parent = mainImpostor;
                            childImpostor.resetUpdateFlags();
                            mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
                            //Add the mass of the children.
                            mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
                        }
                    }
                    mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
                };
                meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
            }
        };
        CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
            impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
            this.world.removeEventListener("preStep", impostor.beforeStep);
            this.world.removeEventListener("postStep", impostor.afterStep);
            this.world.remove(impostor.physicsBody);
        };
        CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
            var mainBody = impostorJoint.mainImpostor.physicsBody;
            var connectedBody = impostorJoint.connectedImpostor.physicsBody;
            if (!mainBody || !connectedBody) {
                return;
            }
            var constraint;
            var jointData = impostorJoint.joint.jointData;
            //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
            var constraintData = {
                pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
                pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
                axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
                axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
                maxForce: jointData.nativeParams.maxForce,
                collideConnected: !!jointData.collision
            };
            //Not needed, Cannon has a collideConnected flag
            /*if (!jointData.collision) {
                //add 1st body to a collision group of its own, if it is not in 1
                if (mainBody.collisionFilterGroup === 1) {
                    mainBody.collisionFilterGroup = this._currentCollisionGroup;
                    this._currentCollisionGroup <<= 1;
                }
                if (connectedBody.collisionFilterGroup === 1) {
                    connectedBody.collisionFilterGroup = this._currentCollisionGroup;
                    this._currentCollisionGroup <<= 1;
                }
                //add their mask to the collisionFilterMask of each other:
                connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
                mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
            }*/
            switch (impostorJoint.joint.type) {
                case BABYLON.PhysicsJoint.HingeJoint:
                case BABYLON.PhysicsJoint.Hinge2Joint:
                    constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
                    break;
                case BABYLON.PhysicsJoint.DistanceJoint:
                    constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
                    break;
                case BABYLON.PhysicsJoint.SpringJoint:
                    var springData = jointData;
                    constraint = new CANNON.Spring(mainBody, connectedBody, {
                        restLength: springData.length,
                        stiffness: springData.stiffness,
                        damping: springData.damping,
                        localAnchorA: constraintData.pivotA,
                        localAnchorB: constraintData.pivotB
                    });
                    break;
                case BABYLON.PhysicsJoint.LockJoint:
                    constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
                    break;
                case BABYLON.PhysicsJoint.PointToPointJoint:
                case BABYLON.PhysicsJoint.BallAndSocketJoint:
                default:
                    constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
                    break;
            }
            //set the collideConnected flag after the creation, since DistanceJoint ignores it.
            constraint.collideConnected = !!jointData.collision;
            impostorJoint.joint.physicsJoint = constraint;
            //don't add spring as constraint, as it is not one.
            if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
                this.world.addConstraint(constraint);
            }
            else {
                impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
                    constraint.applyForce();
                });
            }
        };
        CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
            this.world.removeConstraint(impostorJoint.joint.physicsJoint);
        };
        CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
            var index;
            var mat;
            for (index = 0; index < this._physicsMaterials.length; index++) {
                mat = this._physicsMaterials[index];
                if (mat.friction === friction && mat.restitution === restitution) {
                    return mat;
                }
            }
            var currentMat = new CANNON.Material(name);
            currentMat.friction = friction;
            currentMat.restitution = restitution;
            this._physicsMaterials.push(currentMat);
            return currentMat;
        };
        CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
            return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
        };
        CannonJSPlugin.prototype._createShape = function (impostor) {
            var object = impostor.object;
            var returnValue;
            var extendSize = impostor.getObjectExtendSize();
            switch (impostor.type) {
                case BABYLON.PhysicsEngine.SphereImpostor:
                    var radiusX = extendSize.x;
                    var radiusY = extendSize.y;
                    var radiusZ = extendSize.z;
                    returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
                    break;
                //TMP also for cylinder - TODO Cannon supports cylinder natively.
                case BABYLON.PhysicsImpostor.CylinderImpostor:
                    returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
                    break;
                case BABYLON.PhysicsImpostor.BoxImpostor:
                    var box = extendSize.scale(0.5);
                    returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
                    break;
                case BABYLON.PhysicsImpostor.PlaneImpostor:
                    BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
                    returnValue = new CANNON.Plane();
                    break;
                case BABYLON.PhysicsImpostor.MeshImpostor:
                    var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
                    var rawFaces = object.getIndices ? object.getIndices() : [];
                    BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
                    returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
                    break;
                case BABYLON.PhysicsImpostor.HeightmapImpostor:
                    returnValue = this._createHeightmap(object);
                    break;
                case BABYLON.PhysicsImpostor.ParticleImpostor:
                    returnValue = new CANNON.Particle();
                    break;
            }
            return returnValue;
        };
        CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
            var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var matrix = [];
            //For now pointDepth will not be used and will be automatically calculated.
            //Future reference - try and find the best place to add a reference to the pointDepth variable.
            var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
            var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
            var elementSize = dim * 2 / arraySize;
            var minY = object.getBoundingInfo().boundingBox.extendSize.y;
            for (var i = 0; i < pos.length; i = i + 3) {
                var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
                var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
                var y = pos[i + 1] + minY;
                if (!matrix[x]) {
                    matrix[x] = [];
                }
                if (!matrix[x][z]) {
                    matrix[x][z] = y;
                }
                matrix[x][z] = Math.max(y, matrix[x][z]);
            }
            for (var x = 0; x <= arraySize; ++x) {
                if (!matrix[x]) {
                    var loc = 1;
                    while (!matrix[(x + loc) % arraySize]) {
                        loc++;
                    }
                    matrix[x] = matrix[(x + loc) % arraySize].slice();
                }
                for (var z = 0; z <= arraySize; ++z) {
                    if (!matrix[x][z]) {
                        var loc = 1;
                        var newValue;
                        while (newValue === undefined) {
                            newValue = matrix[x][(z + loc++) % arraySize];
                        }
                        matrix[x][z] = newValue;
                    }
                }
            }
            var shape = new CANNON.Heightfield(matrix, {
                elementSize: elementSize
            });
            //For future reference, needed for body transformation
            shape.minY = minY;
            return shape;
        };
        CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
            var object = impostor.object;
            //make sure it is updated...
            object.computeWorldMatrix && object.computeWorldMatrix(true);
            // The delta between the mesh position and the mesh bounding box center
            var center = impostor.getObjectCenter();
            var extendSize = impostor.getObjectExtendSize();
            this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
            this._tmpPosition.copyFrom(center);
            var quaternion = object.rotationQuaternion;
            //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
            if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
                //-90 DEG in X, precalculated
                quaternion = quaternion.multiply(this._minus90X);
                //Invert! (Precalculated, 90 deg in X)
                //No need to clone. this will never change.
                impostor.setDeltaRotation(this._plus90X);
            }
            //If it is a heightfield, if should be centered.
            if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
                var mesh = object;
                //calculate the correct body position:
                var rotationQuaternion = mesh.rotationQuaternion;
                mesh.rotationQuaternion = this._tmpUnityRotation;
                mesh.computeWorldMatrix(true);
                //get original center with no rotation
                var c = center.clone();
                var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
                //rotation is back
                mesh.rotationQuaternion = rotationQuaternion;
                //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
                var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
                mesh.setPivotMatrix(p);
                mesh.computeWorldMatrix(true);
                //calculate the translation
                var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
                this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
                //add it inverted to the delta 
                this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
                this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
                mesh.setPivotMatrix(oldPivot);
                mesh.computeWorldMatrix(true);
            }
            else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
                this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
                this._tmpPosition.copyFrom(object.position);
            }
            impostor.setDeltaPosition(this._tmpDeltaPosition);
            //Now update the impostor object
            impostor.physicsBody.position.copy(this._tmpPosition);
            impostor.physicsBody.quaternion.copy(quaternion);
        };
        CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
            impostor.object.position.copyFrom(impostor.physicsBody.position);
            impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
        };
        CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
            impostor.physicsBody.position.copy(newPosition);
            impostor.physicsBody.quaternion.copy(newRotation);
        };
        CannonJSPlugin.prototype.isSupported = function () {
            return window.CANNON !== undefined;
        };
        CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
            impostor.physicsBody.velocity.copy(velocity);
        };
        CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
            impostor.physicsBody.angularVelocity.copy(velocity);
        };
        CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
            var v = impostor.physicsBody.velocity;
            if (!v)
                return null;
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
            var v = impostor.physicsBody.angularVelocity;
            if (!v)
                return null;
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
            impostor.physicsBody.mass = mass;
            impostor.physicsBody.updateMassProperties();
        };
        CannonJSPlugin.prototype.sleepBody = function (impostor) {
            impostor.physicsBody.sleep();
        };
        CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
            impostor.physicsBody.wakeUp();
        };
        CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
            joint.physicsJoint.distance = maxDistance;
        };
        CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
            if (!motorIndex) {
                joint.physicsJoint.enableMotor();
            }
        };
        CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
            if (!motorIndex) {
                joint.physicsJoint.disableMotor();
            }
        };
        CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
            if (!motorIndex) {
                joint.physicsJoint.enableMotor();
                joint.physicsJoint.setMotorSpeed(speed);
                if (maxForce) {
                    this.setLimit(joint, maxForce);
                }
            }
        };
        CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
            joint.physicsJoint.motorEquation.maxForce = upperLimit;
            joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
        };
        CannonJSPlugin.prototype.dispose = function () {
            //nothing to do, actually.
        };
        return CannonJSPlugin;
    }());
    BABYLON.CannonJSPlugin = CannonJSPlugin;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.cannonJSPlugin.js.map
 
var BABYLON;
(function (BABYLON) {
    var OimoJSPlugin = (function () {
        function OimoJSPlugin(iterations) {
            this.name = "OimoJSPlugin";
            this._tmpImpostorsArray = [];
            this._tmpPositionVector = BABYLON.Vector3.Zero();
            this.world = new OIMO.World(1 / 60, 2, iterations, true);
            this.world.worldscale(1);
            this.world.clear();
            //making sure no stats are calculated
            this.world.isNoStat = true;
        }
        OimoJSPlugin.prototype.setGravity = function (gravity) {
            this.world.gravity.copy(gravity);
        };
        OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
            this.world.timeStep = timeStep;
        };
        OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
            var _this = this;
            impostors.forEach(function (impostor) {
                impostor.beforeStep();
            });
            this.world.step();
            impostors.forEach(function (impostor) {
                impostor.afterStep();
                //update the ordered impostors array
                _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
            });
            //check for collisions
            var contact = this.world.contacts;
            while (contact !== null) {
                if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
                    contact = contact.next;
                    continue;
                }
                //is this body colliding with any other? get the impostor
                var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
                var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
                if (!mainImpostor || !collidingImpostor) {
                    contact = contact.next;
                    continue;
                }
                mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
                collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
                contact = contact.next;
            }
        };
        OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
            var mass = impostor.physicsBody.massInfo.mass;
            impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
        };
        OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
            BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
            this.applyImpulse(impostor, force, contactPoint);
        };
        OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
            var _this = this;
            //parent-child relationship. Does this impostor has a parent impostor?
            if (impostor.parent) {
                if (impostor.physicsBody) {
                    this.removePhysicsBody(impostor);
                    //TODO is that needed?
                    impostor.forceUpdate();
                }
                return;
            }
            if (impostor.isBodyInitRequired()) {
                var bodyConfig = {
                    name: impostor.uniqueId,
                    //Oimo must have mass, also for static objects.
                    config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
                    size: [],
                    type: [],
                    pos: [],
                    rot: [],
                    move: impostor.getParam("mass") !== 0,
                    //Supporting older versions of Oimo
                    world: this.world
                };
                var impostors = [impostor];
                var addToArray = function (parent) {
                    if (!parent.getChildMeshes)
                        return;
                    parent.getChildMeshes().forEach(function (m) {
                        if (m.physicsImpostor) {
                            impostors.push(m.physicsImpostor);
                            m.physicsImpostor._init();
                        }
                    });
                };
                addToArray(impostor.object);
                var checkWithEpsilon_1 = function (value) {
                    return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
                };
                impostors.forEach(function (i) {
                    //get the correct bounding box
                    var oldQuaternion = i.object.rotationQuaternion;
                    var rot = new OIMO.Euler().setFromQuaternion({
                        x: impostor.object.rotationQuaternion.x,
                        y: impostor.object.rotationQuaternion.y,
                        z: impostor.object.rotationQuaternion.z,
                        s: impostor.object.rotationQuaternion.w
                    });
                    var extendSize = i.getObjectExtendSize();
                    if (i === impostor) {
                        var center = impostor.getObjectCenter();
                        impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
                        //Can also use Array.prototype.push.apply
                        bodyConfig.pos.push(center.x);
                        bodyConfig.pos.push(center.y);
                        bodyConfig.pos.push(center.z);
                        //tmp solution
                        bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
                        bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
                        bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
                    }
                    else {
                        bodyConfig.pos.push(i.object.position.x);
                        bodyConfig.pos.push(i.object.position.y);
                        bodyConfig.pos.push(i.object.position.z);
                        //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
                        bodyConfig.rot.push(0);
                        bodyConfig.rot.push(0);
                        bodyConfig.rot.push(0);
                    }
                    // register mesh
                    switch (i.type) {
                        case BABYLON.PhysicsImpostor.ParticleImpostor:
                            BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
                        case BABYLON.PhysicsImpostor.SphereImpostor:
                            var radiusX = extendSize.x;
                            var radiusY = extendSize.y;
                            var radiusZ = extendSize.z;
                            var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
                            bodyConfig.type.push('sphere');
                            //due to the way oimo works with compounds, add 3 times
                            bodyConfig.size.push(size);
                            bodyConfig.size.push(size);
                            bodyConfig.size.push(size);
                            break;
                        case BABYLON.PhysicsImpostor.CylinderImpostor:
                            var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
                            var sizeY = checkWithEpsilon_1(extendSize.y);
                            bodyConfig.type.push('cylinder');
                            bodyConfig.size.push(sizeX);
                            bodyConfig.size.push(sizeY);
                            //due to the way oimo works with compounds, add one more value.
                            bodyConfig.size.push(sizeY);
                            break;
                        case BABYLON.PhysicsImpostor.PlaneImpostor:
                        case BABYLON.PhysicsImpostor.BoxImpostor:
                        default:
                            var sizeX = checkWithEpsilon_1(extendSize.x);
                            var sizeY = checkWithEpsilon_1(extendSize.y);
                            var sizeZ = checkWithEpsilon_1(extendSize.z);
                            bodyConfig.type.push('box');
                            bodyConfig.size.push(sizeX);
                            bodyConfig.size.push(sizeY);
                            bodyConfig.size.push(sizeZ);
                            break;
                    }
                    //actually not needed, but hey...
                    i.object.rotationQuaternion = oldQuaternion;
                });
                impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
            }
            else {
                this._tmpPositionVector.copyFromFloats(0, 0, 0);
            }
            impostor.setDeltaPosition(this._tmpPositionVector);
            //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
            //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
        };
        OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
            //impostor.physicsBody.dispose();
            //Same as : (older oimo versions)
            this.world.removeRigidBody(impostor.physicsBody);
        };
        OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
            var mainBody = impostorJoint.mainImpostor.physicsBody;
            var connectedBody = impostorJoint.connectedImpostor.physicsBody;
            if (!mainBody || !connectedBody) {
                return;
            }
            var jointData = impostorJoint.joint.jointData;
            var options = jointData.nativeParams || {};
            var type;
            var nativeJointData = {
                body1: mainBody,
                body2: connectedBody,
                axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
                axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
                pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
                pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
                min: options.min,
                max: options.max,
                collision: options.collision || jointData.collision,
                spring: options.spring,
                //supporting older version of Oimo
                world: this.world
            };
            switch (impostorJoint.joint.type) {
                case BABYLON.PhysicsJoint.BallAndSocketJoint:
                    type = "jointBall";
                    break;
                case BABYLON.PhysicsJoint.SpringJoint:
                    BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
                    var springData = jointData;
                    nativeJointData.min = springData.length || nativeJointData.min;
                    //Max should also be set, just make sure it is at least min
                    nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
                case BABYLON.PhysicsJoint.DistanceJoint:
                    type = "jointDistance";
                    nativeJointData.max = jointData.maxDistance;
                    break;
                case BABYLON.PhysicsJoint.PrismaticJoint:
                    type = "jointPrisme";
                    break;
                case BABYLON.PhysicsJoint.SliderJoint:
                    type = "jointSlide";
                    break;
                case BABYLON.PhysicsJoint.WheelJoint:
                    type = "jointWheel";
                    break;
                case BABYLON.PhysicsJoint.HingeJoint:
                default:
                    type = "jointHinge";
                    break;
            }
            nativeJointData.type = type;
            impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
        };
        OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
            //Bug in Oimo prevents us from disposing a joint in the playground
            //joint.joint.physicsJoint.dispose();
            //So we will bruteforce it!
            try {
                this.world.removeJoint(impostorJoint.joint.physicsJoint);
            }
            catch (e) {
                BABYLON.Tools.Warn(e);
            }
        };
        OimoJSPlugin.prototype.isSupported = function () {
            return OIMO !== undefined;
        };
        OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
            if (!impostor.physicsBody.sleeping) {
                //TODO check that
                if (impostor.physicsBody.shapes.next) {
                    var parentShape = this._getLastShape(impostor.physicsBody);
                    impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
                    impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
                    impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
                }
                else {
                    impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
                }
                impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
                impostor.object.rotationQuaternion.normalize();
            }
        };
        OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
            var body = impostor.physicsBody;
            body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
            body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
            body.syncShapes();
            body.awake();
        };
        OimoJSPlugin.prototype._getLastShape = function (body) {
            var lastShape = body.shapes;
            while (lastShape.next) {
                lastShape = lastShape.next;
            }
            return lastShape;
        };
        OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
            impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
        };
        OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
            impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
        };
        OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
            var v = impostor.physicsBody.linearVelocity;
            if (!v)
                return null;
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
            var v = impostor.physicsBody.angularVelocity;
            if (!v)
                return null;
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
            var staticBody = mass === 0;
            //this will actually set the body's density and not its mass.
            //But this is how oimo treats the mass variable.
            impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
            impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
        };
        OimoJSPlugin.prototype.sleepBody = function (impostor) {
            impostor.physicsBody.sleep();
        };
        OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
            impostor.physicsBody.awake();
        };
        OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
            joint.physicsJoint.limitMotor.upperLimit = maxDistance;
            if (minDistance !== void 0) {
                joint.physicsJoint.limitMotor.lowerLimit = minDistance;
            }
        };
        OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
            //TODO separate rotational and transational motors.
            var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
            if (motor) {
                motor.setMotor(speed, maxForce);
            }
        };
        OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
            //TODO separate rotational and transational motors.
            var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
            if (motor) {
                motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
            }
        };
        OimoJSPlugin.prototype.dispose = function () {
            this.world.clear();
        };
        return OimoJSPlugin;
    }());
    BABYLON.OimoJSPlugin = OimoJSPlugin;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.oimoJSPlugin.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var DisplayPassPostProcess = (function (_super) {
        __extends(DisplayPassPostProcess, _super);
        function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
            _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
        }
        return DisplayPassPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.displayPassPostProcess.js.map
 
var BABYLON;
(function (BABYLON) {
    var SimplificationSettings = (function () {
        function SimplificationSettings(quality, distance, optimizeMesh) {
            this.quality = quality;
            this.distance = distance;
            this.optimizeMesh = optimizeMesh;
        }
        return SimplificationSettings;
    }());
    BABYLON.SimplificationSettings = SimplificationSettings;
    var SimplificationQueue = (function () {
        function SimplificationQueue() {
            this.running = false;
            this._simplificationArray = [];
        }
        SimplificationQueue.prototype.addTask = function (task) {
            this._simplificationArray.push(task);
        };
        SimplificationQueue.prototype.executeNext = function () {
            var task = this._simplificationArray.pop();
            if (task) {
                this.running = true;
                this.runSimplification(task);
            }
            else {
                this.running = false;
            }
        };
        SimplificationQueue.prototype.runSimplification = function (task) {
            var _this = this;
            if (task.parallelProcessing) {
                //parallel simplifier
                task.settings.forEach(function (setting) {
                    var simplifier = _this.getSimplifier(task);
                    simplifier.simplify(setting, function (newMesh) {
                        task.mesh.addLODLevel(setting.distance, newMesh);
                        newMesh.isVisible = true;
                        //check if it is the last
                        if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
                            //all done, run the success callback.
                            task.successCallback();
                        }
                        _this.executeNext();
                    });
                });
            }
            else {
                //single simplifier.
                var simplifier = this.getSimplifier(task);
                var runDecimation = function (setting, callback) {
                    simplifier.simplify(setting, function (newMesh) {
                        task.mesh.addLODLevel(setting.distance, newMesh);
                        newMesh.isVisible = true;
                        //run the next quality level
                        callback();
                    });
                };
                BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
                    runDecimation(task.settings[loop.index], function () {
                        loop.executeNext();
                    });
                }, function () {
                    //execution ended, run the success callback.
                    if (task.successCallback) {
                        task.successCallback();
                    }
                    _this.executeNext();
                });
            }
        };
        SimplificationQueue.prototype.getSimplifier = function (task) {
            switch (task.simplificationType) {
                case SimplificationType.QUADRATIC:
                default:
                    return new QuadraticErrorSimplification(task.mesh);
            }
        };
        return SimplificationQueue;
    }());
    BABYLON.SimplificationQueue = SimplificationQueue;
    /**
     * The implemented types of simplification.
     * At the moment only Quadratic Error Decimation is implemented.
     */
    (function (SimplificationType) {
        SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
    })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
    var SimplificationType = BABYLON.SimplificationType;
    var DecimationTriangle = (function () {
        function DecimationTriangle(vertices) {
            this.vertices = vertices;
            this.error = new Array(4);
            this.deleted = false;
            this.isDirty = false;
            this.deletePending = false;
            this.borderFactor = 0;
        }
        return DecimationTriangle;
    }());
    BABYLON.DecimationTriangle = DecimationTriangle;
    var DecimationVertex = (function () {
        function DecimationVertex(position, id) {
            this.position = position;
            this.id = id;
            this.isBorder = true;
            this.q = new QuadraticMatrix();
            this.triangleCount = 0;
            this.triangleStart = 0;
            this.originalOffsets = [];
        }
        DecimationVertex.prototype.updatePosition = function (newPosition) {
            this.position.copyFrom(newPosition);
        };
        return DecimationVertex;
    }());
    BABYLON.DecimationVertex = DecimationVertex;
    var QuadraticMatrix = (function () {
        function QuadraticMatrix(data) {
            this.data = new Array(10);
            for (var i = 0; i < 10; ++i) {
                if (data && data[i]) {
                    this.data[i] = data[i];
                }
                else {
                    this.data[i] = 0;
                }
            }
        }
        QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
            var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
                this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
                this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
            return det;
        };
        QuadraticMatrix.prototype.addInPlace = function (matrix) {
            for (var i = 0; i < 10; ++i) {
                this.data[i] += matrix.data[i];
            }
        };
        QuadraticMatrix.prototype.addArrayInPlace = function (data) {
            for (var i = 0; i < 10; ++i) {
                this.data[i] += data[i];
            }
        };
        QuadraticMatrix.prototype.add = function (matrix) {
            var m = new QuadraticMatrix();
            for (var i = 0; i < 10; ++i) {
                m.data[i] = this.data[i] + matrix.data[i];
            }
            return m;
        };
        QuadraticMatrix.FromData = function (a, b, c, d) {
            return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
        };
        //returning an array to avoid garbage collection
        QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
            return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
        };
        return QuadraticMatrix;
    }());
    BABYLON.QuadraticMatrix = QuadraticMatrix;
    var Reference = (function () {
        function Reference(vertexId, triangleId) {
            this.vertexId = vertexId;
            this.triangleId = triangleId;
        }
        return Reference;
    }());
    BABYLON.Reference = Reference;
    /**
     * An implementation of the Quadratic Error simplification algorithm.
     * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
     * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
     * @author RaananW
     */
    var QuadraticErrorSimplification = (function () {
        function QuadraticErrorSimplification(_mesh) {
            this._mesh = _mesh;
            this.initialized = false;
            this.syncIterations = 5000;
            this.aggressiveness = 7;
            this.decimationIterations = 100;
            this.boundingBoxEpsilon = BABYLON.Epsilon;
        }
        QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
            var _this = this;
            this.initDecimatedMesh();
            //iterating through the submeshes array, one after the other.
            BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
                _this.initWithMesh(loop.index, function () {
                    _this.runDecimation(settings, loop.index, function () {
                        loop.executeNext();
                    });
                }, settings.optimizeMesh);
            }, function () {
                setTimeout(function () {
                    successCallback(_this._reconstructedMesh);
                }, 0);
            });
        };
        QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
            var _this = this;
            var gCount = 0;
            triangle.vertices.forEach(function (vertex) {
                var count = 0;
                var vPos = vertex.position;
                var bbox = _this._mesh.getBoundingInfo().boundingBox;
                if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
                    ++count;
                if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
                    ++count;
                if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
                    ++count;
                if (count > 1) {
                    ++gCount;
                }
                ;
            });
            if (gCount > 1) {
                console.log(triangle, gCount);
            }
            return gCount > 1;
        };
        QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
            var _this = this;
            var targetCount = ~~(this.triangles.length * settings.quality);
            var deletedTriangles = 0;
            var triangleCount = this.triangles.length;
            var iterationFunction = function (iteration, callback) {
                setTimeout(function () {
                    if (iteration % 5 === 0) {
                        _this.updateMesh(iteration === 0);
                    }
                    for (var i = 0; i < _this.triangles.length; ++i) {
                        _this.triangles[i].isDirty = false;
                    }
                    var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
                    var trianglesIterator = function (i) {
                        var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
                        var t = _this.triangles[tIdx];
                        if (!t)
                            return;
                        if (t.error[3] > threshold || t.deleted || t.isDirty) {
                            return;
                        }
                        for (var j = 0; j < 3; ++j) {
                            if (t.error[j] < threshold) {
                                var deleted0 = [];
                                var deleted1 = [];
                                var v0 = t.vertices[j];
                                var v1 = t.vertices[(j + 1) % 3];
                                if (v0.isBorder || v1.isBorder)
                                    continue;
                                var p = BABYLON.Vector3.Zero();
                                var n = BABYLON.Vector3.Zero();
                                var uv = BABYLON.Vector2.Zero();
                                var color = new BABYLON.Color4(0, 0, 0, 1);
                                _this.calculateError(v0, v1, p, n, uv, color);
                                var delTr = [];
                                if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
                                    continue;
                                if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
                                    continue;
                                if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
                                    continue;
                                var uniqueArray = [];
                                delTr.forEach(function (deletedT) {
                                    if (uniqueArray.indexOf(deletedT) === -1) {
                                        deletedT.deletePending = true;
                                        uniqueArray.push(deletedT);
                                    }
                                });
                                if (uniqueArray.length % 2 !== 0) {
                                    continue;
                                }
                                v0.q = v1.q.add(v0.q);
                                v0.updatePosition(p);
                                var tStart = _this.references.length;
                                deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
                                deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
                                var tCount = _this.references.length - tStart;
                                if (tCount <= v0.triangleCount) {
                                    if (tCount) {
                                        for (var c = 0; c < tCount; c++) {
                                            _this.references[v0.triangleStart + c] = _this.references[tStart + c];
                                        }
                                    }
                                }
                                else {
                                    v0.triangleStart = tStart;
                                }
                                v0.triangleCount = tCount;
                                break;
                            }
                        }
                    };
                    BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
                }, 0);
            };
            BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
                if (triangleCount - deletedTriangles <= targetCount)
                    loop.breakLoop();
                else {
                    iterationFunction(loop.index, function () {
                        loop.executeNext();
                    });
                }
            }, function () {
                setTimeout(function () {
                    //reconstruct this part of the mesh
                    _this.reconstructMesh(submeshIndex);
                    successCallback();
                }, 0);
            });
        };
        QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
            var _this = this;
            this.vertices = [];
            this.triangles = [];
            var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this._mesh.getIndices();
            var submesh = this._mesh.subMeshes[submeshIndex];
            var findInVertices = function (positionToSearch) {
                if (optimizeMesh) {
                    for (var ii = 0; ii < _this.vertices.length; ++ii) {
                        if (_this.vertices[ii].position.equals(positionToSearch)) {
                            return _this.vertices[ii];
                        }
                    }
                }
                return null;
            };
            var vertexReferences = [];
            var vertexInit = function (i) {
                var offset = i + submesh.verticesStart;
                var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
                var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
                vertex.originalOffsets.push(offset);
                if (vertex.id === _this.vertices.length) {
                    _this.vertices.push(vertex);
                }
                vertexReferences.push(vertex.id);
            };
            //var totalVertices = mesh.getTotalVertices();
            var totalVertices = submesh.verticesCount;
            BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
                var indicesInit = function (i) {
                    var offset = (submesh.indexStart / 3) + i;
                    var pos = (offset * 3);
                    var i0 = indices[pos + 0];
                    var i1 = indices[pos + 1];
                    var i2 = indices[pos + 2];
                    var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
                    var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
                    var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
                    var triangle = new DecimationTriangle([v0, v1, v2]);
                    triangle.originalOffset = pos;
                    _this.triangles.push(triangle);
                };
                BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
                    _this.init(callback);
                });
            });
        };
        QuadraticErrorSimplification.prototype.init = function (callback) {
            var _this = this;
            var triangleInit1 = function (i) {
                var t = _this.triangles[i];
                t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
                for (var j = 0; j < 3; j++) {
                    t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
                }
            };
            BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
                var triangleInit2 = function (i) {
                    var t = _this.triangles[i];
                    for (var j = 0; j < 3; ++j) {
                        t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
                    }
                    t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
                };
                BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
                    _this.initialized = true;
                    callback();
                });
            });
        };
        QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
            var newTriangles = [];
            var i;
            for (i = 0; i < this.vertices.length; ++i) {
                this.vertices[i].triangleCount = 0;
            }
            var t;
            var j;
            for (i = 0; i < this.triangles.length; ++i) {
                if (!this.triangles[i].deleted) {
                    t = this.triangles[i];
                    for (j = 0; j < 3; ++j) {
                        t.vertices[j].triangleCount = 1;
                    }
                    newTriangles.push(t);
                }
            }
            var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
            var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
            var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
            var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
            var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            var vertexCount = 0;
            for (i = 0; i < this.vertices.length; ++i) {
                var vertex = this.vertices[i];
                vertex.id = vertexCount;
                if (vertex.triangleCount) {
                    vertex.originalOffsets.forEach(function (originalOffset) {
                        newPositionData.push(vertex.position.x);
                        newPositionData.push(vertex.position.y);
                        newPositionData.push(vertex.position.z);
                        newNormalData.push(normalData[originalOffset * 3]);
                        newNormalData.push(normalData[(originalOffset * 3) + 1]);
                        newNormalData.push(normalData[(originalOffset * 3) + 2]);
                        if (uvs && uvs.length) {
                            newUVsData.push(uvs[(originalOffset * 2)]);
                            newUVsData.push(uvs[(originalOffset * 2) + 1]);
                        }
                        else if (colorsData && colorsData.length) {
                            newColorsData.push(colorsData[(originalOffset * 4)]);
                            newColorsData.push(colorsData[(originalOffset * 4) + 1]);
                            newColorsData.push(colorsData[(originalOffset * 4) + 2]);
                            newColorsData.push(colorsData[(originalOffset * 4) + 3]);
                        }
                        ++vertexCount;
                    });
                }
            }
            var startingIndex = this._reconstructedMesh.getTotalIndices();
            var startingVertex = this._reconstructedMesh.getTotalVertices();
            var submeshesArray = this._reconstructedMesh.subMeshes;
            this._reconstructedMesh.subMeshes = [];
            var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
            var originalIndices = this._mesh.getIndices();
            for (i = 0; i < newTriangles.length; ++i) {
                t = newTriangles[i]; //now get the new referencing point for each vertex
                [0, 1, 2].forEach(function (idx) {
                    var id = originalIndices[t.originalOffset + idx];
                    var offset = t.vertices[idx].originalOffsets.indexOf(id);
                    if (offset < 0)
                        offset = 0;
                    newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
                });
            }
            //overwriting the old vertex buffers and indices.
            this._reconstructedMesh.setIndices(newIndicesArray);
            this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
            this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
            if (newUVsData.length > 0)
                this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
            if (newColorsData.length > 0)
                this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
            //create submesh
            var originalSubmesh = this._mesh.subMeshes[submeshIndex];
            if (submeshIndex > 0) {
                this._reconstructedMesh.subMeshes = [];
                submeshesArray.forEach(function (submesh) {
                    new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
                });
                var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
            }
        };
        QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
            this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
            this._reconstructedMesh.material = this._mesh.material;
            this._reconstructedMesh.parent = this._mesh.parent;
            this._reconstructedMesh.isVisible = false;
            this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
        };
        QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
            for (var i = 0; i < vertex1.triangleCount; ++i) {
                var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
                if (t.deleted)
                    continue;
                var s = this.references[vertex1.triangleStart + i].vertexId;
                var v1 = t.vertices[(s + 1) % 3];
                var v2 = t.vertices[(s + 2) % 3];
                if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
                    deletedArray[i] = true;
                    delTr.push(t);
                    continue;
                }
                var d1 = v1.position.subtract(point);
                d1 = d1.normalize();
                var d2 = v2.position.subtract(point);
                d2 = d2.normalize();
                if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
                    return true;
                var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
                deletedArray[i] = false;
                if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
                    return true;
            }
            return false;
        };
        QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
            var newDeleted = deletedTriangles;
            for (var i = 0; i < vertex.triangleCount; ++i) {
                var ref = this.references[vertex.triangleStart + i];
                var t = this.triangles[ref.triangleId];
                if (t.deleted)
                    continue;
                if (deletedArray[i] && t.deletePending) {
                    t.deleted = true;
                    newDeleted++;
                    continue;
                }
                t.vertices[ref.vertexId] = origVertex;
                t.isDirty = true;
                t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
                t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
                t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
                t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
                this.references.push(ref);
            }
            return newDeleted;
        };
        QuadraticErrorSimplification.prototype.identifyBorder = function () {
            for (var i = 0; i < this.vertices.length; ++i) {
                var vCount = [];
                var vId = [];
                var v = this.vertices[i];
                var j;
                for (j = 0; j < v.triangleCount; ++j) {
                    var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
                    for (var ii = 0; ii < 3; ii++) {
                        var ofs = 0;
                        var vv = triangle.vertices[ii];
                        while (ofs < vCount.length) {
                            if (vId[ofs] === vv.id)
                                break;
                            ++ofs;
                        }
                        if (ofs === vCount.length) {
                            vCount.push(1);
                            vId.push(vv.id);
                        }
                        else {
                            vCount[ofs]++;
                        }
                    }
                }
                for (j = 0; j < vCount.length; ++j) {
                    if (vCount[j] === 1) {
                        this.vertices[vId[j]].isBorder = true;
                    }
                    else {
                        this.vertices[vId[j]].isBorder = false;
                    }
                }
            }
        };
        QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
            if (identifyBorders === void 0) { identifyBorders = false; }
            var i;
            if (!identifyBorders) {
                var newTrianglesVector = [];
                for (i = 0; i < this.triangles.length; ++i) {
                    if (!this.triangles[i].deleted) {
                        newTrianglesVector.push(this.triangles[i]);
                    }
                }
                this.triangles = newTrianglesVector;
            }
            for (i = 0; i < this.vertices.length; ++i) {
                this.vertices[i].triangleCount = 0;
                this.vertices[i].triangleStart = 0;
            }
            var t;
            var j;
            var v;
            for (i = 0; i < this.triangles.length; ++i) {
                t = this.triangles[i];
                for (j = 0; j < 3; ++j) {
                    v = t.vertices[j];
                    v.triangleCount++;
                }
            }
            var tStart = 0;
            for (i = 0; i < this.vertices.length; ++i) {
                this.vertices[i].triangleStart = tStart;
                tStart += this.vertices[i].triangleCount;
                this.vertices[i].triangleCount = 0;
            }
            var newReferences = new Array(this.triangles.length * 3);
            for (i = 0; i < this.triangles.length; ++i) {
                t = this.triangles[i];
                for (j = 0; j < 3; ++j) {
                    v = t.vertices[j];
                    newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
                    v.triangleCount++;
                }
            }
            this.references = newReferences;
            if (identifyBorders) {
                this.identifyBorder();
            }
        };
        QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
            var x = point.x;
            var y = point.y;
            var z = point.z;
            return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
                + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
        };
        QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
            var q = vertex1.q.add(vertex2.q);
            var border = vertex1.isBorder && vertex2.isBorder;
            var error = 0;
            var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
            if (qDet !== 0 && !border) {
                if (!pointResult) {
                    pointResult = BABYLON.Vector3.Zero();
                }
                pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
                pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
                pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
                error = this.vertexError(q, pointResult);
            }
            else {
                var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
                //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
                var error1 = this.vertexError(q, vertex1.position);
                var error2 = this.vertexError(q, vertex2.position);
                var error3 = this.vertexError(q, p3);
                error = Math.min(error1, error2, error3);
                if (error === error1) {
                    if (pointResult) {
                        pointResult.copyFrom(vertex1.position);
                    }
                }
                else if (error === error2) {
                    if (pointResult) {
                        pointResult.copyFrom(vertex2.position);
                    }
                }
                else {
                    if (pointResult) {
                        pointResult.copyFrom(p3);
                    }
                }
            }
            return error;
        };
        return QuadraticErrorSimplification;
    }());
    BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.meshSimplification.js.map
 
var BABYLON;
(function (BABYLON) {
    var serializedGeometries = [];
    var serializeGeometry = function (geometry, serializationGeometries) {
        if (serializedGeometries[geometry.id]) {
            return;
        }
        if (geometry.doNotSerialize) {
            return;
        }
        if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
            serializationGeometries.boxes.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
            serializationGeometries.spheres.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
            serializationGeometries.cylinders.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
            serializationGeometries.toruses.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
            serializationGeometries.grounds.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
            serializationGeometries.planes.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
            serializationGeometries.torusKnots.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
            throw new Error("Unknown primitive type");
        }
        else {
            serializationGeometries.vertexData.push(geometry.serializeVerticeData());
        }
        serializedGeometries[geometry.id] = true;
    };
    var serializeMesh = function (mesh, serializationScene) {
        var serializationObject = {};
        serializationObject.name = mesh.name;
        serializationObject.id = mesh.id;
        if (BABYLON.Tags.HasTags(mesh)) {
            serializationObject.tags = BABYLON.Tags.GetTags(mesh);
        }
        serializationObject.position = mesh.position.asArray();
        if (mesh.rotationQuaternion) {
            serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
        }
        else if (mesh.rotation) {
            serializationObject.rotation = mesh.rotation.asArray();
        }
        serializationObject.scaling = mesh.scaling.asArray();
        serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
        serializationObject.isEnabled = mesh.isEnabled();
        serializationObject.isVisible = mesh.isVisible;
        serializationObject.infiniteDistance = mesh.infiniteDistance;
        serializationObject.pickable = mesh.isPickable;
        serializationObject.receiveShadows = mesh.receiveShadows;
        serializationObject.billboardMode = mesh.billboardMode;
        serializationObject.visibility = mesh.visibility;
        serializationObject.checkCollisions = mesh.checkCollisions;
        serializationObject.isBlocker = mesh.isBlocker;
        // Parent
        if (mesh.parent) {
            serializationObject.parentId = mesh.parent.id;
        }
        // Geometry
        var geometry = mesh._geometry;
        if (geometry) {
            var geometryId = geometry.id;
            serializationObject.geometryId = geometryId;
            if (!mesh.getScene().getGeometryByID(geometryId)) {
                // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
                serializeGeometry(geometry, serializationScene.geometries);
            }
            // SubMeshes
            serializationObject.subMeshes = [];
            for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
                var subMesh = mesh.subMeshes[subIndex];
                serializationObject.subMeshes.push({
                    materialIndex: subMesh.materialIndex,
                    verticesStart: subMesh.verticesStart,
                    verticesCount: subMesh.verticesCount,
                    indexStart: subMesh.indexStart,
                    indexCount: subMesh.indexCount
                });
            }
        }
        // Material
        if (mesh.material) {
            serializationObject.materialId = mesh.material.id;
        }
        else {
            mesh.material = null;
        }
        // Skeleton
        if (mesh.skeleton) {
            serializationObject.skeletonId = mesh.skeleton.id;
        }
        // Physics
        //TODO implement correct serialization for physics impostors.
        if (mesh.getPhysicsImpostor()) {
            serializationObject.physicsMass = mesh.getPhysicsMass();
            serializationObject.physicsFriction = mesh.getPhysicsFriction();
            serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
            serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
        }
        // Metadata
        if (mesh.metadata) {
            serializationObject.metadata = mesh.metadata;
        }
        // Instances
        serializationObject.instances = [];
        for (var index = 0; index < mesh.instances.length; index++) {
            var instance = mesh.instances[index];
            var serializationInstance = {
                name: instance.name,
                position: instance.position.asArray(),
                scaling: instance.scaling.asArray()
            };
            if (instance.rotationQuaternion) {
                serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
            }
            else if (instance.rotation) {
                serializationInstance.rotation = instance.rotation.asArray();
            }
            serializationObject.instances.push(serializationInstance);
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
            serializationInstance.ranges = instance.serializeAnimationRanges();
        }
        // Animations
        BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
        serializationObject.ranges = mesh.serializeAnimationRanges();
        // Layer mask
        serializationObject.layerMask = mesh.layerMask;
        // Alpha
        serializationObject.alphaIndex = mesh.alphaIndex;
        serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
        // Overlay
        serializationObject.overlayAlpha = mesh.overlayAlpha;
        serializationObject.overlayColor = mesh.overlayColor.asArray();
        serializationObject.renderOverlay = mesh.renderOverlay;
        // Fog
        serializationObject.applyFog = mesh.applyFog;
        // Action Manager
        if (mesh.actionManager) {
            serializationObject.actions = mesh.actionManager.serialize(mesh.name);
        }
        return serializationObject;
    };
    var finalizeSingleMesh = function (mesh, serializationObject) {
        //only works if the mesh is already loaded
        if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
            //serialize material
            if (mesh.material) {
                if (mesh.material instanceof BABYLON.StandardMaterial) {
                    serializationObject.materials = serializationObject.materials || [];
                    if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
                        serializationObject.materials.push(mesh.material.serialize());
                    }
                }
                else if (mesh.material instanceof BABYLON.MultiMaterial) {
                    serializationObject.multiMaterials = serializationObject.multiMaterials || [];
                    if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
                        serializationObject.multiMaterials.push(mesh.material.serialize());
                    }
                }
            }
            //serialize geometry
            var geometry = mesh._geometry;
            if (geometry) {
                if (!serializationObject.geometries) {
                    serializationObject.geometries = {};
                    serializationObject.geometries.boxes = [];
                    serializationObject.geometries.spheres = [];
                    serializationObject.geometries.cylinders = [];
                    serializationObject.geometries.toruses = [];
                    serializationObject.geometries.grounds = [];
                    serializationObject.geometries.planes = [];
                    serializationObject.geometries.torusKnots = [];
                    serializationObject.geometries.vertexData = [];
                }
                serializeGeometry(geometry, serializationObject.geometries);
            }
            // Skeletons
            if (mesh.skeleton) {
                serializationObject.skeletons = serializationObject.skeletons || [];
                serializationObject.skeletons.push(mesh.skeleton.serialize());
            }
            //serialize the actual mesh
            serializationObject.meshes = serializationObject.meshes || [];
            serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
        }
    };
    var SceneSerializer = (function () {
        function SceneSerializer() {
        }
        SceneSerializer.ClearCache = function () {
            serializedGeometries = [];
        };
        SceneSerializer.Serialize = function (scene) {
            var serializationObject = {};
            // Scene
            serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
            serializationObject.autoClear = scene.autoClear;
            serializationObject.clearColor = scene.clearColor.asArray();
            serializationObject.ambientColor = scene.ambientColor.asArray();
            serializationObject.gravity = scene.gravity.asArray();
            serializationObject.collisionsEnabled = scene.collisionsEnabled;
            serializationObject.workerCollisions = scene.workerCollisions;
            // Fog
            if (scene.fogMode && scene.fogMode !== 0) {
                serializationObject.fogMode = scene.fogMode;
                serializationObject.fogColor = scene.fogColor.asArray();
                serializationObject.fogStart = scene.fogStart;
                serializationObject.fogEnd = scene.fogEnd;
                serializationObject.fogDensity = scene.fogDensity;
            }
            //Physics
            if (scene.isPhysicsEnabled()) {
                serializationObject.physicsEnabled = true;
                serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
                serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
            }
            // Metadata
            if (scene.metadata) {
                serializationObject.metadata = scene.metadata;
            }
            // Lights
            serializationObject.lights = [];
            var index;
            var light;
            for (index = 0; index < scene.lights.length; index++) {
                light = scene.lights[index];
                if (!light.doNotSerialize) {
                    serializationObject.lights.push(light.serialize());
                }
            }
            // Cameras
            serializationObject.cameras = [];
            for (index = 0; index < scene.cameras.length; index++) {
                var camera = scene.cameras[index];
                if (!camera.doNotSerialize) {
                    serializationObject.cameras.push(camera.serialize());
                }
            }
            if (scene.activeCamera) {
                serializationObject.activeCameraID = scene.activeCamera.id;
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
            // Materials
            serializationObject.materials = [];
            serializationObject.multiMaterials = [];
            var material;
            for (index = 0; index < scene.materials.length; index++) {
                material = scene.materials[index];
                if (!material.doNotSerialize) {
                    serializationObject.materials.push(material.serialize());
                }
            }
            // MultiMaterials
            serializationObject.multiMaterials = [];
            for (index = 0; index < scene.multiMaterials.length; index++) {
                var multiMaterial = scene.multiMaterials[index];
                serializationObject.multiMaterials.push(multiMaterial.serialize());
            }
            // Skeletons
            serializationObject.skeletons = [];
            for (index = 0; index < scene.skeletons.length; index++) {
                serializationObject.skeletons.push(scene.skeletons[index].serialize());
            }
            // Geometries
            serializationObject.geometries = {};
            serializationObject.geometries.boxes = [];
            serializationObject.geometries.spheres = [];
            serializationObject.geometries.cylinders = [];
            serializationObject.geometries.toruses = [];
            serializationObject.geometries.grounds = [];
            serializationObject.geometries.planes = [];
            serializationObject.geometries.torusKnots = [];
            serializationObject.geometries.vertexData = [];
            serializedGeometries = [];
            var geometries = scene.getGeometries();
            for (index = 0; index < geometries.length; index++) {
                var geometry = geometries[index];
                if (geometry.isReady()) {
                    serializeGeometry(geometry, serializationObject.geometries);
                }
            }
            // Meshes
            serializationObject.meshes = [];
            for (index = 0; index < scene.meshes.length; index++) {
                var abstractMesh = scene.meshes[index];
                if (abstractMesh instanceof BABYLON.Mesh) {
                    var mesh = abstractMesh;
                    if (!mesh.doNotSerialize) {
                        if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
                            serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
                        }
                    }
                }
            }
            // Particles Systems
            serializationObject.particleSystems = [];
            for (index = 0; index < scene.particleSystems.length; index++) {
                serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
            }
            // Lens flares
            serializationObject.lensFlareSystems = [];
            for (index = 0; index < scene.lensFlareSystems.length; index++) {
                serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
            }
            // Shadows
            serializationObject.shadowGenerators = [];
            for (index = 0; index < scene.lights.length; index++) {
                light = scene.lights[index];
                var shadowGenerator = light.getShadowGenerator();
                // Only support serialization for official generator so far.
                if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
                    serializationObject.shadowGenerators.push(shadowGenerator.serialize());
                }
            }
            // Action Manager
            if (scene.actionManager) {
                serializationObject.actions = scene.actionManager.serialize("scene");
            }
            // Audio
            serializationObject.sounds = [];
            for (index = 0; index < scene.soundTracks.length; index++) {
                var soundtrack = scene.soundTracks[index];
                for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
                    serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
                }
            }
            return serializationObject;
        };
        SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
            if (withParents === void 0) { withParents = false; }
            if (withChildren === void 0) { withChildren = false; }
            var serializationObject = {};
            toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
            if (withParents || withChildren) {
                //deliberate for loop! not for each, appended should be processed as well.
                for (var i = 0; i < toSerialize.length; ++i) {
                    if (withChildren) {
                        toSerialize[i].getDescendants().forEach(function (node) {
                            if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
                                toSerialize.push(node);
                            }
                        });
                    }
                    //make sure the array doesn't contain the object already
                    if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
                        toSerialize.push(toSerialize[i].parent);
                    }
                }
            }
            toSerialize.forEach(function (mesh) {
                finalizeSingleMesh(mesh, serializationObject);
            });
            return serializationObject;
        };
        return SceneSerializer;
    }());
    BABYLON.SceneSerializer = SceneSerializer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.sceneSerializer.js.map
 
// All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
// Huge respect for a such great lib. 
// Earcut license:
// Copyright (c) 2016, Mapbox
// 
// Permission to use, copy, modify, and/or distribute this software for any purpose
// with or without fee is hereby granted, provided that the above copyright notice
// and this permission notice appear in all copies.
// 
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
// THIS SOFTWARE.
var Earcut;
(function (Earcut) {
    /**
     * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
     * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
     * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
     * @param dim is the number of coordinates per vertice in the input array (2 by default).
     */
    function earcut(data, holeIndices, dim) {
        dim = dim || 2;
        var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
        if (!outerNode)
            return triangles;
        var minX, minY, maxX, maxY, x, y, size;
        if (hasHoles)
            outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
        // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
        if (data.length > 80 * dim) {
            minX = maxX = data[0];
            minY = maxY = data[1];
            for (var i = dim; i < outerLen; i += dim) {
                x = data[i];
                y = data[i + 1];
                if (x < minX)
                    minX = x;
                if (y < minY)
                    minY = y;
                if (x > maxX)
                    maxX = x;
                if (y > maxY)
                    maxY = y;
            }
            // minX, minY and size are later used to transform coords into integers for z-order calculation
            size = Math.max(maxX - minX, maxY - minY);
        }
        earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
        return triangles;
    }
    Earcut.earcut = earcut;
    // create a circular doubly linked list from polygon points in the specified winding order
    function linkedList(data, start, end, dim, clockwise) {
        var i, last;
        if (clockwise === (signedArea(data, start, end, dim) > 0)) {
            for (i = start; i < end; i += dim)
                last = insertNode(i, data[i], data[i + 1], last);
        }
        else {
            for (i = end - dim; i >= start; i -= dim)
                last = insertNode(i, data[i], data[i + 1], last);
        }
        if (last && equals(last, last.next)) {
            removeNode(last);
            last = last.next;
        }
        return last;
    }
    // eliminate colinear or duplicate points
    function filterPoints(start, end) {
        if (!start)
            return start;
        if (!end)
            end = start;
        var p = start, again;
        do {
            again = false;
            if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
                removeNode(p);
                p = end = p.prev;
                if (p === p.next)
                    return null;
                again = true;
            }
            else {
                p = p.next;
            }
        } while (again || p !== end);
        return end;
    }
    // main ear slicing loop which triangulates a polygon (given as a linked list)
    function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
        if (!ear)
            return;
        // interlink polygon nodes in z-order
        if (!pass && size)
            indexCurve(ear, minX, minY, size);
        var stop = ear, prev, next;
        // iterate through ears, slicing them one by one
        while (ear.prev !== ear.next) {
            prev = ear.prev;
            next = ear.next;
            if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
                // cut off the triangle
                triangles.push(prev.i / dim);
                triangles.push(ear.i / dim);
                triangles.push(next.i / dim);
                removeNode(ear);
                // skipping the next vertice leads to less sliver triangles
                ear = next.next;
                stop = next.next;
                continue;
            }
            ear = next;
            // if we looped through the whole remaining polygon and can't find any more ears
            if (ear === stop) {
                // try filtering points and slicing again
                if (!pass) {
                    earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
                }
                else if (pass === 1) {
                    ear = cureLocalIntersections(ear, triangles, dim);
                    earcutLinked(ear, triangles, dim, minX, minY, size, 2);
                }
                else if (pass === 2) {
                    splitEarcut(ear, triangles, dim, minX, minY, size);
                }
                break;
            }
        }
    }
    // check whether a polygon node forms a valid ear with adjacent nodes
    function isEar(ear) {
        var a = ear.prev, b = ear, c = ear.next;
        if (area(a, b, c) >= 0)
            return false; // reflex, can't be an ear
        // now make sure we don't have other points inside the potential ear
        var p = ear.next.next;
        while (p !== ear.prev) {
            if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
                area(p.prev, p, p.next) >= 0)
                return false;
            p = p.next;
        }
        return true;
    }
    function isEarHashed(ear, minX, minY, size) {
        var a = ear.prev, b = ear, c = ear.next;
        if (area(a, b, c) >= 0)
            return false; // reflex, can't be an ear
        // triangle bbox; min & max are calculated like this for speed
        var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
        // z-order range for the current triangle bbox;
        var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
        // first look for points inside the triangle in increasing z-order
        var p = ear.nextZ;
        while (p && p.z <= maxZ) {
            if (p !== ear.prev &&
                p !== ear.next &&
                pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
                area(p.prev, p, p.next) >= 0)
                return false;
            p = p.nextZ;
        }
        // then look for points in decreasing z-order
        p = ear.prevZ;
        while (p && p.z >= minZ) {
            if (p !== ear.prev &&
                p !== ear.next &&
                pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
                area(p.prev, p, p.next) >= 0)
                return false;
            p = p.prevZ;
        }
        return true;
    }
    // go through all polygon nodes and cure small local self-intersections
    function cureLocalIntersections(start, triangles, dim) {
        var p = start;
        do {
            var a = p.prev, b = p.next.next;
            if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
                triangles.push(a.i / dim);
                triangles.push(p.i / dim);
                triangles.push(b.i / dim);
                // remove two nodes involved
                removeNode(p);
                removeNode(p.next);
                p = start = b;
            }
            p = p.next;
        } while (p !== start);
        return p;
    }
    // try splitting polygon into two and triangulate them independently
    function splitEarcut(start, triangles, dim, minX, minY, size) {
        // look for a valid diagonal that divides the polygon into two
        var a = start;
        do {
            var b = a.next.next;
            while (b !== a.prev) {
                if (a.i !== b.i && isValidDiagonal(a, b)) {
                    // split the polygon in two by the diagonal
                    var c = splitPolygon(a, b);
                    // filter colinear points around the cuts
                    a = filterPoints(a, a.next);
                    c = filterPoints(c, c.next);
                    // run earcut on each half
                    earcutLinked(a, triangles, dim, minX, minY, size, undefined);
                    earcutLinked(c, triangles, dim, minX, minY, size, undefined);
                    return;
                }
                b = b.next;
            }
            a = a.next;
        } while (a !== start);
    }
    // link every hole into the outer loop, producing a single-ring polygon without holes
    function eliminateHoles(data, holeIndices, outerNode, dim) {
        var queue = [], i, len, start, end, list;
        for (i = 0, len = holeIndices.length; i < len; i++) {
            start = holeIndices[i] * dim;
            end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
            list = linkedList(data, start, end, dim, false);
            if (list === list.next)
                list.steiner = true;
            queue.push(getLeftmost(list));
        }
        queue.sort(compareX);
        // process holes from left to right
        for (i = 0; i < queue.length; i++) {
            eliminateHole(queue[i], outerNode);
            outerNode = filterPoints(outerNode, outerNode.next);
        }
        return outerNode;
    }
    function compareX(a, b) {
        return a.x - b.x;
    }
    // find a bridge between vertices that connects hole with an outer ring and and link it
    function eliminateHole(hole, outerNode) {
        outerNode = findHoleBridge(hole, outerNode);
        if (outerNode) {
            var b = splitPolygon(outerNode, hole);
            filterPoints(b, b.next);
        }
    }
    // David Eberly's algorithm for finding a bridge between hole and outer polygon
    function findHoleBridge(hole, outerNode) {
        var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
        // find a segment intersected by a ray from the hole's leftmost point to the left;
        // segment's endpoint with lesser x will be potential connection point
        do {
            if (hy <= p.y && hy >= p.next.y) {
                var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
                if (x <= hx && x > qx) {
                    qx = x;
                    if (x === hx) {
                        if (hy === p.y)
                            return p;
                        if (hy === p.next.y)
                            return p.next;
                    }
                    m = p.x < p.next.x ? p : p.next;
                }
            }
            p = p.next;
        } while (p !== outerNode);
        if (!m)
            return null;
        if (hx === qx)
            return m.prev; // hole touches outer segment; pick lower endpoint
        // look for points inside the triangle of hole point, segment intersection and endpoint;
        // if there are no points found, we have a valid connection;
        // otherwise choose the point of the minimum angle with the ray as connection point
        var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
        p = m.next;
        while (p !== stop) {
            if (hx >= p.x &&
                p.x >= mx &&
                pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
                tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
                if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
                    m = p;
                    tanMin = tan;
                }
            }
            p = p.next;
        }
        return m;
    }
    // interlink polygon nodes in z-order
    function indexCurve(start, minX, minY, size) {
        var p = start;
        do {
            if (p.z === null)
                p.z = zOrder(p.x, p.y, minX, minY, size);
            p.prevZ = p.prev;
            p.nextZ = p.next;
            p = p.next;
        } while (p !== start);
        p.prevZ.nextZ = null;
        p.prevZ = null;
        sortLinked(p);
    }
    // Simon Tatham's linked list merge sort algorithm
    // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
    function sortLinked(list) {
        var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
        do {
            p = list;
            list = null;
            tail = null;
            numMerges = 0;
            while (p) {
                numMerges++;
                q = p;
                pSize = 0;
                for (i = 0; i < inSize; i++) {
                    pSize++;
                    q = q.nextZ;
                    if (!q)
                        break;
                }
                qSize = inSize;
                while (pSize > 0 || (qSize > 0 && q)) {
                    if (pSize === 0) {
                        e = q;
                        q = q.nextZ;
                        qSize--;
                    }
                    else if (qSize === 0 || !q) {
                        e = p;
                        p = p.nextZ;
                        pSize--;
                    }
                    else if (p.z <= q.z) {
                        e = p;
                        p = p.nextZ;
                        pSize--;
                    }
                    else {
                        e = q;
                        q = q.nextZ;
                        qSize--;
                    }
                    if (tail)
                        tail.nextZ = e;
                    else
                        list = e;
                    e.prevZ = tail;
                    tail = e;
                }
                p = q;
            }
            tail.nextZ = null;
            inSize *= 2;
        } while (numMerges > 1);
        return list;
    }
    // z-order of a point given coords and size of the data bounding box
    function zOrder(x, y, minX, minY, size) {
        // coords are transformed into non-negative 15-bit integer range
        x = 32767 * (x - minX) / size;
        y = 32767 * (y - minY) / size;
        x = (x | (x << 8)) & 0x00FF00FF;
        x = (x | (x << 4)) & 0x0F0F0F0F;
        x = (x | (x << 2)) & 0x33333333;
        x = (x | (x << 1)) & 0x55555555;
        y = (y | (y << 8)) & 0x00FF00FF;
        y = (y | (y << 4)) & 0x0F0F0F0F;
        y = (y | (y << 2)) & 0x33333333;
        y = (y | (y << 1)) & 0x55555555;
        return x | (y << 1);
    }
    // find the leftmost node of a polygon ring
    function getLeftmost(start) {
        var p = start, leftmost = start;
        do {
            if (p.x < leftmost.x)
                leftmost = p;
            p = p.next;
        } while (p !== start);
        return leftmost;
    }
    // check if a point lies within a convex triangle
    function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
        return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
            (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
            (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
    }
    // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
    function isValidDiagonal(a, b) {
        return a.next.i !== b.i &&
            a.prev.i !== b.i &&
            !intersectsPolygon(a, b) &&
            locallyInside(a, b) &&
            locallyInside(b, a) &&
            middleInside(a, b);
    }
    // signed area of a triangle
    function area(p, q, r) {
        return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
    }
    // check if two points are equal
    function equals(p1, p2) {
        return p1.x === p2.x && p1.y === p2.y;
    }
    // check if two segments intersect
    function intersects(p1, q1, p2, q2) {
        if ((equals(p1, q1) && equals(p2, q2)) ||
            (equals(p1, q2) && equals(p2, q1)))
            return true;
        return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
            area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
    }
    // check if a polygon diagonal intersects any polygon segments
    function intersectsPolygon(a, b) {
        var p = a;
        do {
            if (p.i !== a.i &&
                p.next.i !== a.i &&
                p.i !== b.i &&
                p.next.i !== b.i &&
                intersects(p, p.next, a, b))
                return true;
            p = p.next;
        } while (p !== a);
        return false;
    }
    // check if a polygon diagonal is locally inside the polygon
    function locallyInside(a, b) {
        return area(a.prev, a, a.next) < 0
            ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
            : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
    }
    // check if the middle point of a polygon diagonal is inside the polygon
    function middleInside(a, b) {
        var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
        do {
            if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
                inside = !inside;
            p = p.next;
        } while (p !== a);
        return inside;
    }
    // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
    // if one belongs to the outer ring and another to a hole, it merges it into a single ring
    function splitPolygon(a, b) {
        var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
        a.next = b;
        b.prev = a;
        a2.next = an;
        an.prev = a2;
        b2.next = a2;
        a2.prev = b2;
        bp.next = b2;
        b2.prev = bp;
        return b2;
    }
    // create a node and optionally link it with previous one (in a circular doubly linked list)
    function insertNode(i, x, y, last) {
        var p = new Node(i, x, y);
        if (!last) {
            p.prev = p;
            p.next = p;
        }
        else {
            p.next = last.next;
            p.prev = last;
            last.next.prev = p;
            last.next = p;
        }
        return p;
    }
    function removeNode(p) {
        p.next.prev = p.prev;
        p.prev.next = p.next;
        if (p.prevZ)
            p.prevZ.nextZ = p.nextZ;
        if (p.nextZ)
            p.nextZ.prevZ = p.prevZ;
    }
    function Node(i, x, y) {
        // vertice index in coordinates array
        this.i = i;
        // vertex coordinates
        this.x = x;
        this.y = y;
        // previous and next vertice nodes in a polygon ring
        this.prev = null;
        this.next = null;
        // z-order curve value
        this.z = null;
        // previous and next nodes in z-order
        this.prevZ = null;
        this.nextZ = null;
        // indicates whether this is a steiner point
        this.steiner = false;
    }
    /**
     * return a percentage difference between the polygon area and its triangulation area;
     * used to verify correctness of triangulation
     */
    function deviation(data, holeIndices, dim, triangles) {
        var hasHoles = holeIndices && holeIndices.length;
        var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
        var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
        if (hasHoles) {
            for (var i = 0, len = holeIndices.length; i < len; i++) {
                var start = holeIndices[i] * dim;
                var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
                polygonArea -= Math.abs(signedArea(data, start, end, dim));
            }
        }
        var trianglesArea = 0;
        for (i = 0; i < triangles.length; i += 3) {
            var a = triangles[i] * dim;
            var b = triangles[i + 1] * dim;
            var c = triangles[i + 2] * dim;
            trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
                (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
        }
        return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
    }
    Earcut.deviation = deviation;
    ;
    function signedArea(data, start, end, dim) {
        var sum = 0;
        for (var i = start, j = end - dim; i < end; i += dim) {
            sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
            j = i;
        }
        return sum;
    }
    /**
     *  turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
     */
    function flatten(data) {
        var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
        for (var i = 0; i < data.length; i++) {
            for (var j = 0; j < data[i].length; j++) {
                for (var d = 0; d < dim; d++)
                    result.vertices.push(data[i][j][d]);
            }
            if (i > 0) {
                holeIndex += data[i - 1].length;
                result.holes.push(holeIndex);
            }
        }
        return result;
    }
    Earcut.flatten = flatten;
    ;
})(Earcut || (Earcut = {}));
 
//# sourceMappingURL=babylon.earcut.js.map
 
var BABYLON;
(function (BABYLON) {
    // Unique ID when we import meshes from Babylon to CSG
    var currentCSGMeshId = 0;
    // # class Vertex
    // Represents a vertex of a polygon. Use your own vertex class instead of this
    // one to provide additional features like texture coordinates and vertex
    // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
    // `flip()`, and `interpolate()` methods that behave analogous to the ones
    // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
    // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
    // is not used anywhere else. 
    // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
    var Vertex = (function () {
        function Vertex(pos, normal, uv) {
            this.pos = pos;
            this.normal = normal;
            this.uv = uv;
        }
        Vertex.prototype.clone = function () {
            return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
        };
        // Invert all orientation-specific data (e.g. vertex normal). Called when the
        // orientation of a polygon is flipped.
        Vertex.prototype.flip = function () {
            this.normal = this.normal.scale(-1);
        };
        // Create a new vertex between this vertex and `other` by linearly
        // interpolating all properties using a parameter of `t`. Subclasses should
        // override this to interpolate additional properties.
        Vertex.prototype.interpolate = function (other, t) {
            return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
        };
        return Vertex;
    }());
    // # class Plane
    // Represents a plane in 3D space.
    var Plane = (function () {
        function Plane(normal, w) {
            this.normal = normal;
            this.w = w;
        }
        Plane.FromPoints = function (a, b, c) {
            var v0 = c.subtract(a);
            var v1 = b.subtract(a);
            if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
                return null;
            }
            var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
            return new Plane(n, BABYLON.Vector3.Dot(n, a));
        };
        Plane.prototype.clone = function () {
            return new Plane(this.normal.clone(), this.w);
        };
        Plane.prototype.flip = function () {
            this.normal.scaleInPlace(-1);
            this.w = -this.w;
        };
        // Split `polygon` by this plane if needed, then put the polygon or polygon
        // fragments in the appropriate lists. Coplanar polygons go into either
        // `coplanarFront` or `coplanarBack` depending on their orientation with
        // respect to this plane. Polygons in front or in back of this plane go into
        // either `front` or `back`.
        Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
            var COPLANAR = 0;
            var FRONT = 1;
            var BACK = 2;
            var SPANNING = 3;
            // Classify each point as well as the entire polygon into one of the above
            // four classes.
            var polygonType = 0;
            var types = [];
            var i;
            var t;
            for (i = 0; i < polygon.vertices.length; i++) {
                t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
                var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
                polygonType |= type;
                types.push(type);
            }
            // Put the polygon in the correct list, splitting it when necessary.
            switch (polygonType) {
                case COPLANAR:
                    (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
                    break;
                case FRONT:
                    front.push(polygon);
                    break;
                case BACK:
                    back.push(polygon);
                    break;
                case SPANNING:
                    var f = [], b = [];
                    for (i = 0; i < polygon.vertices.length; i++) {
                        var j = (i + 1) % polygon.vertices.length;
                        var ti = types[i], tj = types[j];
                        var vi = polygon.vertices[i], vj = polygon.vertices[j];
                        if (ti !== BACK)
                            f.push(vi);
                        if (ti !== FRONT)
                            b.push(ti !== BACK ? vi.clone() : vi);
                        if ((ti | tj) === SPANNING) {
                            t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
                            var v = vi.interpolate(vj, t);
                            f.push(v);
                            b.push(v.clone());
                        }
                    }
                    var poly;
                    if (f.length >= 3) {
                        poly = new Polygon(f, polygon.shared);
                        if (poly.plane)
                            front.push(poly);
                    }
                    if (b.length >= 3) {
                        poly = new Polygon(b, polygon.shared);
                        if (poly.plane)
                            back.push(poly);
                    }
                    break;
            }
        };
        // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
        // point is on the plane.
        Plane.EPSILON = 1e-5;
        return Plane;
    }());
    // # class Polygon
    // Represents a convex polygon. The vertices used to initialize a polygon must
    // be coplanar and form a convex loop.
    // 
    // Each convex polygon has a `shared` property, which is shared between all
    // polygons that are clones of each other or were split from the same polygon.
    // This can be used to define per-polygon properties (such as surface color).
    var Polygon = (function () {
        function Polygon(vertices, shared) {
            this.vertices = vertices;
            this.shared = shared;
            this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
        }
        Polygon.prototype.clone = function () {
            var vertices = this.vertices.map(function (v) { return v.clone(); });
            return new Polygon(vertices, this.shared);
        };
        Polygon.prototype.flip = function () {
            this.vertices.reverse().map(function (v) { v.flip(); });
            this.plane.flip();
        };
        return Polygon;
    }());
    // # class Node
    // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
    // by picking a polygon to split along. That polygon (and all other coplanar
    // polygons) are added directly to that node and the other polygons are added to
    // the front and/or back subtrees. This is not a leafy BSP tree since there is
    // no distinction between internal and leaf nodes.
    var Node = (function () {
        function Node(polygons) {
            this.plane = null;
            this.front = null;
            this.back = null;
            this.polygons = [];
            if (polygons) {
                this.build(polygons);
            }
        }
        Node.prototype.clone = function () {
            var node = new Node();
            node.plane = this.plane && this.plane.clone();
            node.front = this.front && this.front.clone();
            node.back = this.back && this.back.clone();
            node.polygons = this.polygons.map(function (p) { return p.clone(); });
            return node;
        };
        // Convert solid space to empty space and empty space to solid space.
        Node.prototype.invert = function () {
            for (var i = 0; i < this.polygons.length; i++) {
                this.polygons[i].flip();
            }
            if (this.plane) {
                this.plane.flip();
            }
            if (this.front) {
                this.front.invert();
            }
            if (this.back) {
                this.back.invert();
            }
            var temp = this.front;
            this.front = this.back;
            this.back = temp;
        };
        // Recursively remove all polygons in `polygons` that are inside this BSP
        // tree.
        Node.prototype.clipPolygons = function (polygons) {
            if (!this.plane)
                return polygons.slice();
            var front = [], back = [];
            for (var i = 0; i < polygons.length; i++) {
                this.plane.splitPolygon(polygons[i], front, back, front, back);
            }
            if (this.front) {
                front = this.front.clipPolygons(front);
            }
            if (this.back) {
                back = this.back.clipPolygons(back);
            }
            else {
                back = [];
            }
            return front.concat(back);
        };
        // Remove all polygons in this BSP tree that are inside the other BSP tree
        // `bsp`.
        Node.prototype.clipTo = function (bsp) {
            this.polygons = bsp.clipPolygons(this.polygons);
            if (this.front)
                this.front.clipTo(bsp);
            if (this.back)
                this.back.clipTo(bsp);
        };
        // Return a list of all polygons in this BSP tree.
        Node.prototype.allPolygons = function () {
            var polygons = this.polygons.slice();
            if (this.front)
                polygons = polygons.concat(this.front.allPolygons());
            if (this.back)
                polygons = polygons.concat(this.back.allPolygons());
            return polygons;
        };
        // Build a BSP tree out of `polygons`. When called on an existing tree, the
        // new polygons are filtered down to the bottom of the tree and become new
        // nodes there. Each set of polygons is partitioned using the first polygon
        // (no heuristic is used to pick a good split).
        Node.prototype.build = function (polygons) {
            if (!polygons.length)
                return;
            if (!this.plane)
                this.plane = polygons[0].plane.clone();
            var front = [], back = [];
            for (var i = 0; i < polygons.length; i++) {
                this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
            }
            if (front.length) {
                if (!this.front)
                    this.front = new Node();
                this.front.build(front);
            }
            if (back.length) {
                if (!this.back)
                    this.back = new Node();
                this.back.build(back);
            }
        };
        return Node;
    }());
    var CSG = (function () {
        function CSG() {
            this.polygons = new Array();
        }
        // Convert BABYLON.Mesh to BABYLON.CSG
        CSG.FromMesh = function (mesh) {
            var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
            var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
            if (mesh instanceof BABYLON.Mesh) {
                mesh.computeWorldMatrix(true);
                matrix = mesh.getWorldMatrix();
                meshPosition = mesh.position.clone();
                meshRotation = mesh.rotation.clone();
                if (mesh.rotationQuaternion) {
                    meshRotationQuaternion = mesh.rotationQuaternion.clone();
                }
                meshScaling = mesh.scaling.clone();
            }
            else {
                throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
            }
            var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var subMeshes = mesh.subMeshes;
            for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
                for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
                    vertices = [];
                    for (var j = 0; j < 3; j++) {
                        var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
                        uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
                        var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
                        position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
                        normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
                        vertex = new Vertex(position, normal, uv);
                        vertices.push(vertex);
                    }
                    polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
                    // To handle the case of degenerated triangle
                    // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
                    if (polygon.plane)
                        polygons.push(polygon);
                }
            }
            var csg = CSG.FromPolygons(polygons);
            csg.matrix = matrix;
            csg.position = meshPosition;
            csg.rotation = meshRotation;
            csg.scaling = meshScaling;
            csg.rotationQuaternion = meshRotationQuaternion;
            currentCSGMeshId++;
            return csg;
        };
        // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
        CSG.FromPolygons = function (polygons) {
            var csg = new CSG();
            csg.polygons = polygons;
            return csg;
        };
        CSG.prototype.clone = function () {
            var csg = new CSG();
            csg.polygons = this.polygons.map(function (p) { return p.clone(); });
            csg.copyTransformAttributes(this);
            return csg;
        };
        CSG.prototype.toPolygons = function () {
            return this.polygons;
        };
        CSG.prototype.union = function (csg) {
            var a = new Node(this.clone().polygons);
            var b = new Node(csg.clone().polygons);
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
        };
        CSG.prototype.unionInPlace = function (csg) {
            var a = new Node(this.polygons);
            var b = new Node(csg.polygons);
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            this.polygons = a.allPolygons();
        };
        CSG.prototype.subtract = function (csg) {
            var a = new Node(this.clone().polygons);
            var b = new Node(csg.clone().polygons);
            a.invert();
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            a.invert();
            return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
        };
        CSG.prototype.subtractInPlace = function (csg) {
            var a = new Node(this.polygons);
            var b = new Node(csg.polygons);
            a.invert();
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            a.invert();
            this.polygons = a.allPolygons();
        };
        CSG.prototype.intersect = function (csg) {
            var a = new Node(this.clone().polygons);
            var b = new Node(csg.clone().polygons);
            a.invert();
            b.clipTo(a);
            b.invert();
            a.clipTo(b);
            b.clipTo(a);
            a.build(b.allPolygons());
            a.invert();
            return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
        };
        CSG.prototype.intersectInPlace = function (csg) {
            var a = new Node(this.polygons);
            var b = new Node(csg.polygons);
            a.invert();
            b.clipTo(a);
            b.invert();
            a.clipTo(b);
            b.clipTo(a);
            a.build(b.allPolygons());
            a.invert();
            this.polygons = a.allPolygons();
        };
        // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
        // not modified.
        CSG.prototype.inverse = function () {
            var csg = this.clone();
            csg.inverseInPlace();
            return csg;
        };
        CSG.prototype.inverseInPlace = function () {
            this.polygons.map(function (p) { p.flip(); });
        };
        // This is used to keep meshes transformations so they can be restored
        // when we build back a Babylon Mesh
        // NB : All CSG operations are performed in world coordinates
        CSG.prototype.copyTransformAttributes = function (csg) {
            this.matrix = csg.matrix;
            this.position = csg.position;
            this.rotation = csg.rotation;
            this.scaling = csg.scaling;
            this.rotationQuaternion = csg.rotationQuaternion;
            return this;
        };
        // Build Raw mesh from CSG
        // Coordinates here are in world space
        CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
            var matrix = this.matrix.clone();
            matrix.invert();
            var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
            if (keepSubMeshes) {
                // Sort Polygons, since subMeshes are indices range
                polygons.sort(function (a, b) {
                    if (a.shared.meshId === b.shared.meshId) {
                        return a.shared.subMeshId - b.shared.subMeshId;
                    }
                    else {
                        return a.shared.meshId - b.shared.meshId;
                    }
                });
            }
            for (var i = 0, il = polygons.length; i < il; i++) {
                polygon = polygons[i];
                // Building SubMeshes
                if (!subMesh_dict[polygon.shared.meshId]) {
                    subMesh_dict[polygon.shared.meshId] = {};
                }
                if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
                    subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
                        indexStart: +Infinity,
                        indexEnd: -Infinity,
                        materialIndex: polygon.shared.materialIndex
                    };
                }
                subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
                for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
                    polygonIndices[0] = 0;
                    polygonIndices[1] = j - 1;
                    polygonIndices[2] = j;
                    for (var k = 0; k < 3; k++) {
                        vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
                        normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
                        uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
                        var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
                        var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
                        vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
                        // Check if 2 points can be merged
                        if (!(typeof vertex_idx !== 'undefined' &&
                            normals[vertex_idx * 3] === localNormal.x &&
                            normals[vertex_idx * 3 + 1] === localNormal.y &&
                            normals[vertex_idx * 3 + 2] === localNormal.z &&
                            uvs[vertex_idx * 2] === uv.x &&
                            uvs[vertex_idx * 2 + 1] === uv.y)) {
                            vertices.push(localVertex.x, localVertex.y, localVertex.z);
                            uvs.push(uv.x, uv.y);
                            normals.push(normal.x, normal.y, normal.z);
                            vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
                        }
                        indices.push(vertex_idx);
                        subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
                        subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
                        currentIndex++;
                    }
                }
            }
            mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
            mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
            mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
            mesh.setIndices(indices);
            if (keepSubMeshes) {
                // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
                var materialIndexOffset = 0, materialMaxIndex;
                mesh.subMeshes = new Array();
                for (var m in subMesh_dict) {
                    materialMaxIndex = -1;
                    for (var sm in subMesh_dict[m]) {
                        subMesh_obj = subMesh_dict[m][sm];
                        BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
                        materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
                    }
                    materialIndexOffset += ++materialMaxIndex;
                }
            }
            return mesh;
        };
        // Build Mesh from CSG taking material and transforms into account
        CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
            var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
            mesh.material = material;
            mesh.position.copyFrom(this.position);
            mesh.rotation.copyFrom(this.rotation);
            if (this.rotationQuaternion) {
                mesh.rotationQuaternion = this.rotationQuaternion.clone();
            }
            mesh.scaling.copyFrom(this.scaling);
            mesh.computeWorldMatrix(true);
            return mesh;
        };
        return CSG;
    }());
    BABYLON.CSG = CSG;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.csg.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var VRDistortionCorrectionPostProcess = (function (_super) {
        __extends(VRDistortionCorrectionPostProcess, _super);
        //ANY
        function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
            var _this = this;
            _super.call(this, name, "vrDistortionCorrection", [
                'LensCenter',
                'Scale',
                'ScaleIn',
                'HmdWarpParam'
            ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
            this._isRightEye = isRightEye;
            this._distortionFactors = vrMetrics.distortionK;
            this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
            this._lensCenterOffset = vrMetrics.lensCenterOffset;
            this.onSizeChangedObservable.add(function () {
                _this.aspectRatio = _this.width * .5 / _this.height;
                _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
                _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
                _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
            });
            this.onApplyObservable.add(function (effect) {
                effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
                effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
                effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
                effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
            });
        }
        return VRDistortionCorrectionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
 
// Mainly based on these 2 articles : 
// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ 
var BABYLON;
(function (BABYLON) {
    (function (JoystickAxis) {
        JoystickAxis[JoystickAxis["X"] = 0] = "X";
        JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
        JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
    })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
    var JoystickAxis = BABYLON.JoystickAxis;
    var VirtualJoystick = (function () {
        function VirtualJoystick(leftJoystick) {
            var _this = this;
            if (leftJoystick) {
                this._leftJoystick = true;
            }
            else {
                this._leftJoystick = false;
            }
            this._joystickIndex = VirtualJoystick._globalJoystickIndex;
            VirtualJoystick._globalJoystickIndex++;
            // By default left & right arrow keys are moving the X
            // and up & down keys are moving the Y
            this._axisTargetedByLeftAndRight = JoystickAxis.X;
            this._axisTargetedByUpAndDown = JoystickAxis.Y;
            this.reverseLeftRight = false;
            this.reverseUpDown = false;
            // collections of pointers
            this._touches = new BABYLON.StringDictionary();
            this.deltaPosition = BABYLON.Vector3.Zero();
            this._joystickSensibility = 25;
            this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
            this._rotationSpeed = 25;
            this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
            this._rotateOnAxisRelativeToMesh = false;
            this._onResize = function (evt) {
                VirtualJoystick.vjCanvasWidth = window.innerWidth;
                VirtualJoystick.vjCanvasHeight = window.innerHeight;
                VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
                VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
                VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
                VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
            };
            // injecting a canvas element on top of the canvas 3D game
            if (!VirtualJoystick.vjCanvas) {
                window.addEventListener("resize", this._onResize, false);
                VirtualJoystick.vjCanvas = document.createElement("canvas");
                VirtualJoystick.vjCanvasWidth = window.innerWidth;
                VirtualJoystick.vjCanvasHeight = window.innerHeight;
                VirtualJoystick.vjCanvas.width = window.innerWidth;
                VirtualJoystick.vjCanvas.height = window.innerHeight;
                VirtualJoystick.vjCanvas.style.width = "100%";
                VirtualJoystick.vjCanvas.style.height = "100%";
                VirtualJoystick.vjCanvas.style.position = "absolute";
                VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
                VirtualJoystick.vjCanvas.style.top = "0px";
                VirtualJoystick.vjCanvas.style.left = "0px";
                VirtualJoystick.vjCanvas.style.zIndex = "5";
                VirtualJoystick.vjCanvas.style.msTouchAction = "none";
                // Support for jQuery PEP polyfill
                VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
                VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
                VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
                VirtualJoystick.vjCanvasContext.lineWidth = 2;
                document.body.appendChild(VirtualJoystick.vjCanvas);
            }
            VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
            VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
            this.pressed = false;
            // default joystick color
            this._joystickColor = "cyan";
            this._joystickPointerID = -1;
            // current joystick position
            this._joystickPointerPos = new BABYLON.Vector2(0, 0);
            this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
            // origin joystick position
            this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
            this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
            this._onPointerDownHandlerRef = function (evt) {
                _this._onPointerDown(evt);
            };
            this._onPointerMoveHandlerRef = function (evt) {
                _this._onPointerMove(evt);
            };
            this._onPointerOutHandlerRef = function (evt) {
                _this._onPointerUp(evt);
            };
            this._onPointerUpHandlerRef = function (evt) {
                _this._onPointerUp(evt);
            };
            VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
                evt.preventDefault(); // Disables system menu
            }, false);
            requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
        }
        VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
            this._joystickSensibility = newJoystickSensibility;
            this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
        };
        VirtualJoystick.prototype._onPointerDown = function (e) {
            var positionOnScreenCondition;
            e.preventDefault();
            if (this._leftJoystick === true) {
                positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
            }
            else {
                positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
            }
            if (positionOnScreenCondition && this._joystickPointerID < 0) {
                // First contact will be dedicated to the virtual joystick
                this._joystickPointerID = e.pointerId;
                this._joystickPointerStartPos.x = e.clientX;
                this._joystickPointerStartPos.y = e.clientY;
                this._joystickPointerPos = this._joystickPointerStartPos.clone();
                this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
                this._deltaJoystickVector.x = 0;
                this._deltaJoystickVector.y = 0;
                this.pressed = true;
                this._touches.add(e.pointerId.toString(), e);
            }
            else {
                // You can only trigger the action buttons with a joystick declared
                if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
                    this._action();
                    this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
                }
            }
        };
        VirtualJoystick.prototype._onPointerMove = function (e) {
            // If the current pointer is the one associated to the joystick (first touch contact)
            if (this._joystickPointerID == e.pointerId) {
                this._joystickPointerPos.x = e.clientX;
                this._joystickPointerPos.y = e.clientY;
                this._deltaJoystickVector = this._joystickPointerPos.clone();
                this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
                var directionLeftRight = this.reverseLeftRight ? -1 : 1;
                var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
                switch (this._axisTargetedByLeftAndRight) {
                    case JoystickAxis.X:
                        this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
                        break;
                    case JoystickAxis.Y:
                        this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
                        break;
                    case JoystickAxis.Z:
                        this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
                        break;
                }
                var directionUpDown = this.reverseUpDown ? 1 : -1;
                var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
                switch (this._axisTargetedByUpAndDown) {
                    case JoystickAxis.X:
                        this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
                        break;
                    case JoystickAxis.Y:
                        this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
                        break;
                    case JoystickAxis.Z:
                        this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
                        break;
                }
            }
            else {
                var data = this._touches.get(e.pointerId.toString());
                if (data) {
                    data.x = e.clientX;
                    data.y = e.clientY;
                }
            }
        };
        VirtualJoystick.prototype._onPointerUp = function (e) {
            if (this._joystickPointerID == e.pointerId) {
                VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
                VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
                this._joystickPointerID = -1;
                this.pressed = false;
            }
            else {
                var touch = this._touches.get(e.pointerId.toString());
                if (touch) {
                    VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
                }
            }
            this._deltaJoystickVector.x = 0;
            this._deltaJoystickVector.y = 0;
            this._touches.remove(e.pointerId.toString());
        };
        /**
        * Change the color of the virtual joystick
        * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
        */
        VirtualJoystick.prototype.setJoystickColor = function (newColor) {
            this._joystickColor = newColor;
        };
        VirtualJoystick.prototype.setActionOnTouch = function (action) {
            this._action = action;
        };
        // Define which axis you'd like to control for left & right 
        VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
            switch (axis) {
                case JoystickAxis.X:
                case JoystickAxis.Y:
                case JoystickAxis.Z:
                    this._axisTargetedByLeftAndRight = axis;
                    break;
                default:
                    this._axisTargetedByLeftAndRight = JoystickAxis.X;
                    break;
            }
        };
        // Define which axis you'd like to control for up & down 
        VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
            switch (axis) {
                case JoystickAxis.X:
                case JoystickAxis.Y:
                case JoystickAxis.Z:
                    this._axisTargetedByUpAndDown = axis;
                    break;
                default:
                    this._axisTargetedByUpAndDown = JoystickAxis.Y;
                    break;
            }
        };
        VirtualJoystick.prototype._clearCanvas = function () {
            if (this._leftJoystick) {
                VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
            }
            else {
                VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
            }
        };
        VirtualJoystick.prototype._drawVirtualJoystick = function () {
            var _this = this;
            if (this.pressed) {
                this._touches.forEach(function (touch) {
                    if (touch.pointerId === _this._joystickPointerID) {
                        VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
                        VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.lineWidth = 6;
                        VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
                        VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
                        VirtualJoystick.vjCanvasContext.lineWidth = 2;
                        VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
                        VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
                    }
                    else {
                        VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.fillStyle = "white";
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.strokeStyle = "red";
                        VirtualJoystick.vjCanvasContext.lineWidth = 6;
                        VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        touch.prevX = touch.x;
                        touch.prevY = touch.y;
                    }
                    ;
                });
            }
            requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
        };
        VirtualJoystick.prototype.releaseCanvas = function () {
            if (VirtualJoystick.vjCanvas) {
                VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
                VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
                VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
                VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
                window.removeEventListener("resize", this._onResize);
                document.body.removeChild(VirtualJoystick.vjCanvas);
                VirtualJoystick.vjCanvas = null;
            }
        };
        // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
        VirtualJoystick._globalJoystickIndex = 0;
        return VirtualJoystick;
    }());
    BABYLON.VirtualJoystick = VirtualJoystick;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.virtualJoystick.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // We're mainly based on the logic defined into the FreeCamera code
    var VirtualJoysticksCamera = (function (_super) {
        __extends(VirtualJoysticksCamera, _super);
        function VirtualJoysticksCamera(name, position, scene) {
            _super.call(this, name, position, scene);
            this.inputs.addVirtualJoystick();
        }
        return VirtualJoysticksCamera;
    }(BABYLON.FreeCamera));
    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
 
var BABYLON;
(function (BABYLON) {
    var FreeCameraVirtualJoystickInput = (function () {
        function FreeCameraVirtualJoystickInput() {
        }
        FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
            return this._leftjoystick;
        };
        FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
            return this._rightjoystick;
        };
        FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
            if (this._leftjoystick) {
                var camera = this.camera;
                var speed = camera._computeLocalCameraSpeed() * 50;
                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
                camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
                if (!this._leftjoystick.pressed) {
                    this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
                }
                if (!this._rightjoystick.pressed) {
                    this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
                }
            }
        };
        FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
            this._leftjoystick = new BABYLON.VirtualJoystick(true);
            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
            this._leftjoystick.setJoystickSensibility(0.15);
            this._rightjoystick = new BABYLON.VirtualJoystick(false);
            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
            this._rightjoystick.reverseUpDown = true;
            this._rightjoystick.setJoystickSensibility(0.05);
            this._rightjoystick.setJoystickColor("yellow");
        };
        FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
            this._leftjoystick.releaseCanvas();
            this._rightjoystick.releaseCanvas();
        };
        FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
            return "FreeCameraVirtualJoystickInput";
        };
        FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
            return "virtualJoystick";
        };
        return FreeCameraVirtualJoystickInput;
    }());
    BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
    BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var AnaglyphPostProcess = (function (_super) {
        __extends(AnaglyphPostProcess, _super);
        function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
            this._passedProcess = rigCameras[0]._rigPostProcess;
            this.onApplyObservable.add(function (effect) {
                effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
            });
        }
        return AnaglyphPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.anaglyphPostProcess.js.map
 
var BABYLON;
(function (BABYLON) {
    var OutlineRenderer = (function () {
        function OutlineRenderer(scene) {
            this._scene = scene;
        }
        OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
            var _this = this;
            if (useOverlay === void 0) { useOverlay = false; }
            var scene = this._scene;
            var engine = this._scene.getEngine();
            var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
            if (!this.isReady(subMesh, hardwareInstancedRendering)) {
                return;
            }
            var mesh = subMesh.getRenderingMesh();
            var material = subMesh.getMaterial();
            engine.enableEffect(this._effect);
            this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
            this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
            this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
            }
            mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
            // Alpha test
            if (material && material.needAlphaTesting()) {
                var alphaTexture = material.getAlphaTestTexture();
                this._effect.setTexture("diffuseSampler", alphaTexture);
                this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
            }
            mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
        };
        OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
            var mesh = subMesh.getMesh();
            var material = subMesh.getMaterial();
            // Alpha test
            if (material && material.needAlphaTesting()) {
                defines.push("#define ALPHATEST");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                    defines.push("#define UV2");
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Instances
            if (useInstances) {
                defines.push("#define INSTANCES");
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
            // Get correct effect      
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
            }
            return this._effect.isReady();
        };
        return OutlineRenderer;
    }());
    BABYLON.OutlineRenderer = OutlineRenderer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.outlineRenderer.js.map
 
var BABYLON;
(function (BABYLON) {
    var MeshAssetTask = (function () {
        function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
            this.name = name;
            this.meshesNames = meshesNames;
            this.rootUrl = rootUrl;
            this.sceneFilename = sceneFilename;
            this.isCompleted = false;
        }
        MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
                _this.loadedMeshes = meshes;
                _this.loadedParticleSystems = particleSystems;
                _this.loadedSkeletons = skeletons;
                _this.isCompleted = true;
                if (_this.onSuccess) {
                    _this.onSuccess(_this);
                }
                onSuccess();
            }, null, function () {
                if (_this.onError) {
                    _this.onError(_this);
                }
                onError();
            });
        };
        return MeshAssetTask;
    }());
    BABYLON.MeshAssetTask = MeshAssetTask;
    var TextFileAssetTask = (function () {
        function TextFileAssetTask(name, url) {
            this.name = name;
            this.url = url;
            this.isCompleted = false;
        }
        TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            BABYLON.Tools.LoadFile(this.url, function (data) {
                _this.text = data;
                _this.isCompleted = true;
                if (_this.onSuccess) {
                    _this.onSuccess(_this);
                }
                onSuccess();
            }, null, scene.database, false, function () {
                if (_this.onError) {
                    _this.onError(_this);
                }
                onError();
            });
        };
        return TextFileAssetTask;
    }());
    BABYLON.TextFileAssetTask = TextFileAssetTask;
    var BinaryFileAssetTask = (function () {
        function BinaryFileAssetTask(name, url) {
            this.name = name;
            this.url = url;
            this.isCompleted = false;
        }
        BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            BABYLON.Tools.LoadFile(this.url, function (data) {
                _this.data = data;
                _this.isCompleted = true;
                if (_this.onSuccess) {
                    _this.onSuccess(_this);
                }
                onSuccess();
            }, null, scene.database, true, function () {
                if (_this.onError) {
                    _this.onError(_this);
                }
                onError();
            });
        };
        return BinaryFileAssetTask;
    }());
    BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
    var ImageAssetTask = (function () {
        function ImageAssetTask(name, url) {
            this.name = name;
            this.url = url;
            this.isCompleted = false;
        }
        ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            var img = new Image();
            BABYLON.Tools.SetCorsBehavior(this.url, img);
            img.onload = function () {
                _this.image = img;
                _this.isCompleted = true;
                if (_this.onSuccess) {
                    _this.onSuccess(_this);
                }
                onSuccess();
            };
            img.onerror = function () {
                if (_this.onError) {
                    _this.onError(_this);
                }
                onError();
            };
            img.src = this.url;
        };
        return ImageAssetTask;
    }());
    BABYLON.ImageAssetTask = ImageAssetTask;
    var TextureAssetTask = (function () {
        function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            this.name = name;
            this.url = url;
            this.noMipmap = noMipmap;
            this.invertY = invertY;
            this.samplingMode = samplingMode;
            this.isCompleted = false;
        }
        TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            var onload = function () {
                _this.isCompleted = true;
                if (_this.onSuccess) {
                    _this.onSuccess(_this);
                }
                onSuccess();
            };
            var onerror = function () {
                if (_this.onError) {
                    _this.onError(_this);
                }
                onError();
            };
            this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
        };
        return TextureAssetTask;
    }());
    BABYLON.TextureAssetTask = TextureAssetTask;
    var CubeTextureAssetTask = (function () {
        function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
            this.name = name;
            this.url = url;
            this.extensions = extensions;
            this.noMipmap = noMipmap;
            this.files = files;
            this.isCompleted = false;
        }
        CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            var onload = function () {
                _this.isCompleted = true;
                if (_this.onSuccess) {
                    _this.onSuccess(_this);
                }
                onSuccess();
            };
            var onerror = function () {
                if (_this.onError) {
                    _this.onError(_this);
                }
                onError();
            };
            this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
        };
        return CubeTextureAssetTask;
    }());
    BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
    var AssetsManager = (function () {
        function AssetsManager(scene) {
            this.tasks = new Array();
            this.waitingTasksCount = 0;
            this.useDefaultLoadingScreen = true;
            this._scene = scene;
        }
        AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
            var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
            this.tasks.push(task);
            return task;
        };
        AssetsManager.prototype.addTextFileTask = function (taskName, url) {
            var task = new TextFileAssetTask(taskName, url);
            this.tasks.push(task);
            return task;
        };
        AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
            var task = new BinaryFileAssetTask(taskName, url);
            this.tasks.push(task);
            return task;
        };
        AssetsManager.prototype.addImageTask = function (taskName, url) {
            var task = new ImageAssetTask(taskName, url);
            this.tasks.push(task);
            return task;
        };
        AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
            this.tasks.push(task);
            return task;
        };
        AssetsManager.prototype._decreaseWaitingTasksCount = function () {
            this.waitingTasksCount--;
            if (this.waitingTasksCount === 0) {
                if (this.onFinish) {
                    this.onFinish(this.tasks);
                }
                this._scene.getEngine().hideLoadingUI();
            }
        };
        AssetsManager.prototype._runTask = function (task) {
            var _this = this;
            task.run(this._scene, function () {
                if (_this.onTaskSuccess) {
                    _this.onTaskSuccess(task);
                }
                _this._decreaseWaitingTasksCount();
            }, function () {
                if (_this.onTaskError) {
                    _this.onTaskError(task);
                }
                _this._decreaseWaitingTasksCount();
            });
        };
        AssetsManager.prototype.reset = function () {
            this.tasks = new Array();
            return this;
        };
        AssetsManager.prototype.load = function () {
            this.waitingTasksCount = this.tasks.length;
            if (this.waitingTasksCount === 0) {
                if (this.onFinish) {
                    this.onFinish(this.tasks);
                }
                return this;
            }
            if (this.useDefaultLoadingScreen) {
                this._scene.getEngine().displayLoadingUI();
            }
            for (var index = 0; index < this.tasks.length; index++) {
                var task = this.tasks[index];
                this._runTask(task);
            }
            return this;
        };
        return AssetsManager;
    }());
    BABYLON.AssetsManager = AssetsManager;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.assetsManager.js.map
 
var BABYLON;
(function (BABYLON) {
    var VRCameraMetrics = (function () {
        function VRCameraMetrics() {
            this.compensateDistortion = true;
        }
        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
            get: function () {
                return this.hResolution / (2 * this.vResolution);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
            get: function () {
                return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
            get: function () {
                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
                var h = (4 * meters) / this.hScreenSize;
                return BABYLON.Matrix.Translation(h, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
            get: function () {
                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
                var h = (4 * meters) / this.hScreenSize;
                return BABYLON.Matrix.Translation(-h, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
            get: function () {
                return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
            get: function () {
                return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        VRCameraMetrics.GetDefault = function () {
            var result = new VRCameraMetrics();
            result.hResolution = 1280;
            result.vResolution = 800;
            result.hScreenSize = 0.149759993;
            result.vScreenSize = 0.0935999975;
            result.vScreenCenter = 0.0467999987,
                result.eyeToScreenDistance = 0.0410000011;
            result.lensSeparationDistance = 0.0635000020;
            result.interpupillaryDistance = 0.0640000030;
            result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
            result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
            result.postProcessScaleFactor = 1.714605507808412;
            result.lensCenterOffset = 0.151976421;
            return result;
        };
        return VRCameraMetrics;
    }());
    BABYLON.VRCameraMetrics = VRCameraMetrics;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.vrCameraMetrics.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var WebVRFreeCamera = (function (_super) {
        __extends(WebVRFreeCamera, _super);
        function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
            var _this = this;
            if (compensateDistortion === void 0) { compensateDistortion = false; }
            if (webVROptions === void 0) { webVROptions = {}; }
            _super.call(this, name, position, scene);
            this.webVROptions = webVROptions;
            this._vrDevice = null;
            this._cacheState = null;
            this._vrEnabled = false;
            this._attached = false;
            //using the position provided as the current position offset
            this._positionOffset = position;
            //enable VR
            this.getEngine().initWebVR();
            if (!this.getEngine().vrDisplaysPromise) {
                BABYLON.Tools.Error("WebVR is not enabled on your browser");
            }
            else {
                //TODO get the metrics updated using the device's eye parameters!
                //TODO also check that the device has the right capabilities!
                this._frameData = new VRFrameData();
                this.getEngine().vrDisplaysPromise.then(function (devices) {
                    if (devices.length > 0) {
                        _this._vrEnabled = true;
                        if (_this.webVROptions.displayName) {
                            var found = devices.some(function (device) {
                                if (device.displayName === _this.webVROptions.displayName) {
                                    _this._vrDevice = device;
                                    return true;
                                }
                                else {
                                    return false;
                                }
                            });
                            if (!found) {
                                _this._vrDevice = devices[0];
                                BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
                            }
                        }
                        else {
                            //choose the first one
                            _this._vrDevice = devices[0];
                        }
                        //reset the rig parameters.
                        _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
                        if (_this._attached) {
                            _this.getEngine().enableVR(_this._vrDevice);
                        }
                    }
                    else {
                        BABYLON.Tools.Error("No WebVR devices found!");
                    }
                });
            }
            this.rotationQuaternion = new BABYLON.Quaternion();
            this._quaternionCache = new BABYLON.Quaternion();
        }
        WebVRFreeCamera.prototype._checkInputs = function () {
            if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
                var currentPost = this._frameData.pose;
                //make sure we have data
                if (currentPost && currentPost.orientation) {
                    this._cacheState = currentPost;
                    this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
                    if (this.webVROptions.trackPosition && this._cacheState.position) {
                        this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
                        //scale the position accordingly
                        this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
                        //add the position offset
                        this.position.addInPlace(this._positionOffset);
                    }
                }
            }
            _super.prototype._checkInputs.call(this);
        };
        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
            _super.prototype.attachControl.call(this, element, noPreventDefault);
            this._attached = true;
            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
            if (this._vrEnabled) {
                this.getEngine().enableVR(this._vrDevice);
            }
        };
        WebVRFreeCamera.prototype.detachControl = function (element) {
            _super.prototype.detachControl.call(this, element);
            this._vrEnabled = false;
            this._attached = false;
            this.getEngine().disableVR();
        };
        WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
            //Backwards comp.
            BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
            //this.getEngine().switchFullscreen(requestPointerlock);
        };
        WebVRFreeCamera.prototype.getTypeName = function () {
            return "WebVRFreeCamera";
        };
        WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
            //uses the vrDisplay's "resetPose()".
            //pitch and roll won't be affected.
            this._vrDevice.resetPose();
        };
        /**
         *
         * Set the position offset of the VR camera
         * The offset will be added to the WebVR pose, after scaling it (if set).
         *
         * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
         *
         * @memberOf WebVRFreeCamera
         */
        WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
            if (newPosition) {
                this._positionOffset = newPosition;
            }
            else {
                this._positionOffset.copyFrom(this.position);
            }
        };
        return WebVRFreeCamera;
    }(BABYLON.FreeCamera));
    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.webVRCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // Standard optimizations
    var SceneOptimization = (function () {
        function SceneOptimization(priority) {
            if (priority === void 0) { priority = 0; }
            this.priority = priority;
            this.apply = function (scene) {
                return true; // Return true if everything that can be done was applied
            };
        }
        return SceneOptimization;
    }());
    BABYLON.SceneOptimization = SceneOptimization;
    var TextureOptimization = (function (_super) {
        __extends(TextureOptimization, _super);
        function TextureOptimization(priority, maximumSize) {
            var _this = this;
            if (priority === void 0) { priority = 0; }
            if (maximumSize === void 0) { maximumSize = 1024; }
            _super.call(this, priority);
            this.priority = priority;
            this.maximumSize = maximumSize;
            this.apply = function (scene) {
                var allDone = true;
                for (var index = 0; index < scene.textures.length; index++) {
                    var texture = scene.textures[index];
                    if (!texture.canRescale) {
                        continue;
                    }
                    var currentSize = texture.getSize();
                    var maxDimension = Math.max(currentSize.width, currentSize.height);
                    if (maxDimension > _this.maximumSize) {
                        texture.scale(0.5);
                        allDone = false;
                    }
                }
                return allDone;
            };
        }
        return TextureOptimization;
    }(SceneOptimization));
    BABYLON.TextureOptimization = TextureOptimization;
    var HardwareScalingOptimization = (function (_super) {
        __extends(HardwareScalingOptimization, _super);
        function HardwareScalingOptimization(priority, maximumScale) {
            var _this = this;
            if (priority === void 0) { priority = 0; }
            if (maximumScale === void 0) { maximumScale = 2; }
            _super.call(this, priority);
            this.priority = priority;
            this.maximumScale = maximumScale;
            this._currentScale = 1;
            this.apply = function (scene) {
                _this._currentScale++;
                scene.getEngine().setHardwareScalingLevel(_this._currentScale);
                return _this._currentScale >= _this.maximumScale;
            };
        }
        return HardwareScalingOptimization;
    }(SceneOptimization));
    BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
    var ShadowsOptimization = (function (_super) {
        __extends(ShadowsOptimization, _super);
        function ShadowsOptimization() {
            _super.apply(this, arguments);
            this.apply = function (scene) {
                scene.shadowsEnabled = false;
                return true;
            };
        }
        return ShadowsOptimization;
    }(SceneOptimization));
    BABYLON.ShadowsOptimization = ShadowsOptimization;
    var PostProcessesOptimization = (function (_super) {
        __extends(PostProcessesOptimization, _super);
        function PostProcessesOptimization() {
            _super.apply(this, arguments);
            this.apply = function (scene) {
                scene.postProcessesEnabled = false;
                return true;
            };
        }
        return PostProcessesOptimization;
    }(SceneOptimization));
    BABYLON.PostProcessesOptimization = PostProcessesOptimization;
    var LensFlaresOptimization = (function (_super) {
        __extends(LensFlaresOptimization, _super);
        function LensFlaresOptimization() {
            _super.apply(this, arguments);
            this.apply = function (scene) {
                scene.lensFlaresEnabled = false;
                return true;
            };
        }
        return LensFlaresOptimization;
    }(SceneOptimization));
    BABYLON.LensFlaresOptimization = LensFlaresOptimization;
    var ParticlesOptimization = (function (_super) {
        __extends(ParticlesOptimization, _super);
        function ParticlesOptimization() {
            _super.apply(this, arguments);
            this.apply = function (scene) {
                scene.particlesEnabled = false;
                return true;
            };
        }
        return ParticlesOptimization;
    }(SceneOptimization));
    BABYLON.ParticlesOptimization = ParticlesOptimization;
    var RenderTargetsOptimization = (function (_super) {
        __extends(RenderTargetsOptimization, _super);
        function RenderTargetsOptimization() {
            _super.apply(this, arguments);
            this.apply = function (scene) {
                scene.renderTargetsEnabled = false;
                return true;
            };
        }
        return RenderTargetsOptimization;
    }(SceneOptimization));
    BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
    var MergeMeshesOptimization = (function (_super) {
        __extends(MergeMeshesOptimization, _super);
        function MergeMeshesOptimization() {
            var _this = this;
            _super.apply(this, arguments);
            this._canBeMerged = function (abstractMesh) {
                if (!(abstractMesh instanceof BABYLON.Mesh)) {
                    return false;
                }
                var mesh = abstractMesh;
                if (!mesh.isVisible || !mesh.isEnabled()) {
                    return false;
                }
                if (mesh.instances.length > 0) {
                    return false;
                }
                if (mesh.skeleton || mesh.hasLODLevels) {
                    return false;
                }
                if (mesh.parent) {
                    return false;
                }
                return true;
            };
            this.apply = function (scene, updateSelectionTree) {
                var globalPool = scene.meshes.slice(0);
                var globalLength = globalPool.length;
                for (var index = 0; index < globalLength; index++) {
                    var currentPool = new Array();
                    var current = globalPool[index];
                    // Checks
                    if (!_this._canBeMerged(current)) {
                        continue;
                    }
                    currentPool.push(current);
                    // Find compatible meshes
                    for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
                        var otherMesh = globalPool[subIndex];
                        if (!_this._canBeMerged(otherMesh)) {
                            continue;
                        }
                        if (otherMesh.material !== current.material) {
                            continue;
                        }
                        if (otherMesh.checkCollisions !== current.checkCollisions) {
                            continue;
                        }
                        currentPool.push(otherMesh);
                        globalLength--;
                        globalPool.splice(subIndex, 1);
                        subIndex--;
                    }
                    if (currentPool.length < 2) {
                        continue;
                    }
                    // Merge meshes
                    BABYLON.Mesh.MergeMeshes(currentPool);
                }
                if (updateSelectionTree != undefined) {
                    if (updateSelectionTree) {
                        scene.createOrUpdateSelectionOctree();
                    }
                }
                else if (MergeMeshesOptimization.UpdateSelectionTree) {
                    scene.createOrUpdateSelectionOctree();
                }
                return true;
            };
        }
        Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
            get: function () {
                return MergeMeshesOptimization._UpdateSelectionTree;
            },
            set: function (value) {
                MergeMeshesOptimization._UpdateSelectionTree = value;
            },
            enumerable: true,
            configurable: true
        });
        MergeMeshesOptimization._UpdateSelectionTree = false;
        return MergeMeshesOptimization;
    }(SceneOptimization));
    BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
    // Options
    var SceneOptimizerOptions = (function () {
        function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
            if (targetFrameRate === void 0) { targetFrameRate = 60; }
            if (trackerDuration === void 0) { trackerDuration = 2000; }
            this.targetFrameRate = targetFrameRate;
            this.trackerDuration = trackerDuration;
            this.optimizations = new Array();
        }
        SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
            var result = new SceneOptimizerOptions(targetFrameRate);
            var priority = 0;
            result.optimizations.push(new MergeMeshesOptimization(priority));
            result.optimizations.push(new ShadowsOptimization(priority));
            result.optimizations.push(new LensFlaresOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new PostProcessesOptimization(priority));
            result.optimizations.push(new ParticlesOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new TextureOptimization(priority, 1024));
            return result;
        };
        SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
            var result = new SceneOptimizerOptions(targetFrameRate);
            var priority = 0;
            result.optimizations.push(new MergeMeshesOptimization(priority));
            result.optimizations.push(new ShadowsOptimization(priority));
            result.optimizations.push(new LensFlaresOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new PostProcessesOptimization(priority));
            result.optimizations.push(new ParticlesOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new TextureOptimization(priority, 512));
            // Next priority
            priority++;
            result.optimizations.push(new RenderTargetsOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new HardwareScalingOptimization(priority, 2));
            return result;
        };
        SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
            var result = new SceneOptimizerOptions(targetFrameRate);
            var priority = 0;
            result.optimizations.push(new MergeMeshesOptimization(priority));
            result.optimizations.push(new ShadowsOptimization(priority));
            result.optimizations.push(new LensFlaresOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new PostProcessesOptimization(priority));
            result.optimizations.push(new ParticlesOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new TextureOptimization(priority, 256));
            // Next priority
            priority++;
            result.optimizations.push(new RenderTargetsOptimization(priority));
            // Next priority
            priority++;
            result.optimizations.push(new HardwareScalingOptimization(priority, 4));
            return result;
        };
        return SceneOptimizerOptions;
    }());
    BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
    // Scene optimizer tool
    var SceneOptimizer = (function () {
        function SceneOptimizer() {
        }
        SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
            // TODO: add an epsilon
            if (scene.getEngine().getFps() >= options.targetFrameRate) {
                if (onSuccess) {
                    onSuccess();
                }
                return;
            }
            // Apply current level of optimizations
            var allDone = true;
            var noOptimizationApplied = true;
            for (var index = 0; index < options.optimizations.length; index++) {
                var optimization = options.optimizations[index];
                if (optimization.priority === currentPriorityLevel) {
                    noOptimizationApplied = false;
                    allDone = allDone && optimization.apply(scene);
                }
            }
            // If no optimization was applied, this is a failure :(
            if (noOptimizationApplied) {
                if (onFailure) {
                    onFailure();
                }
                return;
            }
            // If all optimizations were done, move to next level
            if (allDone) {
                currentPriorityLevel++;
            }
            // Let's the system running for a specific amount of time before checking FPS
            scene.executeWhenReady(function () {
                setTimeout(function () {
                    SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
                }, options.trackerDuration);
            });
        };
        SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
            if (!options) {
                options = SceneOptimizerOptions.ModerateDegradationAllowed();
            }
            // Let's the system running for a specific amount of time before checking FPS
            scene.executeWhenReady(function () {
                setTimeout(function () {
                    SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
                }, options.trackerDuration);
            });
        };
        return SceneOptimizer;
    }());
    BABYLON.SceneOptimizer = SceneOptimizer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.sceneOptimizer.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var MeshLODLevel = (function () {
            function MeshLODLevel(distance, mesh) {
                this.distance = distance;
                this.mesh = mesh;
            }
            return MeshLODLevel;
        }());
        Internals.MeshLODLevel = MeshLODLevel;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.meshLODLevel.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var RawTexture = (function (_super) {
        __extends(RawTexture, _super);
        function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            _super.call(this, null, scene, !generateMipMaps, invertY);
            this.format = format;
            this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
        }
        RawTexture.prototype.update = function (data) {
            this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
        };
        // Statics
        RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
        };
        RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
        };
        RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
        };
        RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
        };
        RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
        };
        return RawTexture;
    }(BABYLON.Texture));
    BABYLON.RawTexture = RawTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.rawTexture.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var IndexedVector2 = (function (_super) {
        __extends(IndexedVector2, _super);
        function IndexedVector2(original, index) {
            _super.call(this, original.x, original.y);
            this.index = index;
        }
        return IndexedVector2;
    }(BABYLON.Vector2));
    var PolygonPoints = (function () {
        function PolygonPoints() {
            this.elements = new Array();
        }
        PolygonPoints.prototype.add = function (originalPoints) {
            var _this = this;
            var result = new Array();
            originalPoints.forEach(function (point) {
                if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
                    var newPoint = new IndexedVector2(point, _this.elements.length);
                    result.push(newPoint);
                    _this.elements.push(newPoint);
                }
            });
            return result;
        };
        PolygonPoints.prototype.computeBounds = function () {
            var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
            var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
            this.elements.forEach(function (point) {
                // x
                if (point.x < lmin.x) {
                    lmin.x = point.x;
                }
                else if (point.x > lmax.x) {
                    lmax.x = point.x;
                }
                // y
                if (point.y < lmin.y) {
                    lmin.y = point.y;
                }
                else if (point.y > lmax.y) {
                    lmax.y = point.y;
                }
            });
            return {
                min: lmin,
                max: lmax,
                width: lmax.x - lmin.x,
                height: lmax.y - lmin.y
            };
        };
        return PolygonPoints;
    }());
    var Polygon = (function () {
        function Polygon() {
        }
        Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
            return [
                new BABYLON.Vector2(xmin, ymin),
                new BABYLON.Vector2(xmax, ymin),
                new BABYLON.Vector2(xmax, ymax),
                new BABYLON.Vector2(xmin, ymax)
            ];
        };
        Polygon.Circle = function (radius, cx, cy, numberOfSides) {
            if (cx === void 0) { cx = 0; }
            if (cy === void 0) { cy = 0; }
            if (numberOfSides === void 0) { numberOfSides = 32; }
            var result = new Array();
            var angle = 0;
            var increment = (Math.PI * 2) / numberOfSides;
            for (var i = 0; i < numberOfSides; i++) {
                result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
                angle -= increment;
            }
            return result;
        };
        Polygon.Parse = function (input) {
            var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
            var i, result = [];
            for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
                result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
            }
            return result;
        };
        Polygon.StartingAt = function (x, y) {
            return BABYLON.Path2.StartingAt(x, y);
        };
        return Polygon;
    }());
    BABYLON.Polygon = Polygon;
    var PolygonMeshBuilder = (function () {
        function PolygonMeshBuilder(name, contours, scene) {
            this._points = new PolygonPoints();
            this._outlinepoints = new PolygonPoints();
            this._holes = [];
            this._epoints = new Array();
            this._eholes = new Array();
            this._name = name;
            this._scene = scene;
            var points;
            if (contours instanceof BABYLON.Path2) {
                points = contours.getPoints();
            }
            else {
                points = contours;
            }
            this._addToepoint(points);
            this._points.add(points);
            this._outlinepoints.add(points);
        }
        PolygonMeshBuilder.prototype._addToepoint = function (points) {
            for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
                var p = points_1[_i];
                this._epoints.push(p.x, p.y);
            }
        };
        PolygonMeshBuilder.prototype.addHole = function (hole) {
            this._points.add(hole);
            var holepoints = new PolygonPoints();
            holepoints.add(hole);
            this._holes.push(holepoints);
            this._eholes.push(this._epoints.length / 2);
            this._addToepoint(hole);
            return this;
        };
        PolygonMeshBuilder.prototype.build = function (updatable, depth) {
            var _this = this;
            if (updatable === void 0) { updatable = false; }
            var result = new BABYLON.Mesh(this._name, this._scene);
            var normals = [];
            var positions = [];
            var uvs = [];
            var bounds = this._points.computeBounds();
            this._points.elements.forEach(function (p) {
                normals.push(0, 1.0, 0);
                positions.push(p.x, 0, p.y);
                uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
            });
            var indices = [];
            var res = Earcut.earcut(this._epoints, this._eholes, 2);
            for (var i = 0; i < res.length; i++) {
                indices.push(res[i]);
            }
            if (depth > 0) {
                var positionscount = (positions.length / 3); //get the current pointcount
                this._points.elements.forEach(function (p) {
                    normals.push(0, -1.0, 0);
                    positions.push(p.x, -depth, p.y);
                    uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
                });
                var totalCount = indices.length;
                for (var i = 0; i < totalCount; i += 3) {
                    var i0 = indices[i + 0];
                    var i1 = indices[i + 1];
                    var i2 = indices[i + 2];
                    indices.push(i2 + positionscount);
                    indices.push(i1 + positionscount);
                    indices.push(i0 + positionscount);
                }
                //Add the sides
                this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
                this._holes.forEach(function (hole) {
                    _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
                });
            }
            result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
            result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
            result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
            result.setIndices(indices);
            return result;
        };
        PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
            var StartIndex = positions.length / 3;
            var ulength = 0;
            for (var i = 0; i < points.elements.length; i++) {
                var p = points.elements[i];
                var p1;
                if ((i + 1) > points.elements.length - 1) {
                    p1 = points.elements[0];
                }
                else {
                    p1 = points.elements[i + 1];
                }
                positions.push(p.x, 0, p.y);
                positions.push(p.x, -depth, p.y);
                positions.push(p1.x, 0, p1.y);
                positions.push(p1.x, -depth, p1.y);
                var v1 = new BABYLON.Vector3(p.x, 0, p.y);
                var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
                var v3 = v2.subtract(v1);
                var v4 = new BABYLON.Vector3(0, 1, 0);
                var vn = BABYLON.Vector3.Cross(v3, v4);
                vn = vn.normalize();
                uvs.push(ulength / bounds.width, 0);
                uvs.push(ulength / bounds.width, 1);
                ulength += v3.length();
                uvs.push((ulength / bounds.width), 0);
                uvs.push((ulength / bounds.width), 1);
                if (!flip) {
                    normals.push(-vn.x, -vn.y, -vn.z);
                    normals.push(-vn.x, -vn.y, -vn.z);
                    normals.push(-vn.x, -vn.y, -vn.z);
                    normals.push(-vn.x, -vn.y, -vn.z);
                    indices.push(StartIndex);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 2);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 3);
                    indices.push(StartIndex + 2);
                }
                else {
                    normals.push(vn.x, vn.y, vn.z);
                    normals.push(vn.x, vn.y, vn.z);
                    normals.push(vn.x, vn.y, vn.z);
                    normals.push(vn.x, vn.y, vn.z);
                    indices.push(StartIndex);
                    indices.push(StartIndex + 2);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 2);
                    indices.push(StartIndex + 3);
                }
                StartIndex += 4;
            }
            ;
        };
        return PolygonMeshBuilder;
    }());
    BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.polygonMesh.js.map
 
var BABYLON;
(function (BABYLON) {
    var Octree = (function () {
        function Octree(creationFunc, maxBlockCapacity, maxDepth) {
            if (maxDepth === void 0) { maxDepth = 2; }
            this.maxDepth = maxDepth;
            this.dynamicContent = new Array();
            this._maxBlockCapacity = maxBlockCapacity || 64;
            this._selectionContent = new BABYLON.SmartArray(1024);
            this._creationFunc = creationFunc;
        }
        // Methods
        Octree.prototype.update = function (worldMin, worldMax, entries) {
            Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
        };
        Octree.prototype.addMesh = function (entry) {
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.addEntry(entry);
            }
        };
        Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
            this._selectionContent.reset();
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.select(frustumPlanes, this._selectionContent, allowDuplicate);
            }
            if (allowDuplicate) {
                this._selectionContent.concat(this.dynamicContent);
            }
            else {
                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
            }
            return this._selectionContent;
        };
        Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
            this._selectionContent.reset();
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
            }
            if (allowDuplicate) {
                this._selectionContent.concat(this.dynamicContent);
            }
            else {
                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
            }
            return this._selectionContent;
        };
        Octree.prototype.intersectsRay = function (ray) {
            this._selectionContent.reset();
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.intersectsRay(ray, this._selectionContent);
            }
            this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
            return this._selectionContent;
        };
        Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
            target.blocks = new Array();
            var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
            // Segmenting space
            for (var x = 0; x < 2; x++) {
                for (var y = 0; y < 2; y++) {
                    for (var z = 0; z < 2; z++) {
                        var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
                        var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
                        var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
                        block.addEntries(entries);
                        target.blocks.push(block);
                    }
                }
            }
        };
        Octree.CreationFuncForMeshes = function (entry, block) {
            if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
                block.entries.push(entry);
            }
        };
        Octree.CreationFuncForSubMeshes = function (entry, block) {
            if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
                block.entries.push(entry);
            }
        };
        return Octree;
    }());
    BABYLON.Octree = Octree;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.octree.js.map
 
var BABYLON;
(function (BABYLON) {
    var OctreeBlock = (function () {
        function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
            this.entries = new Array();
            this._boundingVectors = new Array();
            this._capacity = capacity;
            this._depth = depth;
            this._maxDepth = maxDepth;
            this._creationFunc = creationFunc;
            this._minPoint = minPoint;
            this._maxPoint = maxPoint;
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors[2].x = maxPoint.x;
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors[3].y = maxPoint.y;
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors[4].z = maxPoint.z;
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors[5].z = minPoint.z;
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors[6].x = minPoint.x;
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors[7].y = minPoint.y;
        }
        Object.defineProperty(OctreeBlock.prototype, "capacity", {
            // Property
            get: function () {
                return this._capacity;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OctreeBlock.prototype, "minPoint", {
            get: function () {
                return this._minPoint;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
            get: function () {
                return this._maxPoint;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        OctreeBlock.prototype.addEntry = function (entry) {
            if (this.blocks) {
                for (var index = 0; index < this.blocks.length; index++) {
                    var block = this.blocks[index];
                    block.addEntry(entry);
                }
                return;
            }
            this._creationFunc(entry, this);
            if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
                this.createInnerBlocks();
            }
        };
        OctreeBlock.prototype.addEntries = function (entries) {
            for (var index = 0; index < entries.length; index++) {
                var mesh = entries[index];
                this.addEntry(mesh);
            }
        };
        OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
            if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
                if (this.blocks) {
                    for (var index = 0; index < this.blocks.length; index++) {
                        var block = this.blocks[index];
                        block.select(frustumPlanes, selection, allowDuplicate);
                    }
                    return;
                }
                if (allowDuplicate) {
                    selection.concat(this.entries);
                }
                else {
                    selection.concatWithNoDuplicate(this.entries);
                }
            }
        };
        OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
            if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
                if (this.blocks) {
                    for (var index = 0; index < this.blocks.length; index++) {
                        var block = this.blocks[index];
                        block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
                    }
                    return;
                }
                if (allowDuplicate) {
                    selection.concat(this.entries);
                }
                else {
                    selection.concatWithNoDuplicate(this.entries);
                }
            }
        };
        OctreeBlock.prototype.intersectsRay = function (ray, selection) {
            if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
                if (this.blocks) {
                    for (var index = 0; index < this.blocks.length; index++) {
                        var block = this.blocks[index];
                        block.intersectsRay(ray, selection);
                    }
                    return;
                }
                selection.concatWithNoDuplicate(this.entries);
            }
        };
        OctreeBlock.prototype.createInnerBlocks = function () {
            BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
        };
        return OctreeBlock;
    }());
    BABYLON.OctreeBlock = OctreeBlock;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.octreeBlock.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var BlurPostProcess = (function (_super) {
        __extends(BlurPostProcess, _super);
        function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
            this.direction = direction;
            this.blurWidth = blurWidth;
            this.onApplyObservable.add(function (effect) {
                effect.setFloat2("screenSize", _this.width, _this.height);
                effect.setVector2("direction", _this.direction);
                effect.setFloat("blurWidth", _this.blurWidth);
            });
        }
        return BlurPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.BlurPostProcess = BlurPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.blurPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var RefractionPostProcess = (function (_super) {
        __extends(RefractionPostProcess, _super);
        function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
            this.color = color;
            this.depth = depth;
            this.colorLevel = colorLevel;
            this.onActivateObservable.add(function (cam) {
                _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
            });
            this.onApplyObservable.add(function (effect) {
                effect.setColor3("baseColor", _this.color);
                effect.setFloat("depth", _this.depth);
                effect.setFloat("colorLevel", _this.colorLevel);
                effect.setTexture("refractionSampler", _this._refRexture);
            });
        }
        // Methods
        RefractionPostProcess.prototype.dispose = function (camera) {
            if (this._refRexture) {
                this._refRexture.dispose();
            }
            _super.prototype.dispose.call(this, camera);
        };
        return RefractionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.RefractionPostProcess = RefractionPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.refractionPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var BlackAndWhitePostProcess = (function (_super) {
        __extends(BlackAndWhitePostProcess, _super);
        function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
            _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
        }
        return BlackAndWhitePostProcess;
    }(BABYLON.PostProcess));
    BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var ConvolutionPostProcess = (function (_super) {
        __extends(ConvolutionPostProcess, _super);
        function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
            this.kernel = kernel;
            this.onApply = function (effect) {
                effect.setFloat2("screenSize", _this.width, _this.height);
                effect.setArray("kernel", _this.kernel);
            };
        }
        // Statics
        // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
        ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
        ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
        ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
        ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
        ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
        ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
        return ConvolutionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.convolutionPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var FilterPostProcess = (function (_super) {
        __extends(FilterPostProcess, _super);
        function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
            this.kernelMatrix = kernelMatrix;
            this.onApply = function (effect) {
                effect.setMatrix("kernelMatrix", _this.kernelMatrix);
            };
        }
        return FilterPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.FilterPostProcess = FilterPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.filterPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var FxaaPostProcess = (function (_super) {
        __extends(FxaaPostProcess, _super);
        function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
            this.onSizeChangedObservable.add(function () {
                _this.texelWidth = 1.0 / _this.width;
                _this.texelHeight = 1.0 / _this.height;
            });
            this.onApplyObservable.add(function (effect) {
                effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
            });
        }
        return FxaaPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.FxaaPostProcess = FxaaPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.fxaaPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var StereoscopicInterlacePostProcess = (function (_super) {
        __extends(StereoscopicInterlacePostProcess, _super);
        function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
            this._passedProcess = rigCameras[0]._rigPostProcess;
            this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
            this.onSizeChangedObservable.add(function () {
                _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
            });
            this.onApplyObservable.add(function (effect) {
                effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
                effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
            });
        }
        return StereoscopicInterlacePostProcess;
    }(BABYLON.PostProcess));
    BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
 
var BABYLON;
(function (BABYLON) {
    var LensFlare = (function () {
        function LensFlare(size, position, color, imgUrl, system) {
            this.size = size;
            this.position = position;
            this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
            this.dispose = function () {
                if (this.texture) {
                    this.texture.dispose();
                }
                // Remove from scene
                var index = this._system.lensFlares.indexOf(this);
                this._system.lensFlares.splice(index, 1);
            };
            this.color = color || new BABYLON.Color3(1, 1, 1);
            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
            this._system = system;
            system.lensFlares.push(this);
        }
        return LensFlare;
    }());
    BABYLON.LensFlare = LensFlare;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.lensFlare.js.map
 
var BABYLON;
(function (BABYLON) {
    var LensFlareSystem = (function () {
        function LensFlareSystem(name, emitter, scene) {
            this.name = name;
            this.lensFlares = new Array();
            this.borderLimit = 300;
            this.viewportBorder = 0;
            this.layerMask = 0x0FFFFFFF;
            this._vertexBuffers = {};
            this._isEnabled = true;
            this._scene = scene;
            this._emitter = emitter;
            this.id = name;
            scene.lensFlareSystems.push(this);
            this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
            var engine = scene.getEngine();
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
            // Effects
            this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
        }
        Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
            get: function () {
                return this._isEnabled;
            },
            set: function (value) {
                this._isEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        LensFlareSystem.prototype.getScene = function () {
            return this._scene;
        };
        LensFlareSystem.prototype.getEmitter = function () {
            return this._emitter;
        };
        LensFlareSystem.prototype.setEmitter = function (newEmitter) {
            this._emitter = newEmitter;
        };
        LensFlareSystem.prototype.getEmitterPosition = function () {
            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
        };
        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
            var position = this.getEmitterPosition();
            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
            this._positionX = position.x;
            this._positionY = position.y;
            position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
            if (this.viewportBorder > 0) {
                globalViewport.x -= this.viewportBorder;
                globalViewport.y -= this.viewportBorder;
                globalViewport.width += this.viewportBorder * 2;
                globalViewport.height += this.viewportBorder * 2;
                position.x += this.viewportBorder;
                position.y += this.viewportBorder;
                this._positionX += this.viewportBorder;
                this._positionY += this.viewportBorder;
            }
            if (position.z > 0) {
                if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
                    if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
                        return true;
                }
                return true;
            }
            return false;
        };
        LensFlareSystem.prototype._isVisible = function () {
            if (!this._isEnabled) {
                return false;
            }
            var emitterPosition = this.getEmitterPosition();
            var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
            var distance = direction.length();
            direction.normalize();
            var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
            return !pickInfo.hit || pickInfo.distance > distance;
        };
        LensFlareSystem.prototype.render = function () {
            if (!this._effect.isReady())
                return false;
            var engine = this._scene.getEngine();
            var viewport = this._scene.activeCamera.viewport;
            var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
            // Position
            if (!this.computeEffectivePosition(globalViewport)) {
                return false;
            }
            // Visibility
            if (!this._isVisible()) {
                return false;
            }
            // Intensity
            var awayX;
            var awayY;
            if (this._positionX < this.borderLimit + globalViewport.x) {
                awayX = this.borderLimit + globalViewport.x - this._positionX;
            }
            else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
            }
            else {
                awayX = 0;
            }
            if (this._positionY < this.borderLimit + globalViewport.y) {
                awayY = this.borderLimit + globalViewport.y - this._positionY;
            }
            else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
            }
            else {
                awayY = 0;
            }
            var away = (awayX > awayY) ? awayX : awayY;
            away -= this.viewportBorder;
            if (away > this.borderLimit) {
                away = this.borderLimit;
            }
            var intensity = 1.0 - (away / this.borderLimit);
            if (intensity < 0) {
                return false;
            }
            if (intensity > 1.0) {
                intensity = 1.0;
            }
            if (this.viewportBorder > 0) {
                globalViewport.x += this.viewportBorder;
                globalViewport.y += this.viewportBorder;
                globalViewport.width -= this.viewportBorder * 2;
                globalViewport.height -= this.viewportBorder * 2;
                this._positionX -= this.viewportBorder;
                this._positionY -= this.viewportBorder;
            }
            // Position
            var centerX = globalViewport.x + globalViewport.width / 2;
            var centerY = globalViewport.y + globalViewport.height / 2;
            var distX = centerX - this._positionX;
            var distY = centerY - this._positionY;
            // Effects
            engine.enableEffect(this._effect);
            engine.setState(false);
            engine.setDepthBuffer(false);
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
            // Flares
            for (var index = 0; index < this.lensFlares.length; index++) {
                var flare = this.lensFlares[index];
                engine.setAlphaMode(flare.alphaMode);
                var x = centerX - (distX * flare.position);
                var y = centerY - (distY * flare.position);
                var cw = flare.size;
                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
                var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
                var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
                var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
                this._effect.setMatrix("viewportMatrix", viewportMatrix);
                // Texture
                this._effect.setTexture("textureSampler", flare.texture);
                // Color
                this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
                // Draw order
                engine.draw(true, 0, 6);
            }
            engine.setDepthBuffer(true);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            return true;
        };
        LensFlareSystem.prototype.dispose = function () {
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            while (this.lensFlares.length) {
                this.lensFlares[0].dispose();
            }
            // Remove from scene
            var index = this._scene.lensFlareSystems.indexOf(this);
            this._scene.lensFlareSystems.splice(index, 1);
        };
        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
            var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
            var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
            lensFlareSystem.id = parsedLensFlareSystem.id || name;
            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
                var parsedFlare = parsedLensFlareSystem.flares[index];
                var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
            }
            return lensFlareSystem;
        };
        LensFlareSystem.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.id = this.id;
            serializationObject.name = this.name;
            serializationObject.emitterId = this.getEmitter().id;
            serializationObject.borderLimit = this.borderLimit;
            serializationObject.flares = [];
            for (var index = 0; index < this.lensFlares.length; index++) {
                var flare = this.lensFlares[index];
                serializationObject.flares.push({
                    size: flare.size,
                    position: flare.position,
                    color: flare.color.asArray(),
                    textureName: BABYLON.Tools.GetFilename(flare.texture.name)
                });
            }
            return serializationObject;
        };
        return LensFlareSystem;
    }());
    BABYLON.LensFlareSystem = LensFlareSystem;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.lensFlareSystem.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // We're mainly based on the logic defined into the FreeCamera code
    var DeviceOrientationCamera = (function (_super) {
        __extends(DeviceOrientationCamera, _super);
        function DeviceOrientationCamera(name, position, scene) {
            _super.call(this, name, position, scene);
            this._quaternionCache = new BABYLON.Quaternion();
            this.inputs.addDeviceOrientation();
        }
        DeviceOrientationCamera.prototype.getTypeName = function () {
            return "DeviceOrientationCamera";
        };
        DeviceOrientationCamera.prototype._checkInputs = function () {
            _super.prototype._checkInputs.call(this);
            this._quaternionCache.copyFrom(this.rotationQuaternion);
            if (this._initialQuaternion) {
                this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
            }
        };
        DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
            var _this = this;
            if (axis === void 0) { axis = BABYLON.Axis.Y; }
            //can only work if this camera has a rotation quaternion already.
            if (!this.rotationQuaternion)
                return;
            if (!this._initialQuaternion) {
                this._initialQuaternion = new BABYLON.Quaternion();
            }
            this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
            ['x', 'y', 'z'].forEach(function (axisName) {
                if (!axis[axisName]) {
                    _this._initialQuaternion[axisName] = 0;
                }
                else {
                    _this._initialQuaternion[axisName] *= -1;
                }
            });
            this._initialQuaternion.normalize();
            //force rotation update
            this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
        };
        return DeviceOrientationCamera;
    }(BABYLON.FreeCamera));
    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.deviceOrientationCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var VRDeviceOrientationFreeCamera = (function (_super) {
        __extends(VRDeviceOrientationFreeCamera, _super);
        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
            if (compensateDistortion === void 0) { compensateDistortion = true; }
            if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
            _super.call(this, name, position, scene);
            vrCameraMetrics.compensateDistortion = compensateDistortion;
            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
        }
        VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
            return "VRDeviceOrientationFreeCamera";
        };
        return VRDeviceOrientationFreeCamera;
    }(BABYLON.DeviceOrientationCamera));
    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
    var VRDeviceOrientationArcRotateCamera = (function (_super) {
        __extends(VRDeviceOrientationArcRotateCamera, _super);
        function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
            if (compensateDistortion === void 0) { compensateDistortion = true; }
            if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
            _super.call(this, name, alpha, beta, radius, target, scene);
            vrCameraMetrics.compensateDistortion = compensateDistortion;
            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
            this.inputs.addVRDeviceOrientation();
        }
        VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
            return "VRDeviceOrientationArcRotateCamera";
        };
        return VRDeviceOrientationArcRotateCamera;
    }(BABYLON.ArcRotateCamera));
    BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // We're mainly based on the logic defined into the FreeCamera code
    var UniversalCamera = (function (_super) {
        __extends(UniversalCamera, _super);
        //-- end properties for backward compatibility for inputs
        function UniversalCamera(name, position, scene) {
            _super.call(this, name, position, scene);
            this.inputs.addGamepad();
        }
        Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
            //-- Begin properties for backward compatibility for inputs
            get: function () {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    return gamepad.gamepadAngularSensibility;
            },
            set: function (value) {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    gamepad.gamepadAngularSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
            get: function () {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    return gamepad.gamepadMoveSensibility;
            },
            set: function (value) {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    gamepad.gamepadMoveSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        UniversalCamera.prototype.getTypeName = function () {
            return "UniversalCamera";
        };
        return UniversalCamera;
    }(BABYLON.TouchCamera));
    BABYLON.UniversalCamera = UniversalCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.universalCamera.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Gamepads = (function () {
        function Gamepads(ongamedpadconnected) {
            var _this = this;
            this.babylonGamepads = [];
            this.oneGamepadConnected = false;
            this.isMonitoring = false;
            this.gamepadEventSupported = 'GamepadEvent' in window;
            this.gamepadSupportAvailable = (navigator.getGamepads ||
                !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
            this._callbackGamepadConnected = ongamedpadconnected;
            if (this.gamepadSupportAvailable) {
                // Checking if the gamepad connected event is supported (like in Firefox)
                if (this.gamepadEventSupported) {
                    this._onGamepadConnectedEvent = function (evt) {
                        _this._onGamepadConnected(evt);
                    };
                    this._onGamepadDisonnectedEvent = function (evt) {
                        _this._onGamepadDisconnected(evt);
                    };
                    window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
                    window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
                }
                else {
                    this._startMonitoringGamepads();
                }
            }
        }
        Gamepads.prototype.dispose = function () {
            if (Gamepads.gamepadDOMInfo) {
                document.body.removeChild(Gamepads.gamepadDOMInfo);
            }
            if (this._onGamepadConnectedEvent) {
                window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
                window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
                this._onGamepadConnectedEvent = null;
                this._onGamepadDisonnectedEvent = null;
            }
        };
        Gamepads.prototype._onGamepadConnected = function (evt) {
            var newGamepad = this._addNewGamepad(evt.gamepad);
            if (this._callbackGamepadConnected)
                this._callbackGamepadConnected(newGamepad);
            this._startMonitoringGamepads();
        };
        Gamepads.prototype._addNewGamepad = function (gamepad) {
            if (!this.oneGamepadConnected) {
                this.oneGamepadConnected = true;
                if (Gamepads.gamepadDOMInfo) {
                    document.body.removeChild(Gamepads.gamepadDOMInfo);
                    Gamepads.gamepadDOMInfo = null;
                }
            }
            var newGamepad;
            var xboxOne = (gamepad.id.search("Xbox One") !== -1);
            if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
                newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
            }
            else {
                newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
            }
            this.babylonGamepads.push(newGamepad);
            return newGamepad;
        };
        Gamepads.prototype._onGamepadDisconnected = function (evt) {
            // Remove the gamepad from the list of gamepads to monitor.
            for (var i in this.babylonGamepads) {
                if (this.babylonGamepads[i].index == evt.gamepad.index) {
                    this.babylonGamepads.splice(+i, 1);
                    break;
                }
            }
            // If no gamepads are left, stop the polling loop.
            if (this.babylonGamepads.length == 0) {
                this._stopMonitoringGamepads();
            }
        };
        Gamepads.prototype._startMonitoringGamepads = function () {
            if (!this.isMonitoring) {
                this.isMonitoring = true;
                this._checkGamepadsStatus();
            }
        };
        Gamepads.prototype._stopMonitoringGamepads = function () {
            this.isMonitoring = false;
        };
        Gamepads.prototype._checkGamepadsStatus = function () {
            var _this = this;
            // updating gamepad objects
            this._updateGamepadObjects();
            for (var i in this.babylonGamepads) {
                this.babylonGamepads[i].update();
            }
            if (this.isMonitoring) {
                if (window.requestAnimationFrame) {
                    window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
                }
                else if (window.mozRequestAnimationFrame) {
                    window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
                }
                else if (window.webkitRequestAnimationFrame) {
                    window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
                }
            }
        };
        // This function is called only on Chrome, which does not yet support
        // connection/disconnection events, but requires you to monitor
        // an array for changes.
        Gamepads.prototype._updateGamepadObjects = function () {
            var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
            for (var i = 0; i < gamepads.length; i++) {
                if (gamepads[i]) {
                    if (!(gamepads[i].index in this.babylonGamepads)) {
                        var newGamepad = this._addNewGamepad(gamepads[i]);
                        if (this._callbackGamepadConnected) {
                            this._callbackGamepadConnected(newGamepad);
                        }
                    }
                    else {
                        this.babylonGamepads[i].browserGamepad = gamepads[i];
                    }
                }
            }
        };
        return Gamepads;
    }());
    BABYLON.Gamepads = Gamepads;
    var StickValues = (function () {
        function StickValues(x, y) {
            this.x = x;
            this.y = y;
        }
        return StickValues;
    }());
    BABYLON.StickValues = StickValues;
    var Gamepad = (function () {
        function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
            if (leftStickX === void 0) { leftStickX = 0; }
            if (leftStickY === void 0) { leftStickY = 1; }
            if (rightStickX === void 0) { rightStickX = 2; }
            if (rightStickY === void 0) { rightStickY = 3; }
            this.id = id;
            this.index = index;
            this.browserGamepad = browserGamepad;
            this._leftStickAxisX = leftStickX;
            this._leftStickAxisY = leftStickY;
            this._rightStickAxisX = rightStickX;
            this._rightStickAxisY = rightStickY;
            if (this.browserGamepad.axes.length >= 2) {
                this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
            }
            if (this.browserGamepad.axes.length >= 4) {
                this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
            }
        }
        Gamepad.prototype.onleftstickchanged = function (callback) {
            this._onleftstickchanged = callback;
        };
        Gamepad.prototype.onrightstickchanged = function (callback) {
            this._onrightstickchanged = callback;
        };
        Object.defineProperty(Gamepad.prototype, "leftStick", {
            get: function () {
                return this._leftStick;
            },
            set: function (newValues) {
                if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
                    this._onleftstickchanged(newValues);
                }
                this._leftStick = newValues;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Gamepad.prototype, "rightStick", {
            get: function () {
                return this._rightStick;
            },
            set: function (newValues) {
                if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
                    this._onrightstickchanged(newValues);
                }
                this._rightStick = newValues;
            },
            enumerable: true,
            configurable: true
        });
        Gamepad.prototype.update = function () {
            if (this._leftStick) {
                this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
            }
            if (this._rightStick) {
                this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
            }
        };
        return Gamepad;
    }());
    BABYLON.Gamepad = Gamepad;
    var GenericPad = (function (_super) {
        __extends(GenericPad, _super);
        function GenericPad(id, index, gamepad) {
            _super.call(this, id, index, gamepad);
            this.id = id;
            this.index = index;
            this.gamepad = gamepad;
            this._buttons = new Array(gamepad.buttons.length);
        }
        GenericPad.prototype.onbuttondown = function (callback) {
            this._onbuttondown = callback;
        };
        GenericPad.prototype.onbuttonup = function (callback) {
            this._onbuttonup = callback;
        };
        GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
            if (newValue !== currentValue) {
                if (this._onbuttondown && newValue === 1) {
                    this._onbuttondown(buttonIndex);
                }
                if (this._onbuttonup && newValue === 0) {
                    this._onbuttonup(buttonIndex);
                }
            }
            return newValue;
        };
        GenericPad.prototype.update = function () {
            _super.prototype.update.call(this);
            for (var index = 0; index < this._buttons.length; index++) {
                this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
            }
        };
        return GenericPad;
    }(Gamepad));
    BABYLON.GenericPad = GenericPad;
    (function (Xbox360Button) {
        Xbox360Button[Xbox360Button["A"] = 0] = "A";
        Xbox360Button[Xbox360Button["B"] = 1] = "B";
        Xbox360Button[Xbox360Button["X"] = 2] = "X";
        Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
        Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
        Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
        Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
        Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
        Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
        Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
    })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
    var Xbox360Button = BABYLON.Xbox360Button;
    (function (Xbox360Dpad) {
        Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
        Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
        Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
        Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
    })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
    var Xbox360Dpad = BABYLON.Xbox360Dpad;
    var Xbox360Pad = (function (_super) {
        __extends(Xbox360Pad, _super);
        function Xbox360Pad(id, index, gamepad, xboxOne) {
            if (xboxOne === void 0) { xboxOne = false; }
            _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3));
            this._leftTrigger = 0;
            this._rightTrigger = 0;
            this._buttonA = 0;
            this._buttonB = 0;
            this._buttonX = 0;
            this._buttonY = 0;
            this._buttonBack = 0;
            this._buttonStart = 0;
            this._buttonLB = 0;
            this._buttonRB = 0;
            this._buttonLeftStick = 0;
            this._buttonRightStick = 0;
            this._dPadUp = 0;
            this._dPadDown = 0;
            this._dPadLeft = 0;
            this._dPadRight = 0;
            this._isXboxOnePad = false;
            this._isXboxOnePad = xboxOne;
        }
        Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
            this._onlefttriggerchanged = callback;
        };
        Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
            this._onrighttriggerchanged = callback;
        };
        Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
            get: function () {
                return this._leftTrigger;
            },
            set: function (newValue) {
                if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
                    this._onlefttriggerchanged(newValue);
                }
                this._leftTrigger = newValue;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
            get: function () {
                return this._rightTrigger;
            },
            set: function (newValue) {
                if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
                    this._onrighttriggerchanged(newValue);
                }
                this._rightTrigger = newValue;
            },
            enumerable: true,
            configurable: true
        });
        Xbox360Pad.prototype.onbuttondown = function (callback) {
            this._onbuttondown = callback;
        };
        Xbox360Pad.prototype.onbuttonup = function (callback) {
            this._onbuttonup = callback;
        };
        Xbox360Pad.prototype.ondpaddown = function (callback) {
            this._ondpaddown = callback;
        };
        Xbox360Pad.prototype.ondpadup = function (callback) {
            this._ondpadup = callback;
        };
        Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
            if (newValue !== currentValue) {
                if (this._onbuttondown && newValue === 1) {
                    this._onbuttondown(buttonType);
                }
                if (this._onbuttonup && newValue === 0) {
                    this._onbuttonup(buttonType);
                }
            }
            return newValue;
        };
        Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
            if (newValue !== currentValue) {
                if (this._ondpaddown && newValue === 1) {
                    this._ondpaddown(buttonType);
                }
                if (this._ondpadup && newValue === 0) {
                    this._ondpadup(buttonType);
                }
            }
            return newValue;
        };
        Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
            get: function () {
                return this._buttonA;
            },
            set: function (value) {
                this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
            get: function () {
                return this._buttonB;
            },
            set: function (value) {
                this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
            get: function () {
                return this._buttonX;
            },
            set: function (value) {
                this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
            get: function () {
                return this._buttonY;
            },
            set: function (value) {
                this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
            get: function () {
                return this._buttonStart;
            },
            set: function (value) {
                this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
            get: function () {
                return this._buttonBack;
            },
            set: function (value) {
                this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
            get: function () {
                return this._buttonLB;
            },
            set: function (value) {
                this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
            get: function () {
                return this._buttonRB;
            },
            set: function (value) {
                this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
            get: function () {
                return this._buttonLeftStick;
            },
            set: function (value) {
                this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
            get: function () {
                return this._buttonRightStick;
            },
            set: function (value) {
                this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
            get: function () {
                return this._dPadUp;
            },
            set: function (value) {
                this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
            get: function () {
                return this._dPadDown;
            },
            set: function (value) {
                this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
            get: function () {
                return this._dPadLeft;
            },
            set: function (value) {
                this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
            get: function () {
                return this._dPadRight;
            },
            set: function (value) {
                this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
            },
            enumerable: true,
            configurable: true
        });
        Xbox360Pad.prototype.update = function () {
            _super.prototype.update.call(this);
            if (this._isXboxOnePad) {
                this.buttonA = this.browserGamepad.buttons[0].value;
                this.buttonB = this.browserGamepad.buttons[1].value;
                this.buttonX = this.browserGamepad.buttons[2].value;
                this.buttonY = this.browserGamepad.buttons[3].value;
                this.buttonLB = this.browserGamepad.buttons[4].value;
                this.buttonRB = this.browserGamepad.buttons[5].value;
                this.leftTrigger = this.browserGamepad.axes[2];
                this.rightTrigger = this.browserGamepad.axes[5];
                this.buttonBack = this.browserGamepad.buttons[9].value;
                this.buttonStart = this.browserGamepad.buttons[8].value;
                this.buttonLeftStick = this.browserGamepad.buttons[6].value;
                this.buttonRightStick = this.browserGamepad.buttons[7].value;
                this.dPadUp = this.browserGamepad.buttons[11].value;
                this.dPadDown = this.browserGamepad.buttons[12].value;
                this.dPadLeft = this.browserGamepad.buttons[13].value;
                this.dPadRight = this.browserGamepad.buttons[14].value;
            }
            else {
                this.buttonA = this.browserGamepad.buttons[0].value;
                this.buttonB = this.browserGamepad.buttons[1].value;
                this.buttonX = this.browserGamepad.buttons[2].value;
                this.buttonY = this.browserGamepad.buttons[3].value;
                this.buttonLB = this.browserGamepad.buttons[4].value;
                this.buttonRB = this.browserGamepad.buttons[5].value;
                this.leftTrigger = this.browserGamepad.buttons[6].value;
                this.rightTrigger = this.browserGamepad.buttons[7].value;
                this.buttonBack = this.browserGamepad.buttons[8].value;
                this.buttonStart = this.browserGamepad.buttons[9].value;
                this.buttonLeftStick = this.browserGamepad.buttons[10].value;
                this.buttonRightStick = this.browserGamepad.buttons[11].value;
                this.dPadUp = this.browserGamepad.buttons[12].value;
                this.dPadDown = this.browserGamepad.buttons[13].value;
                this.dPadLeft = this.browserGamepad.buttons[14].value;
                this.dPadRight = this.browserGamepad.buttons[15].value;
            }
        };
        return Xbox360Pad;
    }(Gamepad));
    BABYLON.Xbox360Pad = Xbox360Pad;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.gamepads.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // We're mainly based on the logic defined into the FreeCamera code
    var GamepadCamera = (function (_super) {
        __extends(GamepadCamera, _super);
        //-- end properties for backward compatibility for inputs
        function GamepadCamera(name, position, scene) {
            BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
            _super.call(this, name, position, scene);
        }
        Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
            //-- Begin properties for backward compatibility for inputs
            get: function () {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    return gamepad.gamepadAngularSensibility;
            },
            set: function (value) {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    gamepad.gamepadAngularSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
            get: function () {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    return gamepad.gamepadMoveSensibility;
            },
            set: function (value) {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad)
                    gamepad.gamepadMoveSensibility = value;
            },
            enumerable: true,
            configurable: true
        });
        GamepadCamera.prototype.getTypeName = function () {
            return "GamepadCamera";
        };
        return GamepadCamera;
    }(BABYLON.UniversalCamera));
    BABYLON.GamepadCamera = GamepadCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.gamepadCamera.js.map
 
var BABYLON;
(function (BABYLON) {
    var Analyser = (function () {
        function Analyser(scene) {
            this.SMOOTHING = 0.75;
            this.FFT_SIZE = 512;
            this.BARGRAPHAMPLITUDE = 256;
            this.DEBUGCANVASPOS = { x: 20, y: 20 };
            this.DEBUGCANVASSIZE = { width: 320, height: 200 };
            this._scene = scene;
            this._audioEngine = BABYLON.Engine.audioEngine;
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
                this._webAudioAnalyser.minDecibels = -140;
                this._webAudioAnalyser.maxDecibels = 0;
                this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
                this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
                this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
            }
        }
        Analyser.prototype.getFrequencyBinCount = function () {
            if (this._audioEngine.canUseWebAudio) {
                return this._webAudioAnalyser.frequencyBinCount;
            }
            else {
                return 0;
            }
        };
        Analyser.prototype.getByteFrequencyData = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
                this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
            }
            return this._byteFreqs;
        };
        Analyser.prototype.getByteTimeDomainData = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
                this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
            }
            return this._byteTime;
        };
        Analyser.prototype.getFloatFrequencyData = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
                this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
            }
            return this._floatFreqs;
        };
        Analyser.prototype.drawDebugCanvas = function () {
            var _this = this;
            if (this._audioEngine.canUseWebAudio) {
                if (!this._debugCanvas) {
                    this._debugCanvas = document.createElement("canvas");
                    this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
                    this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
                    this._debugCanvas.style.position = "absolute";
                    this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
                    this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
                    this._debugCanvasContext = this._debugCanvas.getContext("2d");
                    document.body.appendChild(this._debugCanvas);
                    this._registerFunc = function () {
                        _this.drawDebugCanvas();
                    };
                    this._scene.registerBeforeRender(this._registerFunc);
                }
                if (this._registerFunc) {
                    var workingArray = this.getByteFrequencyData();
                    this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
                    this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
                    // Draw the frequency domain chart.
                    for (var i = 0; i < this.getFrequencyBinCount(); i++) {
                        var value = workingArray[i];
                        var percent = value / this.BARGRAPHAMPLITUDE;
                        var height = this.DEBUGCANVASSIZE.height * percent;
                        var offset = this.DEBUGCANVASSIZE.height - height - 1;
                        var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
                        var hue = i / this.getFrequencyBinCount() * 360;
                        this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
                        this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
                    }
                }
            }
        };
        Analyser.prototype.stopDebugCanvas = function () {
            if (this._debugCanvas) {
                this._scene.unregisterBeforeRender(this._registerFunc);
                this._registerFunc = null;
                document.body.removeChild(this._debugCanvas);
                this._debugCanvas = null;
                this._debugCanvasContext = null;
            }
        };
        Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
            if (this._audioEngine.canUseWebAudio) {
                inputAudioNode.connect(this._webAudioAnalyser);
                this._webAudioAnalyser.connect(outputAudioNode);
            }
        };
        Analyser.prototype.dispose = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.disconnect();
            }
        };
        return Analyser;
    }());
    BABYLON.Analyser = Analyser;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.analyser.js.map
 
var BABYLON;
(function (BABYLON) {
    var DepthRenderer = (function () {
        function DepthRenderer(scene, type) {
            var _this = this;
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
            this._viewMatrix = BABYLON.Matrix.Zero();
            this._projectionMatrix = BABYLON.Matrix.Zero();
            this._transformMatrix = BABYLON.Matrix.Zero();
            this._worldViewProjection = BABYLON.Matrix.Zero();
            this._scene = scene;
            var engine = scene.getEngine();
            // Render target
            this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
            this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._depthMap.refreshRate = 1;
            this._depthMap.renderParticles = false;
            this._depthMap.renderList = null;
            // set default depth value to 1.0 (far away)
            this._depthMap.onClearObservable.add(function (engine) {
                engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
            });
            // Custom render function
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                var scene = _this._scene;
                var engine = scene.getEngine();
                // Culling
                engine.setState(subMesh.getMaterial().backFaceCulling);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
                    engine.enableEffect(_this._effect);
                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
                    var material = subMesh.getMaterial();
                    _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
                    _this._effect.setFloat("far", scene.activeCamera.maxZ);
                    // Alpha test
                    if (material && material.needAlphaTesting()) {
                        var alphaTexture = material.getAlphaTestTexture();
                        _this._effect.setTexture("diffuseSampler", alphaTexture);
                        _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                    }
                    // Bones
                    if (mesh.useBones && mesh.computeBonesUsingShaders) {
                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
                }
            };
            this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
                var index;
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
            };
        }
        DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
            var material = subMesh.getMaterial();
            if (material.disableDepthWrite) {
                return false;
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var mesh = subMesh.getMesh();
            var scene = mesh.getScene();
            // Alpha test
            if (material && material.needAlphaTesting()) {
                defines.push("#define ALPHATEST");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                    defines.push("#define UV2");
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Instances
            if (useInstances) {
                defines.push("#define INSTANCES");
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
            // Get correct effect      
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
            }
            return this._effect.isReady();
        };
        DepthRenderer.prototype.getDepthMap = function () {
            return this._depthMap;
        };
        // Methods
        DepthRenderer.prototype.dispose = function () {
            this._depthMap.dispose();
        };
        return DepthRenderer;
    }());
    BABYLON.DepthRenderer = DepthRenderer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.depthRenderer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var SSAORenderingPipeline = (function (_super) {
        __extends(SSAORenderingPipeline, _super);
        /**
         * @constructor
         * @param {string} name - The rendering pipeline name
         * @param {BABYLON.Scene} scene - The scene linked to this pipeline
         * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
         * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
         */
        function SSAORenderingPipeline(name, scene, ratio, cameras) {
            var _this = this;
            _super.call(this, scene.getEngine(), name);
            // Members
            /**
            * The PassPostProcess id in the pipeline that contains the original scene color
            * @type {string}
            */
            this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
            /**
            * The SSAO PostProcess id in the pipeline
            * @type {string}
            */
            this.SSAORenderEffect = "SSAORenderEffect";
            /**
            * The horizontal blur PostProcess id in the pipeline
            * @type {string}
            */
            this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
            /**
            * The vertical blur PostProcess id in the pipeline
            * @type {string}
            */
            this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
            /**
            * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
            * @type {string}
            */
            this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
            /**
            * The output strength of the SSAO post-process. Default value is 1.0.
            * @type {number}
            */
            this.totalStrength = 1.0;
            /**
            * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
            * @type {number}
            */
            this.radius = 0.0001;
            /**
            * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
            * Must not be equal to fallOff and superior to fallOff.
            * Default value is 0.975
            * @type {number}
            */
            this.area = 0.0075;
            /**
            * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
            * Must not be equal to area and inferior to area.
            * Default value is 0.0
            * @type {number}
            */
            this.fallOff = 0.000001;
            /**
            * The base color of the SSAO post-process
            * The final result is "base + ssao" between [0, 1]
            * @type {number}
            */
            this.base = 0.5;
            this._firstUpdate = true;
            this._scene = scene;
            // Set up assets
            this._createRandomTexture();
            this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
            var ssaoRatio = ratio.ssaoRatio || ratio;
            var combineRatio = ratio.combineRatio || ratio;
            this._ratio = {
                ssaoRatio: ssaoRatio,
                combineRatio: combineRatio
            };
            this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
            this._createSSAOPostProcess(ssaoRatio);
            this._createBlurPostProcess(ssaoRatio);
            this._createSSAOCombinePostProcess(combineRatio);
            // Set up pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(this);
            if (cameras)
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
        }
        // Public Methods
        /**
         * Returns the horizontal blur PostProcess
         * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
         */
        SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
            BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
            return null;
        };
        /**
         * Returns the vertical blur PostProcess
         * @return {BABYLON.BlurPostProcess} The vertical blur post-process
         */
        SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
            BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
            return null;
        };
        /**
         * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
         */
        SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
            if (disableDepthRender === void 0) { disableDepthRender = false; }
            for (var i = 0; i < this._scene.cameras.length; i++) {
                var camera = this._scene.cameras[i];
                this._originalColorPostProcess.dispose(camera);
                this._ssaoPostProcess.dispose(camera);
                this._blurHPostProcess.dispose(camera);
                this._blurVPostProcess.dispose(camera);
                this._ssaoCombinePostProcess.dispose(camera);
            }
            this._randomTexture.dispose();
            if (disableDepthRender)
                this._scene.disableDepthRenderer();
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
        };
        // Private Methods
        SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
            var _this = this;
            /*
            var samplerOffsets = [
                -8.0, -6.0, -4.0, -2.0,
                0.0,
                2.0, 4.0, 6.0, 8.0
            ];
            */
            var samples = 16;
            var samplerOffsets = [];
            for (var i = -8; i < 8; i++) {
                samplerOffsets.push(i * 2);
            }
            this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
            this._blurHPostProcess.onApply = function (effect) {
                effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
                effect.setTexture("depthSampler", _this._depthTexture);
                if (_this._firstUpdate) {
                    effect.setArray("samplerOffsets", samplerOffsets);
                }
            };
            this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
            this._blurVPostProcess.onApply = function (effect) {
                effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
                effect.setTexture("depthSampler", _this._depthTexture);
                if (_this._firstUpdate) {
                    effect.setArray("samplerOffsets", samplerOffsets);
                    _this._firstUpdate = false;
                }
            };
        };
        SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
            var _this = this;
            var numSamples = 16;
            var sampleSphere = [
                0.5381, 0.1856, -0.4319,
                0.1379, 0.2486, 0.4430,
                0.3371, 0.5679, -0.0057,
                -0.6999, -0.0451, -0.0019,
                0.0689, -0.1598, -0.8547,
                0.0560, 0.0069, -0.1843,
                -0.0146, 0.1402, 0.0762,
                0.0100, -0.1924, -0.0344,
                -0.3577, -0.5301, -0.4358,
                -0.3169, 0.1063, 0.0158,
                0.0103, -0.5869, 0.0046,
                -0.0897, -0.4940, 0.3287,
                0.7119, -0.0154, -0.0918,
                -0.0533, 0.0596, -0.5411,
                0.0352, -0.0631, 0.5460,
                -0.4776, 0.2847, -0.0271
            ];
            var samplesFactor = 1.0 / numSamples;
            this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
                "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
                "area", "fallOff", "base", "range", "viewport"
            ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
            var viewport = new BABYLON.Vector2(0, 0);
            this._ssaoPostProcess.onApply = function (effect) {
                if (_this._firstUpdate) {
                    effect.setArray3("sampleSphere", sampleSphere);
                    effect.setFloat("samplesFactor", samplesFactor);
                    effect.setFloat("randTextureTiles", 4.0);
                }
                effect.setFloat("totalStrength", _this.totalStrength);
                effect.setFloat("radius", _this.radius);
                effect.setFloat("area", _this.area);
                effect.setFloat("fallOff", _this.fallOff);
                effect.setFloat("base", _this.base);
                effect.setTexture("textureSampler", _this._depthTexture);
                effect.setTexture("randomSampler", _this._randomTexture);
            };
        };
        SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
            var _this = this;
            this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._ssaoCombinePostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
            };
        };
        SSAORenderingPipeline.prototype._createRandomTexture = function () {
            var size = 512;
            this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            var context = this._randomTexture.getContext();
            var rand = function (min, max) {
                return Math.random() * (max - min) + min;
            };
            var randVector = BABYLON.Vector3.Zero();
            for (var x = 0; x < size; x++) {
                for (var y = 0; y < size; y++) {
                    randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
                    randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
                    randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
                    context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
                    context.fillRect(x, y, 1, 1);
                }
            }
            this._randomTexture.update(false);
        };
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "radius", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "area", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "fallOff", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "base", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "_ratio", void 0);
        return SSAORenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
    var VolumetricLightScatteringPostProcess = (function (_super) {
        __extends(VolumetricLightScatteringPostProcess, _super);
        /**
         * @constructor
         * @param {string} name - The post-process name
         * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
         * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
         * @param {number} samples - The post-process quality, default 100
         * @param {number} samplingMode - The post-process filtering mode
         * @param {BABYLON.Engine} engine - The babylon engine
         * @param {boolean} reusable - If the post-process is reusable
         * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
         */
        function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
            var _this = this;
            if (samples === void 0) { samples = 100; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
            this._screenCoordinates = BABYLON.Vector2.Zero();
            /**
            * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
            * @type {Vector3}
            */
            this.customMeshPosition = BABYLON.Vector3.Zero();
            /**
            * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
            * @type {boolean}
            */
            this.useCustomMeshPosition = false;
            /**
            * If the post-process should inverse the light scattering direction
            * @type {boolean}
            */
            this.invert = true;
            /**
            * Array containing the excluded meshes not rendered in the internal pass
            */
            this.excludedMeshes = new Array();
            /**
            * Controls the overall intensity of the post-process
            * @type {number}
            */
            this.exposure = 0.3;
            /**
            * Dissipates each sample's contribution in range [0, 1]
            * @type {number}
            */
            this.decay = 0.96815;
            /**
            * Controls the overall intensity of each sample
            * @type {number}
            */
            this.weight = 0.58767;
            /**
            * Controls the density of each sample
            * @type {number}
            */
            this.density = 0.926;
            scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
            var engine = scene.getEngine();
            this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            // Configure mesh
            this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
            // Configure
            this._createPass(scene, ratio.passRatio || ratio);
            this.onActivate = function (camera) {
                if (!_this.isSupported) {
                    _this.dispose(camera);
                }
                _this.onActivate = null;
            };
            this.onApplyObservable.add(function (effect) {
                _this._updateMeshScreenCoordinates(scene);
                effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
                effect.setFloat("exposure", _this.exposure);
                effect.setFloat("decay", _this.decay);
                effect.setFloat("weight", _this.weight);
                effect.setFloat("density", _this.density);
                effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
            });
        }
        Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
            get: function () {
                BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
                return false;
            },
            set: function (useDiffuseColor) {
                BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
            },
            enumerable: true,
            configurable: true
        });
        VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
            var mesh = subMesh.getMesh();
            // Render this.mesh as default
            if (mesh === this.mesh) {
                return mesh.material.isReady(mesh);
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var material = subMesh.getMaterial();
            var needUV = false;
            // Alpha test
            if (material) {
                if (material.needAlphaTesting()) {
                    defines.push("#define ALPHATEST");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                    defines.push("#define UV2");
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Instances
            if (useInstances) {
                defines.push("#define INSTANCES");
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
            // Get correct effect      
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
            }
            return this._volumetricLightScatteringPass.isReady();
        };
        /**
         * Sets the new light position for light scattering effect
         * @param {BABYLON.Vector3} The new custom light position
         */
        VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
            this.customMeshPosition = position;
        };
        /**
         * Returns the light position for light scattering effect
         * @return {BABYLON.Vector3} The custom light position
         */
        VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
            return this.customMeshPosition;
        };
        /**
         * Disposes the internal assets and detaches the post-process from the camera
         */
        VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
            var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
            if (rttIndex !== -1) {
                camera.getScene().customRenderTargets.splice(rttIndex, 1);
            }
            this._volumetricLightScatteringRTT.dispose();
            _super.prototype.dispose.call(this, camera);
        };
        /**
         * Returns the render target texture used by the post-process
         * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
         */
        VolumetricLightScatteringPostProcess.prototype.getPass = function () {
            return this._volumetricLightScatteringRTT;
        };
        // Private methods
        VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
                return true;
            }
            return false;
        };
        VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
            var _this = this;
            var engine = scene.getEngine();
            this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._volumetricLightScatteringRTT.renderList = null;
            this._volumetricLightScatteringRTT.renderParticles = false;
            scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
            // Custom render function for submeshes
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                if (_this._meshExcluded(mesh)) {
                    return;
                }
                var scene = mesh.getScene();
                var engine = scene.getEngine();
                // Culling
                engine.setState(subMesh.getMaterial().backFaceCulling);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
                    var effect = _this._volumetricLightScatteringPass;
                    if (mesh === _this.mesh) {
                        effect = subMesh.getMaterial().getEffect();
                    }
                    engine.enableEffect(effect);
                    mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
                    if (mesh === _this.mesh) {
                        subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
                    }
                    else {
                        var material = subMesh.getMaterial();
                        _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
                        // Alpha test
                        if (material && material.needAlphaTesting()) {
                            var alphaTexture = material.getAlphaTestTexture();
                            _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
                            if (alphaTexture) {
                                _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                            }
                        }
                        // Bones
                        if (mesh.useBones && mesh.computeBonesUsingShaders) {
                            _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                        }
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
                }
            };
            // Render target texture callbacks
            var savedSceneClearColor;
            var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
            this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
                savedSceneClearColor = scene.clearColor;
                scene.clearColor = sceneClearColor;
            });
            this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
                scene.clearColor = savedSceneClearColor;
            });
            this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
                var engine = scene.getEngine();
                var index;
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                engine.setAlphaTesting(true);
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
                engine.setAlphaTesting(false);
                if (transparentSubMeshes.length) {
                    // Sort sub meshes
                    for (index = 0; index < transparentSubMeshes.length; index++) {
                        var submesh = transparentSubMeshes.data[index];
                        submesh._alphaIndex = submesh.getMesh().alphaIndex;
                        submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
                    }
                    var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
                    sortedArray.sort(function (a, b) {
                        // Alpha index first
                        if (a._alphaIndex > b._alphaIndex) {
                            return 1;
                        }
                        if (a._alphaIndex < b._alphaIndex) {
                            return -1;
                        }
                        // Then distance to camera
                        if (a._distanceToCamera < b._distanceToCamera) {
                            return 1;
                        }
                        if (a._distanceToCamera > b._distanceToCamera) {
                            return -1;
                        }
                        return 0;
                    });
                    // Render sub meshes
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                    for (index = 0; index < sortedArray.length; index++) {
                        renderSubMesh(sortedArray[index]);
                    }
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
                }
            };
        };
        VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
            var transform = scene.getTransformMatrix();
            var meshPosition;
            if (this.useCustomMeshPosition) {
                meshPosition = this.customMeshPosition;
            }
            else if (this.attachedNode) {
                meshPosition = this.attachedNode.position;
            }
            else {
                meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
            }
            var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
            this._screenCoordinates.x = pos.x / this._viewPort.width;
            this._screenCoordinates.y = pos.y / this._viewPort.height;
            if (this.invert)
                this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
        };
        // Static methods
        /**
        * Creates a default mesh for the Volumeric Light Scattering post-process
        * @param {string} The mesh name
        * @param {BABYLON.Scene} The scene where to create the mesh
        * @return {BABYLON.Mesh} the default mesh
        */
        VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
            var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
            mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
            var material = new BABYLON.StandardMaterial(name + "Material", scene);
            material.emissiveColor = new BABYLON.Color3(1, 1, 1);
            mesh.material = material;
            return mesh;
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
        __decorate([
            BABYLON.serializeAsMeshReference()
        ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
        return VolumetricLightScatteringPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
 
// BABYLON.JS Chromatic Aberration GLSL Shader
// Author: Olivier Guyot
// Separates very slightly R, G and B colors on the edges of the screen
// Inspired by Francois Tarlier & Martins Upitis
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var LensRenderingPipeline = (function (_super) {
        __extends(LensRenderingPipeline, _super);
        /**
         * @constructor
         *
         * Effect parameters are as follow:
         * {
         *      chromatic_aberration: number;       // from 0 to x (1 for realism)
         *      edge_blur: number;                  // from 0 to x (1 for realism)
         *      distortion: number;                 // from 0 to x (1 for realism)
         *      grain_amount: number;               // from 0 to 1
         *      grain_texture: BABYLON.Texture;     // texture to use for grain effect; if unset, use random B&W noise
         *      dof_focus_distance: number;         // depth-of-field: focus distance; unset to disable (disabled by default)
         *      dof_aperture: number;               // depth-of-field: focus blur bias (default: 1)
         *      dof_darken: number;                 // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
         *      dof_pentagon: boolean;              // depth-of-field: makes a pentagon-like "bokeh" effect
         *      dof_gain: number;                   // depth-of-field: highlights gain; unset to disable (disabled by default)
         *      dof_threshold: number;              // depth-of-field: highlights threshold (default: 1)
         *      blur_noise: boolean;                // add a little bit of noise to the blur (default: true)
         * }
         * Note: if an effect parameter is unset, effect is disabled
         *
         * @param {string} name - The rendering pipeline name
         * @param {object} parameters - An object containing all parameters (see above)
         * @param {BABYLON.Scene} scene - The scene linked to this pipeline
         * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
         */
        function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
            var _this = this;
            if (ratio === void 0) { ratio = 1.0; }
            _super.call(this, scene.getEngine(), name);
            // Lens effects can be of the following:
            // - chromatic aberration (slight shift of RGB colors)
            // - blur on the edge of the lens
            // - lens distortion
            // - depth-of-field blur & highlights enhancing
            // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
            // - grain effect (noise or custom texture)
            // Two additional texture samplers are needed:
            // - depth map (for depth-of-field)
            // - grain texture
            /**
            * The chromatic aberration PostProcess id in the pipeline
            * @type {string}
            */
            this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
            /**
            * The highlights enhancing PostProcess id in the pipeline
            * @type {string}
            */
            this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
            /**
            * The depth-of-field PostProcess id in the pipeline
            * @type {string}
            */
            this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
            this._scene = scene;
            // Fetch texture samplers
            this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
            if (parameters.grain_texture) {
                this._grainTexture = parameters.grain_texture;
            }
            else {
                this._createGrainTexture();
            }
            // save parameters
            this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
            this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
            this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
            this._distortion = parameters.distortion ? parameters.distortion : 0;
            this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
            this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
            this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
            this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
            this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
            this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
            this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
            // Create effects
            this._createChromaticAberrationPostProcess(ratio);
            this._createHighlightsPostProcess(ratio);
            this._createDepthOfFieldPostProcess(ratio / 4);
            // Set up pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
            if (this._highlightsGain === -1) {
                this._disableEffect(this.HighlightsEnhancingEffect, null);
            }
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(this);
            if (cameras) {
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
            }
        }
        // public methods (self explanatory)
        LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
        LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
        LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
        LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
        LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
        LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
        LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
        LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
        LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
        LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
        LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
        LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
        LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
            this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
        };
        LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
            this._highlightsPostProcess.updateEffect();
        };
        LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
        LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
        LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
            this._highlightsGain = amount;
        };
        LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
            if (this._highlightsGain === -1) {
                this._highlightsGain = 1.0;
            }
            this._highlightsThreshold = amount;
        };
        LensRenderingPipeline.prototype.disableHighlights = function () {
            this._highlightsGain = -1;
        };
        /**
         * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
         */
        LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
            if (disableDepthRender === void 0) { disableDepthRender = false; }
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
            this._chromaticAberrationPostProcess = undefined;
            this._highlightsPostProcess = undefined;
            this._depthOfFieldPostProcess = undefined;
            this._grainTexture.dispose();
            if (disableDepthRender)
                this._scene.disableDepthRenderer();
        };
        // colors shifting and distortion
        LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
            var _this = this;
            this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
            [], // samplers
            ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._chromaticAberrationPostProcess.onApply = function (effect) {
                effect.setFloat('chromatic_aberration', _this._chromaticAberration);
                effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
                effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
            };
        };
        // highlights enhancing
        LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
            var _this = this;
            this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
            [], // samplers
            ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
            this._highlightsPostProcess.onApply = function (effect) {
                effect.setFloat('gain', _this._highlightsGain);
                effect.setFloat('threshold', _this._highlightsThreshold);
                effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
                effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
                effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
            };
        };
        // colors shifting and distortion
        LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
            var _this = this;
            this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
                "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
                "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
            ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._depthOfFieldPostProcess.onApply = function (effect) {
                effect.setTexture("depthSampler", _this._depthTexture);
                effect.setTexture("grainSampler", _this._grainTexture);
                effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
                effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
                effect.setFloat('grain_amount', _this._grainAmount);
                effect.setBool('blur_noise', _this._blurNoise);
                effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
                effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
                effect.setFloat('distortion', _this._distortion);
                effect.setBool('dof_enabled', (_this._dofDistance !== -1));
                effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
                effect.setFloat('aperture', _this._dofAperture);
                effect.setFloat('darken', _this._dofDarken);
                effect.setFloat('edge_blur', _this._edgeBlur);
                effect.setBool('highlights', (_this._highlightsGain !== -1));
                effect.setFloat('near', _this._scene.activeCamera.minZ);
                effect.setFloat('far', _this._scene.activeCamera.maxZ);
            };
        };
        // creates a black and white random noise texture, 512x512
        LensRenderingPipeline.prototype._createGrainTexture = function () {
            var size = 512;
            this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            var context = this._grainTexture.getContext();
            var rand = function (min, max) {
                return Math.random() * (max - min) + min;
            };
            var value;
            for (var x = 0; x < size; x++) {
                for (var y = 0; y < size; y++) {
                    value = Math.floor(rand(0.42, 0.58) * 255);
                    context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
                    context.fillRect(x, y, 1, 1);
                }
            }
            this._grainTexture.update(false);
        };
        return LensRenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.LensRenderingPipeline = LensRenderingPipeline;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.lensRenderingPipeline.js.map
 
//
//  This post-process allows the modification of rendered colors by using
//  a 'look-up table' (LUT). This effect is also called Color Grading.
// 
//  The object needs to be provided an url to a texture containing the color
//  look-up table: the texture must be 256 pixels wide and 16 pixels high.
//  Use an image editing software to tweak the LUT to match your needs.
// 
//  For an example of a color LUT, see here:
//      http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
//  For explanations on color grading, see here:
//      http://udn.epicgames.com/Three/ColorGrading.html
//
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var ColorCorrectionPostProcess = (function (_super) {
        __extends(ColorCorrectionPostProcess, _super);
        function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
            var _this = this;
            _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
            this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            this._colorTableTexture.anisotropicFilteringLevel = 1;
            this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.onApply = function (effect) {
                effect.setTexture("colorTable", _this._colorTableTexture);
            };
        }
        return ColorCorrectionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var AnaglyphFreeCamera = (function (_super) {
        __extends(AnaglyphFreeCamera, _super);
        function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
            _super.call(this, name, position, scene);
            this.interaxialDistance = interaxialDistance;
            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
        }
        AnaglyphFreeCamera.prototype.getTypeName = function () {
            return "AnaglyphFreeCamera";
        };
        return AnaglyphFreeCamera;
    }(BABYLON.FreeCamera));
    BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
    var AnaglyphArcRotateCamera = (function (_super) {
        __extends(AnaglyphArcRotateCamera, _super);
        function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
            _super.call(this, name, alpha, beta, radius, target, scene);
            this.interaxialDistance = interaxialDistance;
            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
        }
        AnaglyphArcRotateCamera.prototype.getTypeName = function () {
            return "AnaglyphArcRotateCamera";
        };
        return AnaglyphArcRotateCamera;
    }(BABYLON.ArcRotateCamera));
    BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
    var AnaglyphGamepadCamera = (function (_super) {
        __extends(AnaglyphGamepadCamera, _super);
        function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
            _super.call(this, name, position, scene);
            this.interaxialDistance = interaxialDistance;
            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
        }
        AnaglyphGamepadCamera.prototype.getTypeName = function () {
            return "AnaglyphGamepadCamera";
        };
        return AnaglyphGamepadCamera;
    }(BABYLON.GamepadCamera));
    BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
    var AnaglyphUniversalCamera = (function (_super) {
        __extends(AnaglyphUniversalCamera, _super);
        function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
            _super.call(this, name, position, scene);
            this.interaxialDistance = interaxialDistance;
            this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
        }
        AnaglyphUniversalCamera.prototype.getTypeName = function () {
            return "AnaglyphUniversalCamera";
        };
        return AnaglyphUniversalCamera;
    }(BABYLON.UniversalCamera));
    BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
    var StereoscopicFreeCamera = (function (_super) {
        __extends(StereoscopicFreeCamera, _super);
        function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
            _super.call(this, name, position, scene);
            this.interaxialDistance = interaxialDistance;
            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
        }
        StereoscopicFreeCamera.prototype.getTypeName = function () {
            return "StereoscopicFreeCamera";
        };
        return StereoscopicFreeCamera;
    }(BABYLON.FreeCamera));
    BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
    var StereoscopicArcRotateCamera = (function (_super) {
        __extends(StereoscopicArcRotateCamera, _super);
        function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
            _super.call(this, name, alpha, beta, radius, target, scene);
            this.interaxialDistance = interaxialDistance;
            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
        }
        StereoscopicArcRotateCamera.prototype.getTypeName = function () {
            return "StereoscopicArcRotateCamera";
        };
        return StereoscopicArcRotateCamera;
    }(BABYLON.ArcRotateCamera));
    BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
    var StereoscopicGamepadCamera = (function (_super) {
        __extends(StereoscopicGamepadCamera, _super);
        function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
            _super.call(this, name, position, scene);
            this.interaxialDistance = interaxialDistance;
            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
        }
        StereoscopicGamepadCamera.prototype.getTypeName = function () {
            return "StereoscopicGamepadCamera";
        };
        return StereoscopicGamepadCamera;
    }(BABYLON.GamepadCamera));
    BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
    var StereoscopicUniversalCamera = (function (_super) {
        __extends(StereoscopicUniversalCamera, _super);
        function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
            _super.call(this, name, position, scene);
            this.interaxialDistance = interaxialDistance;
            this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
        }
        StereoscopicUniversalCamera.prototype.getTypeName = function () {
            return "StereoscopicUniversalCamera";
        };
        return StereoscopicUniversalCamera;
    }(BABYLON.UniversalCamera));
    BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.stereoscopicCameras.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var HDRRenderingPipeline = (function (_super) {
        __extends(HDRRenderingPipeline, _super);
        /**
         * @constructor
         * @param {string} name - The rendering pipeline name
         * @param {BABYLON.Scene} scene - The scene linked to this pipeline
         * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
         * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
         */
        function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
            var _this = this;
            if (originalPostProcess === void 0) { originalPostProcess = null; }
            _super.call(this, scene.getEngine(), name);
            /**
            * Public members
            */
            // Gaussian Blur
            /**
            * Gaussian blur coefficient
            * @type {number}
            */
            this.gaussCoeff = 0.3;
            /**
            * Gaussian blur mean
            * @type {number}
            */
            this.gaussMean = 1.0;
            /**
            * Gaussian blur standard deviation
            * @type {number}
            */
            this.gaussStandDev = 0.8;
            /**
            * Gaussian blur multiplier. Multiplies the blur effect
            * @type {number}
            */
            this.gaussMultiplier = 4.0;
            // HDR
            /**
            * Exposure, controls the overall intensity of the pipeline
            * @type {number}
            */
            this.exposure = 1.0;
            /**
            * Minimum luminance that the post-process can output. Luminance is >= 0
            * @type {number}
            */
            this.minimumLuminance = 1.0;
            /**
            * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
            * @type {number}
            */
            this.maximumLuminance = 1e20;
            /**
            * Increase rate for luminance: eye adaptation speed to dark
            * @type {number}
            */
            this.luminanceIncreaserate = 0.5;
            /**
            * Decrease rate for luminance: eye adaptation speed to bright
            * @type {number}
            */
            this.luminanceDecreaseRate = 0.5;
            // Bright pass
            /**
            * Minimum luminance needed to compute HDR
            * @type {number}
            */
            this.brightThreshold = 0.8;
            this._needUpdate = true;
            this._scene = scene;
            // Bright pass
            this._createBrightPassPostProcess(scene, ratio);
            // Down sample X4
            this._createDownSampleX4PostProcess(scene, ratio);
            // Create gaussian blur post-processes
            this._createGaussianBlurPostProcess(scene, ratio);
            // Texture adder
            this._createTextureAdderPostProcess(scene, ratio);
            // Luminance generator
            this._createLuminanceGeneratorPostProcess(scene);
            // HDR
            this._createHDRPostProcess(scene, ratio);
            // Pass postprocess
            if (originalPostProcess === null) {
                this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
            }
            else {
                this._originalPostProcess = originalPostProcess;
            }
            // Configure pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
            var addDownSamplerPostProcess = function (id) {
                _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
            };
            for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
                addDownSamplerPostProcess(i);
            }
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(this);
            if (cameras !== null) {
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
            }
            this.update();
        }
        /**
        * Tells the pipeline to update its post-processes
        */
        HDRRenderingPipeline.prototype.update = function () {
            this._needUpdate = true;
        };
        /**
        * Returns the current calculated luminance
        */
        HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
            return this._hdrCurrentLuminance;
        };
        /**
        * Returns the currently drawn luminance
        */
        HDRRenderingPipeline.prototype.getOutputLuminance = function () {
            return this._hdrOutputLuminance;
        };
        /**
        * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
        */
        HDRRenderingPipeline.prototype.dispose = function () {
            this._originalPostProcess = undefined;
            this._brightPassPostProcess = undefined;
            this._downSampleX4PostProcess = undefined;
            this._guassianBlurHPostProcess = undefined;
            this._guassianBlurVPostProcess = undefined;
            this._textureAdderPostProcess = undefined;
            for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
                this._downSamplePostProcesses[i] = undefined;
            }
            this._hdrPostProcess = undefined;
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
        };
        /**
        * Creates the HDR post-process and computes the luminance adaptation
        */
        HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
            var _this = this;
            var hdrLastLuminance = 0.0;
            this._hdrOutputLuminance = -1.0;
            this._hdrCurrentLuminance = 1.0;
            this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
            this._hdrPostProcess.onApply = function (effect) {
                if (_this._hdrOutputLuminance < 0.0) {
                    _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
                }
                else {
                    var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
                    if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
                        _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
                    }
                    else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
                        _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
                    }
                    else {
                        _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
                    }
                }
                _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
                hdrLastLuminance += scene.getEngine().getDeltaTime();
                effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
                effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
                effect.setFloat("exposure", _this.exposure);
                effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
                _this._needUpdate = false;
            };
        };
        /**
        * Texture Adder post-process
        */
        HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
            var _this = this;
            this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
            this._textureAdderPostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
            };
        };
        /**
        * Down sample X4 post-process
        */
        HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
            var _this = this;
            var downSampleX4Offsets = new Array(32);
            this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
            this._downSampleX4PostProcess.onApply = function (effect) {
                if (_this._needUpdate) {
                    var id = 0;
                    for (var i = -2; i < 2; i++) {
                        for (var j = -2; j < 2; j++) {
                            downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
                            downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
                            id += 2;
                        }
                    }
                }
                effect.setArray2("dsOffsets", downSampleX4Offsets);
            };
        };
        /**
        * Bright pass post-process
        */
        HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
            var _this = this;
            var brightOffsets = new Array(8);
            var brightPassCallback = function (effect) {
                if (_this._needUpdate) {
                    var sU = (1.0 / _this._brightPassPostProcess.width);
                    var sV = (1.0 / _this._brightPassPostProcess.height);
                    brightOffsets[0] = -0.5 * sU;
                    brightOffsets[1] = 0.5 * sV;
                    brightOffsets[2] = 0.5 * sU;
                    brightOffsets[3] = 0.5 * sV;
                    brightOffsets[4] = -0.5 * sU;
                    brightOffsets[5] = -0.5 * sV;
                    brightOffsets[6] = 0.5 * sU;
                    brightOffsets[7] = -0.5 * sV;
                }
                effect.setArray2("dsOffsets", brightOffsets);
                effect.setFloat("brightThreshold", _this.brightThreshold);
            };
            this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
            this._brightPassPostProcess.onApply = brightPassCallback;
        };
        /**
        * Luminance generator. Creates the luminance post-process and down sample post-processes
        */
        HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
            var _this = this;
            var lumSteps = HDRRenderingPipeline.LUM_STEPS;
            var luminanceOffsets = new Array(8);
            var downSampleOffsets = new Array(18);
            var halfDestPixelSize;
            this._downSamplePostProcesses = new Array(lumSteps);
            // Utils for luminance
            var luminanceUpdateSourceOffsets = function (width, height) {
                var sU = (1.0 / width);
                var sV = (1.0 / height);
                luminanceOffsets[0] = -0.5 * sU;
                luminanceOffsets[1] = 0.5 * sV;
                luminanceOffsets[2] = 0.5 * sU;
                luminanceOffsets[3] = 0.5 * sV;
                luminanceOffsets[4] = -0.5 * sU;
                luminanceOffsets[5] = -0.5 * sV;
                luminanceOffsets[6] = 0.5 * sU;
                luminanceOffsets[7] = -0.5 * sV;
            };
            var luminanceUpdateDestOffsets = function (width, height) {
                var id = 0;
                for (var x = -1; x < 2; x++) {
                    for (var y = -1; y < 2; y++) {
                        downSampleOffsets[id] = (x) / width;
                        downSampleOffsets[id + 1] = (y) / height;
                        id += 2;
                    }
                }
            };
            // Luminance callback
            var luminanceCallback = function (effect) {
                if (_this._needUpdate) {
                    luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
                }
                effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
                effect.setArray2("lumOffsets", luminanceOffsets);
            };
            // Down sample callbacks
            var downSampleCallback = function (indice) {
                var i = indice;
                return function (effect) {
                    luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
                    luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
                    halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
                    effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
                    effect.setFloat("halfDestPixelSize", halfDestPixelSize);
                    effect.setArray2("dsOffsets", downSampleOffsets);
                };
            };
            var downSampleAfterRenderCallback = function (effect) {
                // Unpack result
                var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
                var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
                _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
            };
            // Create luminance post-process
            var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
            this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
            this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
            // Create down sample post-processes
            for (var i = lumSteps - 2; i >= 0; i--) {
                var length = Math.pow(3, i);
                ratio = { width: length, height: length };
                var defines = "#define DOWN_SAMPLE\n";
                if (i === 0) {
                    defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
                }
                this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
                this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
                if (i === 0) {
                    this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
                }
            }
        };
        /**
        * Gaussian blur post-processes. Horizontal and Vertical
        */
        HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
            var _this = this;
            var blurOffsetsW = new Array(9);
            var blurOffsetsH = new Array(9);
            var blurWeights = new Array(9);
            var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
            // Utils for gaussian blur
            var calculateBlurOffsets = function (height) {
                var lastOutputDimensions = {
                    width: scene.getEngine().getRenderWidth(),
                    height: scene.getEngine().getRenderHeight()
                };
                for (var i = 0; i < 9; i++) {
                    var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
                    if (height) {
                        blurOffsetsH[i] = value;
                    }
                    else {
                        blurOffsetsW[i] = value;
                    }
                }
            };
            var calculateWeights = function () {
                var x = 0.0;
                for (var i = 0; i < 9; i++) {
                    x = (i - 4.0) / 4.0;
                    blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
                }
            };
            // Callback
            var gaussianBlurCallback = function (height) {
                return function (effect) {
                    if (_this._needUpdate) {
                        calculateWeights();
                        calculateBlurOffsets(height);
                    }
                    effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
                    effect.setArray("blurWeights", blurWeights);
                    effect.setFloat("multiplier", _this.gaussMultiplier);
                };
            };
            // Create horizontal gaussian blur post-processes
            this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
            this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
            // Create vertical gaussian blur post-process
            this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
            this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
        };
        // Luminance generator
        HDRRenderingPipeline.LUM_STEPS = 6;
        return HDRRenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
 
var BABYLON;
(function (BABYLON) {
    var FaceAdjacencies = (function () {
        function FaceAdjacencies() {
            this.edges = new Array();
            this.edgesConnectedCount = 0;
        }
        return FaceAdjacencies;
    }());
    var EdgesRenderer = (function () {
        // Beware when you use this class with complex objects as the adjacencies computation can be really long
        function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
            if (epsilon === void 0) { epsilon = 0.95; }
            if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
            this.edgesWidthScalerForOrthographic = 1000.0;
            this.edgesWidthScalerForPerspective = 50.0;
            this._linesPositions = new Array();
            this._linesNormals = new Array();
            this._linesIndices = new Array();
            this._buffers = {};
            this._checkVerticesInsteadOfIndices = false;
            this._source = source;
            this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
            this._epsilon = epsilon;
            this._prepareRessources();
            this._generateEdgesLines();
        }
        EdgesRenderer.prototype._prepareRessources = function () {
            if (this._lineShader) {
                return;
            }
            this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
                attributes: ["position", "normal"],
                uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
            });
            this._lineShader.disableDepthWrite = true;
            this._lineShader.backFaceCulling = false;
        };
        EdgesRenderer.prototype.dispose = function () {
            var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer.dispose();
                this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
            if (buffer) {
                buffer.dispose();
                this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
            }
            this._source.getScene().getEngine()._releaseBuffer(this._ib);
            this._lineShader.dispose();
        };
        EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
            if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
                return 0;
            }
            if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
                return 1;
            }
            if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
                return 2;
            }
            return -1;
        };
        EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
            if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
                return 0;
            }
            if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
                return 1;
            }
            if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
                return 2;
            }
            return -1;
        };
        EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
            var needToCreateLine;
            if (edge === undefined) {
                needToCreateLine = true;
            }
            else {
                var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
                needToCreateLine = dotProduct < this._epsilon;
            }
            if (needToCreateLine) {
                var offset = this._linesPositions.length / 3;
                var normal = p0.subtract(p1);
                normal.normalize();
                // Positions
                this._linesPositions.push(p0.x);
                this._linesPositions.push(p0.y);
                this._linesPositions.push(p0.z);
                this._linesPositions.push(p0.x);
                this._linesPositions.push(p0.y);
                this._linesPositions.push(p0.z);
                this._linesPositions.push(p1.x);
                this._linesPositions.push(p1.y);
                this._linesPositions.push(p1.z);
                this._linesPositions.push(p1.x);
                this._linesPositions.push(p1.y);
                this._linesPositions.push(p1.z);
                // Normals
                this._linesNormals.push(p1.x);
                this._linesNormals.push(p1.y);
                this._linesNormals.push(p1.z);
                this._linesNormals.push(-1);
                this._linesNormals.push(p1.x);
                this._linesNormals.push(p1.y);
                this._linesNormals.push(p1.z);
                this._linesNormals.push(1);
                this._linesNormals.push(p0.x);
                this._linesNormals.push(p0.y);
                this._linesNormals.push(p0.z);
                this._linesNormals.push(-1);
                this._linesNormals.push(p0.x);
                this._linesNormals.push(p0.y);
                this._linesNormals.push(p0.z);
                this._linesNormals.push(1);
                // Indices
                this._linesIndices.push(offset);
                this._linesIndices.push(offset + 1);
                this._linesIndices.push(offset + 2);
                this._linesIndices.push(offset);
                this._linesIndices.push(offset + 2);
                this._linesIndices.push(offset + 3);
            }
        };
        EdgesRenderer.prototype._generateEdgesLines = function () {
            var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this._source.getIndices();
            // First let's find adjacencies
            var adjacencies = new Array();
            var faceNormals = new Array();
            var index;
            var faceAdjacencies;
            // Prepare faces
            for (index = 0; index < indices.length; index += 3) {
                faceAdjacencies = new FaceAdjacencies();
                var p0Index = indices[index];
                var p1Index = indices[index + 1];
                var p2Index = indices[index + 2];
                faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
                faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
                faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
                var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
                faceNormal.normalize();
                faceNormals.push(faceNormal);
                adjacencies.push(faceAdjacencies);
            }
            // Scan
            for (index = 0; index < adjacencies.length; index++) {
                faceAdjacencies = adjacencies[index];
                for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
                    var otherFaceAdjacencies = adjacencies[otherIndex];
                    if (faceAdjacencies.edgesConnectedCount === 3) {
                        break;
                    }
                    if (otherFaceAdjacencies.edgesConnectedCount === 3) {
                        continue;
                    }
                    var otherP0 = indices[otherIndex * 3];
                    var otherP1 = indices[otherIndex * 3 + 1];
                    var otherP2 = indices[otherIndex * 3 + 2];
                    for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
                        var otherEdgeIndex;
                        if (faceAdjacencies.edges[edgeIndex] !== undefined) {
                            continue;
                        }
                        switch (edgeIndex) {
                            case 0:
                                if (this._checkVerticesInsteadOfIndices) {
                                    otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
                                }
                                else {
                                    otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
                                }
                                break;
                            case 1:
                                if (this._checkVerticesInsteadOfIndices) {
                                    otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
                                }
                                else {
                                    otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
                                }
                                break;
                            case 2:
                                if (this._checkVerticesInsteadOfIndices) {
                                    otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
                                }
                                else {
                                    otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
                                }
                                break;
                        }
                        if (otherEdgeIndex === -1) {
                            continue;
                        }
                        faceAdjacencies.edges[edgeIndex] = otherIndex;
                        otherFaceAdjacencies.edges[otherEdgeIndex] = index;
                        faceAdjacencies.edgesConnectedCount++;
                        otherFaceAdjacencies.edgesConnectedCount++;
                        if (faceAdjacencies.edgesConnectedCount === 3) {
                            break;
                        }
                    }
                }
            }
            // Create lines
            for (index = 0; index < adjacencies.length; index++) {
                // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
                var current = adjacencies[index];
                this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
                this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
                this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
            }
            // Merge into a single mesh
            var engine = this._source.getScene().getEngine();
            this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
            this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
            this._ib = engine.createIndexBuffer(this._linesIndices);
            this._indicesCount = this._linesIndices.length;
        };
        EdgesRenderer.prototype.render = function () {
            if (!this._lineShader.isReady()) {
                return;
            }
            var scene = this._source.getScene();
            var engine = scene.getEngine();
            this._lineShader._preBind();
            // VBOs
            engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
            scene.resetCachedMaterial();
            this._lineShader.setColor4("color", this._source.edgesColor);
            if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
                this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
            }
            else {
                this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
            }
            this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
            this._lineShader.bind(this._source.getWorldMatrix());
            // Draw order
            engine.draw(true, 0, this._indicesCount);
            this._lineShader.unbind();
            engine.setDepthWrite(true);
        };
        return EdgesRenderer;
    }());
    BABYLON.EdgesRenderer = EdgesRenderer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.edgesRenderer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    (function (TonemappingOperator) {
        TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
        TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
        TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
        TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
    })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
    var TonemappingOperator = BABYLON.TonemappingOperator;
    ;
    var TonemapPostProcess = (function (_super) {
        __extends(TonemapPostProcess, _super);
        function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
            var _this = this;
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
            this._operator = _operator;
            this.exposureAdjustment = exposureAdjustment;
            var defines = "#define ";
            if (this._operator === TonemappingOperator.Hable)
                defines += "HABLE_TONEMAPPING";
            else if (this._operator === TonemappingOperator.Reinhard)
                defines += "REINHARD_TONEMAPPING";
            else if (this._operator === TonemappingOperator.HejiDawson)
                defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
            else if (this._operator === TonemappingOperator.Photographic)
                defines += "PHOTOGRAPHIC_TONEMAPPING";
            //sadly a second call to create the effect.
            this.updateEffect(defines);
            this.onApply = function (effect) {
                effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
            };
        }
        return TonemapPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.TonemapPostProcess = TonemapPostProcess;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tonemapPostProcess.js.map
 
var BABYLON;
(function (BABYLON) {
    var ReflectionProbe = (function () {
        function ReflectionProbe(name, size, scene, generateMipMaps) {
            var _this = this;
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            this.name = name;
            this._viewMatrix = BABYLON.Matrix.Identity();
            this._target = BABYLON.Vector3.Zero();
            this._add = BABYLON.Vector3.Zero();
            this.invertYAxis = false;
            this.position = BABYLON.Vector3.Zero();
            this._scene = scene;
            this._scene.reflectionProbes.push(this);
            this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
            this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
                switch (faceIndex) {
                    case 0:
                        _this._add.copyFromFloats(1, 0, 0);
                        break;
                    case 1:
                        _this._add.copyFromFloats(-1, 0, 0);
                        break;
                    case 2:
                        _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
                        break;
                    case 3:
                        _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
                        break;
                    case 4:
                        _this._add.copyFromFloats(0, 0, 1);
                        break;
                    case 5:
                        _this._add.copyFromFloats(0, 0, -1);
                        break;
                }
                if (_this._attachedMesh) {
                    _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
                }
                _this.position.addToRef(_this._add, _this._target);
                BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
                scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
            });
            this._renderTargetTexture.onAfterUnbindObservable.add(function () {
                scene.updateTransformMatrix(true);
            });
            this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
        }
        Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
            get: function () {
                return this._renderTargetTexture.refreshRate;
            },
            set: function (value) {
                this._renderTargetTexture.refreshRate = value;
            },
            enumerable: true,
            configurable: true
        });
        ReflectionProbe.prototype.getScene = function () {
            return this._scene;
        };
        Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
            get: function () {
                return this._renderTargetTexture;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ReflectionProbe.prototype, "renderList", {
            get: function () {
                return this._renderTargetTexture.renderList;
            },
            enumerable: true,
            configurable: true
        });
        ReflectionProbe.prototype.attachToMesh = function (mesh) {
            this._attachedMesh = mesh;
        };
        ReflectionProbe.prototype.dispose = function () {
            var index = this._scene.reflectionProbes.indexOf(this);
            if (index !== -1) {
                // Remove from the scene if found 
                this._scene.reflectionProbes.splice(index, 1);
            }
            if (this._renderTargetTexture) {
                this._renderTargetTexture.dispose();
                this._renderTargetTexture = null;
            }
        };
        return ReflectionProbe;
    }());
    BABYLON.ReflectionProbe = ReflectionProbe;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.reflectionProbe.js.map
 
var BABYLON;
(function (BABYLON) {
    var SolidParticle = (function () {
        /**
         * Creates a Solid Particle object.
         * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
         * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
         * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
         *  `model` (ModelShape) is a reference to the model shape on what the particle is designed.
         * `shapeId` (integer) is the model shape identifier in the SPS.
         * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
         * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
         */
        function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
            this.idx = 0; // particle global index
            this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
            this.position = BABYLON.Vector3.Zero(); // position
            this.rotation = BABYLON.Vector3.Zero(); // rotation
            this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
            this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
            this.velocity = BABYLON.Vector3.Zero(); // velocity
            this.alive = true; // alive
            this.isVisible = true; // visibility
            this._pos = 0; // index of this particle in the global "positions" array
            this.shapeId = 0; // model shape id
            this.idxInShape = 0; // index of the particle in its shape id
            this.idx = particleIndex;
            this._pos = positionIndex;
            this._model = model;
            this.shapeId = shapeId;
            this.idxInShape = idxInShape;
            this._sps = sps;
            if (modelBoundingInfo) {
                this._modelBoundingInfo = modelBoundingInfo;
                this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
            }
        }
        Object.defineProperty(SolidParticle.prototype, "scale", {
            /**
             * legacy support, changed scale to scaling
             */
            get: function () {
                return this.scaling;
            },
            set: function (scale) {
                this.scaling = scale;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticle.prototype, "quaternion", {
            /**
             * legacy support, changed quaternion to rotationQuaternion
             */
            get: function () {
                return this.rotationQuaternion;
            },
            set: function (q) {
                this.rotationQuaternion = q;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
         * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
         * `target` is the object (solid particle or mesh) what the intersection is computed against.
         */
        SolidParticle.prototype.intersectsMesh = function (target) {
            if (!this._boundingInfo || !target._boundingInfo) {
                return false;
            }
            if (this._sps._bSphereOnly) {
                return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
            }
            return this._boundingInfo.intersects(target._boundingInfo, false);
        };
        return SolidParticle;
    }());
    BABYLON.SolidParticle = SolidParticle;
    var ModelShape = (function () {
        /**
         * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
         * SPS internal tool, don't use it manually.
         */
        function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
            this.shapeID = id;
            this._shape = shape;
            this._shapeUV = shapeUV;
            this._positionFunction = posFunction;
            this._vertexFunction = vtxFunction;
        }
        return ModelShape;
    }());
    BABYLON.ModelShape = ModelShape;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.solidParticle.js.map
 
var BABYLON;
(function (BABYLON) {
    /**
    * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
    */
    var SolidParticleSystem = (function () {
        /**
        * Creates a SPS (Solid Particle System) object.
        * `name` (String) is the SPS name, this will be the underlying mesh name.
        * `scene` (Scene) is the scene in which the SPS is added.
        * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
        * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
        * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
        * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
        * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
        *  Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
        */
        function SolidParticleSystem(name, scene, options) {
            // public members
            /**
            *  The SPS array of Solid Particle objects. Just access each particle as with any classic array.
            *  Example : var p = SPS.particles[i];
            */
            this.particles = new Array();
            /**
            * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
            */
            this.nbParticles = 0;
            /**
            * If the particles must ever face the camera (default false). Useful for planar particles.
            */
            this.billboard = false;
            /**
             * Recompute normals when adding a shape
             */
            this.recomputeNormals = true;
            /**
            * This a counter ofr your own usage. It's not set by any SPS functions.
            */
            this.counter = 0;
            /**
            * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
            * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
            */
            this.vars = {};
            this._positions = new Array();
            this._indices = new Array();
            this._normals = new Array();
            this._colors = new Array();
            this._uvs = new Array();
            this._index = 0; // indices index
            this._updatable = true;
            this._pickable = false;
            this._isVisibilityBoxLocked = false;
            this._alwaysVisible = false;
            this._shapeCounter = 0;
            this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
            this._color = new BABYLON.Color4(0, 0, 0, 0);
            this._computeParticleColor = true;
            this._computeParticleTexture = true;
            this._computeParticleRotation = true;
            this._computeParticleVertex = false;
            this._computeBoundingBox = false;
            this._cam_axisZ = BABYLON.Vector3.Zero();
            this._cam_axisY = BABYLON.Vector3.Zero();
            this._cam_axisX = BABYLON.Vector3.Zero();
            this._axisX = BABYLON.Axis.X;
            this._axisY = BABYLON.Axis.Y;
            this._axisZ = BABYLON.Axis.Z;
            this._camDir = BABYLON.Vector3.Zero();
            this._rotMatrix = new BABYLON.Matrix();
            this._invertMatrix = new BABYLON.Matrix();
            this._rotated = BABYLON.Vector3.Zero();
            this._quaternion = new BABYLON.Quaternion();
            this._vertex = BABYLON.Vector3.Zero();
            this._normal = BABYLON.Vector3.Zero();
            this._yaw = 0.0;
            this._pitch = 0.0;
            this._roll = 0.0;
            this._halfroll = 0.0;
            this._halfpitch = 0.0;
            this._halfyaw = 0.0;
            this._sinRoll = 0.0;
            this._cosRoll = 0.0;
            this._sinPitch = 0.0;
            this._cosPitch = 0.0;
            this._sinYaw = 0.0;
            this._cosYaw = 0.0;
            this._w = 0.0;
            this._minimum = BABYLON.Tmp.Vector3[0];
            this._maximum = BABYLON.Tmp.Vector3[1];
            this._scale = BABYLON.Tmp.Vector3[2];
            this._translation = BABYLON.Tmp.Vector3[3];
            this._minBbox = BABYLON.Tmp.Vector3[4];
            this._maxBbox = BABYLON.Tmp.Vector3[5];
            this._particlesIntersect = false;
            this._bSphereOnly = false;
            this._bSphereRadiusFactor = 1.0;
            this.name = name;
            this._scene = scene;
            this._camera = scene.activeCamera;
            this._pickable = options ? options.isPickable : false;
            this._particlesIntersect = options ? options.particleIntersection : false;
            this._bSphereOnly = options ? options.boundingSphereOnly : false;
            this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
            if (options && options.updatable) {
                this._updatable = options.updatable;
            }
            else {
                this._updatable = true;
            }
            if (this._pickable) {
                this.pickedParticles = [];
            }
        }
        /**
        * Builds the SPS underlying mesh. Returns a standard Mesh.
        * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
        */
        SolidParticleSystem.prototype.buildMesh = function () {
            if (this.nbParticles === 0) {
                var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
                this.addShape(triangle, 1);
                triangle.dispose();
            }
            this._positions32 = new Float32Array(this._positions);
            this._uvs32 = new Float32Array(this._uvs);
            this._colors32 = new Float32Array(this._colors);
            if (this.recomputeNormals) {
                BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
            }
            this._normals32 = new Float32Array(this._normals);
            this._fixedNormal32 = new Float32Array(this._normals);
            var vertexData = new BABYLON.VertexData();
            vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
            vertexData.indices = this._indices;
            vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
            if (this._uvs32) {
                vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
                ;
            }
            if (this._colors32) {
                vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
            }
            var mesh = new BABYLON.Mesh(this.name, this._scene);
            vertexData.applyToMesh(mesh, this._updatable);
            this.mesh = mesh;
            this.mesh.isPickable = this._pickable;
            // free memory
            this._positions = null;
            this._normals = null;
            this._uvs = null;
            this._colors = null;
            if (!this._updatable) {
                this.particles.length = 0;
            }
            return mesh;
        };
        /**
        * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
        * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
        * Thus the particles generated from `digest()` have their property `position` set yet.
        * `mesh` ( Mesh ) is the mesh to be digested
        * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
        * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
        * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
        */
        SolidParticleSystem.prototype.digest = function (mesh, options) {
            var size = (options && options.facetNb) || 1;
            var number = (options && options.number);
            var delta = (options && options.delta) || 0;
            var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var meshInd = mesh.getIndices();
            var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var f = 0; // facet counter
            var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
            // compute size from number
            if (number) {
                number = (number > totalFacets) ? totalFacets : number;
                size = Math.round(totalFacets / number);
                delta = 0;
            }
            else {
                size = (size > totalFacets) ? totalFacets : size;
            }
            var facetPos = []; // submesh positions
            var facetInd = []; // submesh indices
            var facetUV = []; // submesh UV
            var facetCol = []; // submesh colors
            var barycenter = BABYLON.Tmp.Vector3[0];
            var rand;
            var sizeO = size;
            while (f < totalFacets) {
                size = sizeO + Math.floor((1 + delta) * Math.random());
                if (f > totalFacets - size) {
                    size = totalFacets - f;
                }
                // reset temp arrays
                facetPos.length = 0;
                facetInd.length = 0;
                facetUV.length = 0;
                facetCol.length = 0;
                // iterate over "size" facets
                var fi = 0;
                for (var j = f * 3; j < (f + size) * 3; j++) {
                    facetInd.push(fi);
                    var i = meshInd[j];
                    facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
                    if (meshUV) {
                        facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
                    }
                    if (meshCol) {
                        facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
                    }
                    fi++;
                }
                // create a model shape for each single particle
                var idx = this.nbParticles;
                var shape = this._posToShape(facetPos);
                var shapeUV = this._uvsToShapeUV(facetUV);
                // compute the barycenter of the shape
                var v;
                for (v = 0; v < shape.length; v++) {
                    barycenter.addInPlace(shape[v]);
                }
                barycenter.scaleInPlace(1 / shape.length);
                // shift the shape from its barycenter to the origin
                for (v = 0; v < shape.length; v++) {
                    shape[v].subtractInPlace(barycenter);
                }
                var bInfo;
                if (this._particlesIntersect) {
                    bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
                }
                var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
                // add the particle in the SPS
                this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
                this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
                // initialize the particle position
                this.particles[this.nbParticles].position.addInPlace(barycenter);
                this._index += shape.length;
                idx++;
                this.nbParticles++;
                this._shapeCounter++;
                f += size;
            }
            return this;
        };
        //reset copy
        SolidParticleSystem.prototype._resetCopy = function () {
            this._copy.position.x = 0;
            this._copy.position.y = 0;
            this._copy.position.z = 0;
            this._copy.rotation.x = 0;
            this._copy.rotation.y = 0;
            this._copy.rotation.z = 0;
            this._copy.rotationQuaternion = null;
            this._copy.scaling.x = 1;
            this._copy.scaling.y = 1;
            this._copy.scaling.z = 1;
            this._copy.uvs.x = 0;
            this._copy.uvs.y = 0;
            this._copy.uvs.z = 1;
            this._copy.uvs.w = 1;
            this._copy.color = null;
        };
        // _meshBuilder : inserts the shape model in the global SPS mesh
        SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
            var i;
            var u = 0;
            var c = 0;
            var n = 0;
            this._resetCopy();
            if (options && options.positionFunction) {
                options.positionFunction(this._copy, idx, idxInShape);
            }
            if (this._copy.rotationQuaternion) {
                this._quaternion.copyFrom(this._copy.rotationQuaternion);
            }
            else {
                this._yaw = this._copy.rotation.y;
                this._pitch = this._copy.rotation.x;
                this._roll = this._copy.rotation.z;
                this._quaternionRotationYPR();
            }
            this._quaternionToRotationMatrix();
            for (i = 0; i < shape.length; i++) {
                this._vertex.x = shape[i].x;
                this._vertex.y = shape[i].y;
                this._vertex.z = shape[i].z;
                if (options && options.vertexFunction) {
                    options.vertexFunction(this._copy, this._vertex, i);
                }
                this._vertex.x *= this._copy.scaling.x;
                this._vertex.y *= this._copy.scaling.y;
                this._vertex.z *= this._copy.scaling.z;
                BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
                positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
                if (meshUV) {
                    uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
                    u += 2;
                }
                if (this._copy.color) {
                    this._color = this._copy.color;
                }
                else if (meshCol && meshCol[c] !== undefined) {
                    this._color.r = meshCol[c];
                    this._color.g = meshCol[c + 1];
                    this._color.b = meshCol[c + 2];
                    this._color.a = meshCol[c + 3];
                }
                else {
                    this._color.r = 1;
                    this._color.g = 1;
                    this._color.b = 1;
                    this._color.a = 1;
                }
                colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
                c += 4;
                if (!this.recomputeNormals && meshNor) {
                    this._normal.x = meshNor[n];
                    this._normal.y = meshNor[n + 1];
                    this._normal.z = meshNor[n + 2];
                    BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
                    normals.push(this._normal.x, this._normal.y, this._normal.z);
                    n += 3;
                }
            }
            for (i = 0; i < meshInd.length; i++) {
                indices.push(p + meshInd[i]);
            }
            if (this._pickable) {
                var nbfaces = meshInd.length / 3;
                for (i = 0; i < nbfaces; i++) {
                    this.pickedParticles.push({ idx: idx, faceId: i });
                }
            }
        };
        // returns a shape array from positions array
        SolidParticleSystem.prototype._posToShape = function (positions) {
            var shape = [];
            for (var i = 0; i < positions.length; i += 3) {
                shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
            }
            return shape;
        };
        // returns a shapeUV array from a Vector4 uvs
        SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
            var shapeUV = [];
            if (uvs) {
                for (var i = 0; i < uvs.length; i++)
                    shapeUV.push(uvs[i]);
            }
            return shapeUV;
        };
        // adds a new particle object in the particles array
        SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
            this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
        };
        /**
        * Adds some particles to the SPS from the model shape. Returns the shape id.
        * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
        * `mesh` is any Mesh object that will be used as a model for the solid particles.
        * `nb` (positive integer) the number of particles to be created from this model
        * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
        * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
        */
        SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
            var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var meshInd = mesh.getIndices();
            var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var bbInfo;
            if (this._particlesIntersect) {
                bbInfo = mesh.getBoundingInfo();
            }
            var shape = this._posToShape(meshPos);
            var shapeUV = this._uvsToShapeUV(meshUV);
            var posfunc = options ? options.positionFunction : null;
            var vtxfunc = options ? options.vertexFunction : null;
            var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
            // particles
            var idx = this.nbParticles;
            for (var i = 0; i < nb; i++) {
                this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
                if (this._updatable) {
                    this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
                }
                this._index += shape.length;
                idx++;
            }
            this.nbParticles += nb;
            this._shapeCounter++;
            return this._shapeCounter - 1;
        };
        // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
        SolidParticleSystem.prototype._rebuildParticle = function (particle) {
            this._resetCopy();
            if (particle._model._positionFunction) {
                particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
            }
            if (this._copy.rotationQuaternion) {
                this._quaternion.copyFrom(this._copy.rotationQuaternion);
            }
            else {
                this._yaw = this._copy.rotation.y;
                this._pitch = this._copy.rotation.x;
                this._roll = this._copy.rotation.z;
                this._quaternionRotationYPR();
            }
            this._quaternionToRotationMatrix();
            this._shape = particle._model._shape;
            for (var pt = 0; pt < this._shape.length; pt++) {
                this._vertex.x = this._shape[pt].x;
                this._vertex.y = this._shape[pt].y;
                this._vertex.z = this._shape[pt].z;
                if (particle._model._vertexFunction) {
                    particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
                }
                this._vertex.x *= this._copy.scaling.x;
                this._vertex.y *= this._copy.scaling.y;
                this._vertex.z *= this._copy.scaling.z;
                BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
                this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
                this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
                this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
            }
            particle.position.x = 0.0;
            particle.position.y = 0.0;
            particle.position.z = 0.0;
            particle.rotation.x = 0.0;
            particle.rotation.y = 0.0;
            particle.rotation.z = 0.0;
            particle.rotationQuaternion = null;
            particle.scaling.x = 1.0;
            particle.scaling.y = 1.0;
            particle.scaling.z = 1.0;
        };
        /**
        * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
        */
        SolidParticleSystem.prototype.rebuildMesh = function () {
            for (var p = 0; p < this.particles.length; p++) {
                this._rebuildParticle(this.particles[p]);
            }
            this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
        };
        /**
        *  Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
        *  This method calls `updateParticle()` for each particle of the SPS.
        *  For an animated SPS, it is usually called within the render loop.
        * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
        * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
        * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
        */
        SolidParticleSystem.prototype.setParticles = function (start, end, update) {
            if (start === void 0) { start = 0; }
            if (end === void 0) { end = this.nbParticles - 1; }
            if (update === void 0) { update = true; }
            if (!this._updatable) {
                return;
            }
            // custom beforeUpdate
            this.beforeUpdateParticles(start, end, update);
            this._cam_axisX.x = 1.0;
            this._cam_axisX.y = 0.0;
            this._cam_axisX.z = 0.0;
            this._cam_axisY.x = 0.0;
            this._cam_axisY.y = 1.0;
            this._cam_axisY.z = 0.0;
            this._cam_axisZ.x = 0.0;
            this._cam_axisZ.y = 0.0;
            this._cam_axisZ.z = 1.0;
            // if the particles will always face the camera
            if (this.billboard) {
                // compute the camera position and un-rotate it by the current mesh rotation
                if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
                    this._quaternionToRotationMatrix();
                    this._rotMatrix.invertToRef(this._invertMatrix);
                    this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
                    BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
                    this._cam_axisZ.normalize();
                    // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
                    BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
                    BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
                    this._cam_axisY.normalize();
                    this._cam_axisX.normalize();
                }
            }
            BABYLON.Matrix.IdentityToRef(this._rotMatrix);
            var idx = 0;
            var index = 0;
            var colidx = 0;
            var colorIndex = 0;
            var uvidx = 0;
            var uvIndex = 0;
            var pt = 0;
            if (this._computeBoundingBox) {
                BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
                BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
            }
            // particle loop
            end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
            for (var p = start; p <= end; p++) {
                this._particle = this.particles[p];
                this._shape = this._particle._model._shape;
                this._shapeUV = this._particle._model._shapeUV;
                // call to custom user function to update the particle properties
                this.updateParticle(this._particle);
                if (this._particle.isVisible) {
                    // particle rotation matrix
                    if (this.billboard) {
                        this._particle.rotation.x = 0.0;
                        this._particle.rotation.y = 0.0;
                    }
                    if (this._computeParticleRotation || this.billboard) {
                        if (this._particle.rotationQuaternion) {
                            this._quaternion.copyFrom(this._particle.rotationQuaternion);
                        }
                        else {
                            this._yaw = this._particle.rotation.y;
                            this._pitch = this._particle.rotation.x;
                            this._roll = this._particle.rotation.z;
                            this._quaternionRotationYPR();
                        }
                        this._quaternionToRotationMatrix();
                    }
                    // particle vertex loop
                    for (pt = 0; pt < this._shape.length; pt++) {
                        idx = index + pt * 3;
                        colidx = colorIndex + pt * 4;
                        uvidx = uvIndex + pt * 2;
                        this._vertex.x = this._shape[pt].x;
                        this._vertex.y = this._shape[pt].y;
                        this._vertex.z = this._shape[pt].z;
                        if (this._computeParticleVertex) {
                            this.updateParticleVertex(this._particle, this._vertex, pt);
                        }
                        // positions
                        this._vertex.x *= this._particle.scaling.x;
                        this._vertex.y *= this._particle.scaling.y;
                        this._vertex.z *= this._particle.scaling.z;
                        this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
                        this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
                        this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
                        this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
                        this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                        this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                        this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
                        if (this._computeBoundingBox) {
                            if (this._positions32[idx] < this._minimum.x) {
                                this._minimum.x = this._positions32[idx];
                            }
                            if (this._positions32[idx] > this._maximum.x) {
                                this._maximum.x = this._positions32[idx];
                            }
                            if (this._positions32[idx + 1] < this._minimum.y) {
                                this._minimum.y = this._positions32[idx + 1];
                            }
                            if (this._positions32[idx + 1] > this._maximum.y) {
                                this._maximum.y = this._positions32[idx + 1];
                            }
                            if (this._positions32[idx + 2] < this._minimum.z) {
                                this._minimum.z = this._positions32[idx + 2];
                            }
                            if (this._positions32[idx + 2] > this._maximum.z) {
                                this._maximum.z = this._positions32[idx + 2];
                            }
                        }
                        // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
                        if (!this._computeParticleVertex) {
                            this._normal.x = this._fixedNormal32[idx];
                            this._normal.y = this._fixedNormal32[idx + 1];
                            this._normal.z = this._fixedNormal32[idx + 2];
                            this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
                            this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
                            this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
                            this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
                            this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                            this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                            this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
                        }
                        if (this._computeParticleColor) {
                            this._colors32[colidx] = this._particle.color.r;
                            this._colors32[colidx + 1] = this._particle.color.g;
                            this._colors32[colidx + 2] = this._particle.color.b;
                            this._colors32[colidx + 3] = this._particle.color.a;
                        }
                        if (this._computeParticleTexture) {
                            this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
                            this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
                        }
                    }
                }
                else {
                    for (pt = 0; pt < this._shape.length; pt++) {
                        idx = index + pt * 3;
                        colidx = colorIndex + pt * 4;
                        uvidx = uvIndex + pt * 2;
                        this._positions32[idx] = this._camera.position.x;
                        this._positions32[idx + 1] = this._camera.position.y;
                        this._positions32[idx + 2] = this._camera.position.z;
                        this._normals32[idx] = 0.0;
                        this._normals32[idx + 1] = 0.0;
                        this._normals32[idx + 2] = 0.0;
                        if (this._computeParticleColor) {
                            this._colors32[colidx] = this._particle.color.r;
                            this._colors32[colidx + 1] = this._particle.color.g;
                            this._colors32[colidx + 2] = this._particle.color.b;
                            this._colors32[colidx + 3] = this._particle.color.a;
                        }
                        if (this._computeParticleTexture) {
                            this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
                            this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
                        }
                    }
                }
                // if the particle intersections must be computed : update the bbInfo
                if (this._particlesIntersect) {
                    var bInfo = this._particle._boundingInfo;
                    var bBox = bInfo.boundingBox;
                    var bSphere = bInfo.boundingSphere;
                    if (!this._bSphereOnly) {
                        // place, scale and rotate the particle bbox within the SPS local system, then update it
                        for (var b = 0; b < bBox.vectors.length; b++) {
                            this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
                            this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
                            this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
                            this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
                            this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
                            this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
                            this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
                            bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                            bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                            bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
                        }
                        bBox._update(this.mesh._worldMatrix);
                    }
                    // place and scale the particle bouding sphere in the SPS local system, then update it
                    this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
                    this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
                    this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
                    this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
                    this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
                    this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
                    bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
                    bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
                    bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
                    bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
                    bSphere._update(this.mesh._worldMatrix);
                }
                // increment indexes for the next particle
                index = idx + 3;
                colorIndex = colidx + 4;
                uvIndex = uvidx + 2;
            }
            // if the VBO must be updated
            if (update) {
                if (this._computeParticleColor) {
                    this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
                }
                if (this._computeParticleTexture) {
                    this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
                }
                this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
                if (!this.mesh.areNormalsFrozen) {
                    if (this._computeParticleVertex) {
                        // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
                        BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
                        for (var i = 0; i < this._normals32.length; i++) {
                            this._fixedNormal32[i] = this._normals32[i];
                        }
                    }
                    this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
                }
            }
            if (this._computeBoundingBox) {
                this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
                this.mesh._boundingInfo.update(this.mesh._worldMatrix);
            }
            this.afterUpdateParticles(start, end, update);
        };
        SolidParticleSystem.prototype._quaternionRotationYPR = function () {
            this._halfroll = this._roll * 0.5;
            this._halfpitch = this._pitch * 0.5;
            this._halfyaw = this._yaw * 0.5;
            this._sinRoll = Math.sin(this._halfroll);
            this._cosRoll = Math.cos(this._halfroll);
            this._sinPitch = Math.sin(this._halfpitch);
            this._cosPitch = Math.cos(this._halfpitch);
            this._sinYaw = Math.sin(this._halfyaw);
            this._cosYaw = Math.cos(this._halfyaw);
            this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
            this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
            this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
            this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
        };
        SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
            this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
            this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
            this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
            this._rotMatrix.m[3] = 0;
            this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
            this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
            this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
            this._rotMatrix.m[7] = 0;
            this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
            this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
            this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
            this._rotMatrix.m[11] = 0;
            this._rotMatrix.m[12] = 0;
            this._rotMatrix.m[13] = 0;
            this._rotMatrix.m[14] = 0;
            this._rotMatrix.m[15] = 1.0;
        };
        /**
        * Disposes the SPS
        */
        SolidParticleSystem.prototype.dispose = function () {
            this.mesh.dispose();
            this.vars = null;
            // drop references to internal big arrays for the GC
            this._positions = null;
            this._indices = null;
            this._normals = null;
            this._uvs = null;
            this._colors = null;
            this._positions32 = null;
            this._normals32 = null;
            this._fixedNormal32 = null;
            this._uvs32 = null;
            this._colors32 = null;
            this.pickedParticles = null;
        };
        /**
        * Visibilty helper : Recomputes the visible size according to the mesh bounding box
        * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
        */
        SolidParticleSystem.prototype.refreshVisibleSize = function () {
            if (!this._isVisibilityBoxLocked) {
                this.mesh.refreshBoundingInfo();
            }
        };
        /**
        * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
        * @param size the size (float) of the visibility box
        * note : this doesn't lock the SPS mesh bounding box.
        * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
        */
        SolidParticleSystem.prototype.setVisibilityBox = function (size) {
            var vis = size / 2;
            this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
        };
        Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
            // getter and setter
            get: function () {
                return this._alwaysVisible;
            },
            /**
            * Sets the SPS as always visible or not
            * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
            */
            set: function (val) {
                this._alwaysVisible = val;
                this.mesh.alwaysSelectAsActiveMesh = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
            get: function () {
                return this._isVisibilityBoxLocked;
            },
            /**
            * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
            * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
            */
            set: function (val) {
                this._isVisibilityBoxLocked = val;
                this.mesh.getBoundingInfo().isLocked = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
            // getters
            get: function () {
                return this._computeParticleRotation;
            },
            // Optimizer setters
            /**
            * Tells to `setParticles()` to compute the particle rotations or not.
            * Default value : true. The SPS is faster when it's set to false.
            * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
            */
            set: function (val) {
                this._computeParticleRotation = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
            get: function () {
                return this._computeParticleColor;
            },
            /**
            * Tells to `setParticles()` to compute the particle colors or not.
            * Default value : true. The SPS is faster when it's set to false.
            * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
            */
            set: function (val) {
                this._computeParticleColor = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
            get: function () {
                return this._computeParticleTexture;
            },
            /**
            * Tells to `setParticles()` to compute the particle textures or not.
            * Default value : true. The SPS is faster when it's set to false.
            * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
            */
            set: function (val) {
                this._computeParticleTexture = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
            get: function () {
                return this._computeParticleVertex;
            },
            /**
            * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
            * Default value : false. The SPS is faster when it's set to false.
            * Note : the particle custom vertex positions aren't stored values.
            */
            set: function (val) {
                this._computeParticleVertex = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
            get: function () {
                return this._computeBoundingBox;
            },
            /**
            * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
            */
            set: function (val) {
                this._computeBoundingBox = val;
            },
            enumerable: true,
            configurable: true
        });
        // =======================================================================
        // Particle behavior logic
        // these following methods may be overwritten by the user to fit his needs
        /**
        * This function does nothing. It may be overwritten to set all the particle first values.
        * The SPS doesn't call this function, you may have to call it by your own.
        * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
        */
        SolidParticleSystem.prototype.initParticles = function () {
        };
        /**
        * This function does nothing. It may be overwritten to recycle a particle.
        * The SPS doesn't call this function, you may have to call it by your own.
        * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
        */
        SolidParticleSystem.prototype.recycleParticle = function (particle) {
            return particle;
        };
        /**
        * Updates a particle : this function should  be overwritten by the user.
        * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
        * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
        * ex : just set a particle position or velocity and recycle conditions
        */
        SolidParticleSystem.prototype.updateParticle = function (particle) {
            return particle;
        };
        /**
        * Updates a vertex of a particle : it can be overwritten by the user.
        * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
        * @param particle the current particle
        * @param vertex the current index of the current particle
        * @param pt the index of the current vertex in the particle shape
        * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
        * ex : just set a vertex particle position
        */
        SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
            return vertex;
        };
        /**
        * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
        * This does nothing and may be overwritten by the user.
        * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
        * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
        * @param update the boolean update value actually passed to setParticles()
        */
        SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
        };
        /**
        * This will be called  by `setParticles()` after all the other treatments and just before the actual mesh update.
        * This will be passed three parameters.
        * This does nothing and may be overwritten by the user.
        * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
        * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
        * @param update the boolean update value actually passed to setParticles()
        */
        SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
        };
        return SolidParticleSystem;
    }());
    BABYLON.SolidParticleSystem = SolidParticleSystem;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.solidParticleSystem.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        var FileFaceOrientation = (function () {
            function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
                this.name = name;
                this.worldAxisForNormal = worldAxisForNormal;
                this.worldAxisForFileX = worldAxisForFileX;
                this.worldAxisForFileY = worldAxisForFileY;
            }
            return FileFaceOrientation;
        }());
        ;
        /**
         * Helper class dealing with the extraction of spherical polynomial dataArray
         * from a cube map.
         */
        var CubeMapToSphericalPolynomialTools = (function () {
            function CubeMapToSphericalPolynomialTools() {
            }
            /**
             * Converts a cubemap to the according Spherical Polynomial data.
             * This extracts the first 3 orders only as they are the only one used in the lighting.
             *
             * @param cubeInfo The Cube map to extract the information from.
             * @return The Spherical Polynomial data.
             */
            CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
                var sphericalHarmonics = new BABYLON.SphericalHarmonics();
                var totalSolidAngle = 0.0;
                // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
                var du = 2.0 / cubeInfo.size;
                var dv = du;
                // The (u,v) of the first texel is half a texel from the corner (-1,-1).
                var minUV = du * 0.5 - 1.0;
                for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                    var fileFace = this.FileFaces[faceIndex];
                    var dataArray = cubeInfo[fileFace.name];
                    var v = minUV;
                    // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
                    // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
                    // Because SP is still linear, so summation is fine in that basis.
                    for (var y = 0; y < cubeInfo.size; y++) {
                        var u = minUV;
                        for (var x = 0; x < cubeInfo.size; x++) {
                            // World direction (not normalised)
                            var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
                            worldDirection.normalize();
                            var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
                            if (1) {
                                var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
                                var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
                                var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
                                var color = new BABYLON.Color3(r, g, b);
                                sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
                            }
                            else {
                                if (faceIndex == 0) {
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
                                }
                                else if (faceIndex == 1) {
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
                                }
                                else if (faceIndex == 2) {
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
                                }
                                else if (faceIndex == 3) {
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
                                }
                                else if (faceIndex == 4) {
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
                                }
                                else if (faceIndex == 5) {
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
                                    dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
                                }
                                var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
                                sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
                            }
                            totalSolidAngle += deltaSolidAngle;
                            u += du;
                        }
                        v += dv;
                    }
                }
                var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
                var correction = correctSolidAngle / totalSolidAngle;
                sphericalHarmonics.scale(correction);
                // Additionally scale by pi -- audit needed
                sphericalHarmonics.scale(1.0 / Math.PI);
                return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
            };
            CubeMapToSphericalPolynomialTools.FileFaces = [
                new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
                new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
                new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
                new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
                new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
                new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
            ];
            return CubeMapToSphericalPolynomialTools;
        }());
        Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        /**
         * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
         */
        var PanoramaToCubeMapTools = (function () {
            function PanoramaToCubeMapTools() {
            }
            /**
             * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
             *
             * @param float32Array The source data.
             * @param inputWidth The width of the input panorama.
             * @param inputhHeight The height of the input panorama.
             * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
             * @return The cubemap data
             */
            PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
                if (!float32Array) {
                    throw "ConvertPanoramaToCubemap: input cannot be null";
                }
                if (float32Array.length != inputWidth * inputHeight * 3) {
                    throw "ConvertPanoramaToCubemap: input size is wrong";
                }
                var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
                var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
                var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
                var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
                var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
                var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
                return {
                    front: textureFront,
                    back: textureBack,
                    left: textureLeft,
                    right: textureRight,
                    up: textureUp,
                    down: textureDown,
                    size: size
                };
            };
            PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
                var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
                var textureArray = new Float32Array(buffer);
                var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
                var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
                var dy = 1 / texSize;
                var fy = 0;
                for (var y = 0; y < texSize; y++) {
                    var xv1 = faceData[0];
                    var xv2 = faceData[2];
                    for (var x = 0; x < texSize; x++) {
                        var v = xv2.subtract(xv1).scale(fy).add(xv1);
                        v.normalize();
                        var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
                        // 3 channels per pixels
                        textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
                        textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
                        textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
                        xv1 = xv1.add(rotDX1);
                        xv2 = xv2.add(rotDX2);
                    }
                    fy += dy;
                }
                return textureArray;
            };
            PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
                var theta = Math.atan2(vDir.z, vDir.x);
                var phi = Math.acos(vDir.y);
                while (theta < -Math.PI)
                    theta += 2 * Math.PI;
                while (theta > Math.PI)
                    theta -= 2 * Math.PI;
                var dx = theta / Math.PI;
                var dy = phi / Math.PI;
                // recenter.
                dx = dx * 0.5 + 0.5;
                var px = Math.round(dx * inputWidth);
                if (px < 0)
                    px = 0;
                else if (px >= inputWidth)
                    px = inputWidth - 1;
                var py = Math.round(dy * inputHeight);
                if (py < 0)
                    py = 0;
                else if (py >= inputHeight)
                    py = inputHeight - 1;
                var inputY = (inputHeight - py - 1);
                var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
                var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
                var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
                return {
                    r: r,
                    g: g,
                    b: b
                };
            };
            PanoramaToCubeMapTools.FACE_FRONT = [
                new BABYLON.Vector3(-1.0, -1.0, -1.0),
                new BABYLON.Vector3(1.0, -1.0, -1.0),
                new BABYLON.Vector3(-1.0, 1.0, -1.0),
                new BABYLON.Vector3(1.0, 1.0, -1.0)
            ];
            PanoramaToCubeMapTools.FACE_BACK = [
                new BABYLON.Vector3(1.0, -1.0, 1.0),
                new BABYLON.Vector3(-1.0, -1.0, 1.0),
                new BABYLON.Vector3(1.0, 1.0, 1.0),
                new BABYLON.Vector3(-1.0, 1.0, 1.0)
            ];
            PanoramaToCubeMapTools.FACE_RIGHT = [
                new BABYLON.Vector3(1.0, -1.0, -1.0),
                new BABYLON.Vector3(1.0, -1.0, 1.0),
                new BABYLON.Vector3(1.0, 1.0, -1.0),
                new BABYLON.Vector3(1.0, 1.0, 1.0)
            ];
            PanoramaToCubeMapTools.FACE_LEFT = [
                new BABYLON.Vector3(-1.0, -1.0, 1.0),
                new BABYLON.Vector3(-1.0, -1.0, -1.0),
                new BABYLON.Vector3(-1.0, 1.0, 1.0),
                new BABYLON.Vector3(-1.0, 1.0, -1.0)
            ];
            PanoramaToCubeMapTools.FACE_DOWN = [
                new BABYLON.Vector3(-1.0, 1.0, -1.0),
                new BABYLON.Vector3(1.0, 1.0, -1.0),
                new BABYLON.Vector3(-1.0, 1.0, 1.0),
                new BABYLON.Vector3(1.0, 1.0, 1.0)
            ];
            PanoramaToCubeMapTools.FACE_UP = [
                new BABYLON.Vector3(-1.0, -1.0, 1.0),
                new BABYLON.Vector3(1.0, -1.0, 1.0),
                new BABYLON.Vector3(-1.0, -1.0, -1.0),
                new BABYLON.Vector3(1.0, -1.0, -1.0)
            ];
            return PanoramaToCubeMapTools;
        }());
        Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
 
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        ;
        /**
         * This groups tools to convert HDR texture to native colors array.
         */
        var HDRTools = (function () {
            function HDRTools() {
            }
            HDRTools.Ldexp = function (mantissa, exponent) {
                if (exponent > 1023) {
                    return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
                }
                if (exponent < -1074) {
                    return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
                }
                return mantissa * Math.pow(2, exponent);
            };
            HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
                if (exponent > 0) {
                    exponent = this.Ldexp(1.0, exponent - (128 + 8));
                    float32array[index + 0] = red * exponent;
                    float32array[index + 1] = green * exponent;
                    float32array[index + 2] = blue * exponent;
                }
                else {
                    float32array[index + 0] = 0;
                    float32array[index + 1] = 0;
                    float32array[index + 2] = 0;
                }
            };
            HDRTools.readStringLine = function (uint8array, startIndex) {
                var line = "";
                var character = "";
                for (var i = startIndex; i < uint8array.length - startIndex; i++) {
                    character = String.fromCharCode(uint8array[i]);
                    if (character == "\n") {
                        break;
                    }
                    line += character;
                }
                return line;
            };
            /**
             * Reads header information from an RGBE texture stored in a native array.
             * More information on this format are available here:
             * https://en.wikipedia.org/wiki/RGBE_image_format
             *
             * @param uint8array The binary file stored in  native array.
             * @return The header information.
             */
            HDRTools.RGBE_ReadHeader = function (uint8array) {
                var height = 0;
                var width = 0;
                var line = this.readStringLine(uint8array, 0);
                if (line[0] != '#' || line[1] != '?') {
                    throw "Bad HDR Format.";
                }
                var endOfHeader = false;
                var findFormat = false;
                var lineIndex = 0;
                do {
                    lineIndex += (line.length + 1);
                    line = this.readStringLine(uint8array, lineIndex);
                    if (line == "FORMAT=32-bit_rle_rgbe") {
                        findFormat = true;
                    }
                    else if (line.length == 0) {
                        endOfHeader = true;
                    }
                } while (!endOfHeader);
                if (!findFormat) {
                    throw "HDR Bad header format, unsupported FORMAT";
                }
                lineIndex += (line.length + 1);
                line = this.readStringLine(uint8array, lineIndex);
                var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
                var match = sizeRegexp.exec(line);
                // TODO. Support +Y and -X if needed.
                if (match.length < 3) {
                    throw "HDR Bad header format, no size";
                }
                width = parseInt(match[2]);
                height = parseInt(match[1]);
                if (width < 8 || width > 0x7fff) {
                    throw "HDR Bad header format, unsupported size";
                }
                lineIndex += (line.length + 1);
                return {
                    height: height,
                    width: width,
                    dataPosition: lineIndex
                };
            };
            /**
             * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
             * This RGBE texture needs to store the information as a panorama.
             *
             * More information on this format are available here:
             * https://en.wikipedia.org/wiki/RGBE_image_format
             *
             * @param buffer The binary file stored in an array buffer.
             * @param size The expected size of the extracted cubemap.
             * @return The Cube Map information.
             */
            HDRTools.GetCubeMapTextureData = function (buffer, size) {
                var uint8array = new Uint8Array(buffer);
                var hdrInfo = this.RGBE_ReadHeader(uint8array);
                var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
                var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
                return cubeMapData;
            };
            /**
             * Returns the pixels data extracted from an RGBE texture.
             * This pixels will be stored left to right up to down in the R G B order in one array.
             *
             * More information on this format are available here:
             * https://en.wikipedia.org/wiki/RGBE_image_format
             *
             * @param uint8array The binary file stored in an array buffer.
             * @param hdrInfo The header information of the file.
             * @return The pixels data in RGB right to left up to down order.
             */
            HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
                // Keep for multi format supports.
                return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
            };
            HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
                var num_scanlines = hdrInfo.height;
                var scanline_width = hdrInfo.width;
                var a, b, c, d, count;
                var dataIndex = hdrInfo.dataPosition;
                var index = 0, endIndex = 0, i = 0;
                var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
                var scanLineArray = new Uint8Array(scanLineArrayBuffer);
                // 3 channels of 4 bytes per pixel in float.
                var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
                var resultArray = new Float32Array(resultBuffer);
                // read in each successive scanline
                while (num_scanlines > 0) {
                    a = uint8array[dataIndex++];
                    b = uint8array[dataIndex++];
                    c = uint8array[dataIndex++];
                    d = uint8array[dataIndex++];
                    if (a != 2 || b != 2 || (c & 0x80)) {
                        // this file is not run length encoded
                        throw "HDR Bad header format, not RLE";
                    }
                    if (((c << 8) | d) != scanline_width) {
                        throw "HDR Bad header format, wrong scan line width";
                    }
                    index = 0;
                    // read each of the four channels for the scanline into the buffer
                    for (i = 0; i < 4; i++) {
                        endIndex = (i + 1) * scanline_width;
                        while (index < endIndex) {
                            a = uint8array[dataIndex++];
                            b = uint8array[dataIndex++];
                            if (a > 128) {
                                // a run of the same value
                                count = a - 128;
                                if ((count == 0) || (count > endIndex - index)) {
                                    throw "HDR Bad Format, bad scanline data (run)";
                                }
                                while (count-- > 0) {
                                    scanLineArray[index++] = b;
                                }
                            }
                            else {
                                // a non-run
                                count = a;
                                if ((count == 0) || (count > endIndex - index)) {
                                    throw "HDR Bad Format, bad scanline data (non-run)";
                                }
                                scanLineArray[index++] = b;
                                if (--count > 0) {
                                    for (var j = 0; j < count; j++) {
                                        scanLineArray[index++] = uint8array[dataIndex++];
                                    }
                                }
                            }
                        }
                    }
                    // now convert data from buffer into floats
                    for (i = 0; i < scanline_width; i++) {
                        a = scanLineArray[i];
                        b = scanLineArray[i + scanline_width];
                        c = scanLineArray[i + 2 * scanline_width];
                        d = scanLineArray[i + 3 * scanline_width];
                        this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
                    }
                    num_scanlines--;
                }
                return resultArray;
            };
            return HDRTools;
        }());
        Internals.HDRTools = HDRTools;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.hdr.js.map
 
//_______________________________________________________________
// Extracted from CubeMapGen: 
// https://code.google.com/archive/p/cubemapgen/
//
// Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
//_______________________________________________________________
var BABYLON;
(function (BABYLON) {
    var Internals;
    (function (Internals) {
        /**
         * The bounding box information used during the conversion process.
         */
        var CMGBoundinBox = (function () {
            function CMGBoundinBox() {
                this.min = new BABYLON.Vector3(0, 0, 0);
                this.max = new BABYLON.Vector3(0, 0, 0);
                this.clear();
            }
            CMGBoundinBox.prototype.clear = function () {
                this.min.x = CMGBoundinBox.MAX;
                this.min.y = CMGBoundinBox.MAX;
                this.min.z = CMGBoundinBox.MAX;
                this.max.x = CMGBoundinBox.MIN;
                this.max.y = CMGBoundinBox.MIN;
                this.max.z = CMGBoundinBox.MIN;
            };
            CMGBoundinBox.prototype.augment = function (x, y, z) {
                this.min.x = Math.min(this.min.x, x);
                this.min.y = Math.min(this.min.y, y);
                this.min.z = Math.min(this.min.z, z);
                this.max.x = Math.max(this.max.x, x);
                this.max.y = Math.max(this.max.y, y);
                this.max.z = Math.max(this.max.z, z);
            };
            CMGBoundinBox.prototype.clampMin = function (x, y, z) {
                this.min.x = Math.max(this.min.x, x);
                this.min.y = Math.max(this.min.y, y);
                this.min.z = Math.max(this.min.z, z);
            };
            CMGBoundinBox.prototype.clampMax = function (x, y, z) {
                this.max.x = Math.min(this.max.x, x);
                this.max.y = Math.min(this.max.y, y);
                this.max.z = Math.min(this.max.z, z);
            };
            CMGBoundinBox.prototype.empty = function () {
                if ((this.min.x > this.max.y) ||
                    (this.min.y > this.max.y) ||
                    (this.min.z > this.max.y)) {
                    return true;
                }
                else {
                    return false;
                }
            };
            CMGBoundinBox.MAX = Number.MAX_VALUE;
            CMGBoundinBox.MIN = Number.MIN_VALUE;
            return CMGBoundinBox;
        }());
        /**
         * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
         * required by the glossinees of a material.
         *
         * This only supports the cosine drop power as well as Warp fixup generation method.
         *
         * This is using the process from CubeMapGen described here:
         * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
         */
        var PMREMGenerator = (function () {
            /**
             * Constructor of the generator.
             *
             * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
             * @param inputSize The size of the cubemap faces
             * @param outputSize The size of the output cubemap faces
             * @param maxNumMipLevels The max number of mip map to generate (0 means all)
             * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
             * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
             * @param specularPower The max specular level of the desired cubemap
             * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
             * @param excludeBase Specifies wether to process the level 0 (original level) or not
             * @param fixup Specifies wether to apply the edge fixup algorythm or not
             */
            function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
                this.input = input;
                this.inputSize = inputSize;
                this.outputSize = outputSize;
                this.maxNumMipLevels = maxNumMipLevels;
                this.numChannels = numChannels;
                this.isFloat = isFloat;
                this.specularPower = specularPower;
                this.cosinePowerDropPerMip = cosinePowerDropPerMip;
                this.excludeBase = excludeBase;
                this.fixup = fixup;
                this._outputSurface = [];
                this._numMipLevels = 0;
            }
            /**
             * Launches the filter process and return the result.
             *
             * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
             */
            PMREMGenerator.prototype.filterCubeMap = function () {
                // Init cubemap processor
                this.init();
                // Filters the cubemap
                this.filterCubeMapMipChain();
                // Returns the filtered mips.
                return this._outputSurface;
            };
            PMREMGenerator.prototype.init = function () {
                var i;
                var j;
                var mipLevelSize;
                //if nax num mip levels is set to 0, set it to generate the entire mip chain
                if (this.maxNumMipLevels == 0) {
                    this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
                }
                //first miplevel size 
                mipLevelSize = this.outputSize;
                //Iterate over mip chain, and init ArrayBufferView for mip-chain
                for (j = 0; j < this.maxNumMipLevels; j++) {
                    this._outputSurface.length++;
                    this._outputSurface[j] = [];
                    //Iterate over faces for output images
                    for (i = 0; i < 6; i++) {
                        this._outputSurface[j].length++;
                        // Initializes a new array for the output.
                        if (this.isFloat) {
                            this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
                        }
                        else {
                            this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
                        }
                    }
                    //next mip level is half size
                    mipLevelSize >>= 1;
                    this._numMipLevels++;
                    //terminate if mip chain becomes too small
                    if (mipLevelSize == 0) {
                        this.maxNumMipLevels = j;
                        return;
                    }
                }
            };
            //--------------------------------------------------------------------------------------
            //Cube map filtering and mip chain generation.
            // the cube map filtereing is specified using a number of parameters:
            // Filtering per miplevel is specified using 2D cone angle (in degrees) that 
            //  indicates the region of the hemisphere to filter over for each tap. 
            //                
            // Note that the top mip level is also a filtered version of the original input images 
            //  as well in order to create mip chains for diffuse environment illumination.
            // The cone angle for the top level is specified by a_BaseAngle.  This can be used to
            //  generate mipchains used to store the resutls of preintegration across the hemisphere.
            //
            // Then the mip angle used to genreate the next level of the mip chain from the first level 
            //  is a_InitialMipAngle
            //
            // The angle for the subsequent levels of the mip chain are specified by their parents 
            //  filtering angle and a per-level scale and bias
            //   newAngle = oldAngle * a_MipAnglePerLevelScale;
            //
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.filterCubeMapMipChain = function () {
                // First, take count of the lighting model to modify SpecularPower
                // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower; 
                // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
                //Cone angle start (for generating subsequent mip levels)
                var currentSpecularPower = this.specularPower;
                //Build filter lookup tables based on the source miplevel size
                this.precomputeFilterLookupTables(this.inputSize);
                // Note that we need to filter the first level before generating mipmap
                // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
                for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
                    // TODO : Write a function to copy and scale the base mipmap in output
                    // I am just lazy here and just put a high specular power value, and do some if.
                    if (this.excludeBase && (levelIndex == 0)) {
                        // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
                        currentSpecularPower = 100000.0;
                    }
                    // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
                    var srcCubeImage = this.input;
                    var dstCubeImage = this._outputSurface[levelIndex];
                    var dstSize = this.outputSize >> levelIndex;
                    // Compute required angle.
                    var angle = this.getBaseFilterAngle(currentSpecularPower);
                    // filter cube surfaces
                    this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
                    // fix seams
                    if (this.fixup) {
                        this.fixupCubeEdges(dstCubeImage, dstSize);
                    }
                    // Decrease the specular power to generate the mipmap chain
                    // TODO : Use another method for Exclude (see first comment at start of the function
                    if (this.excludeBase && (levelIndex == 0)) {
                        currentSpecularPower = this.specularPower;
                    }
                    currentSpecularPower *= this.cosinePowerDropPerMip;
                }
            };
            //--------------------------------------------------------------------------------------
            // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
            // It allow to optimize the texel to access base on the specular power.
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
                // We want to find the alpha such that:
                // cos(alpha)^cosinePower = epsilon
                // That's: acos(epsilon^(1/cosinePower))
                var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
                var angle = 180.0;
                angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
                angle *= 180.0 / Math.PI; // Convert to degree
                angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
                return angle;
            };
            //--------------------------------------------------------------------------------------
            //Builds the following lookup tables prior to filtering:
            //  -normalizer cube map
            //  -tap weight lookup table
            // 
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
                var srcTexelAngle;
                var iCubeFace;
                //clear pre-existing normalizer cube map
                this._normCubeMap = [];
                //Normalized vectors per cubeface and per-texel solid angle 
                this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
            };
            //--------------------------------------------------------------------------------------
            //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
            //
            //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
            //
            //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
            // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
            // below
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
                var iCubeFace;
                var u;
                var v;
                //iterate over cube faces
                for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
                    //First three channels for norm cube, and last channel for solid angle
                    this._normCubeMap.push(new Float32Array(size * size * 4));
                    //fast texture walk, build normalizer cube map
                    var facesData = this.input[iCubeFace];
                    for (v = 0; v < size; v++) {
                        for (u = 0; u < size; u++) {
                            var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
                            this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
                            this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
                            this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
                            var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
                            this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
                        }
                    }
                }
            };
            //--------------------------------------------------------------------------------------
            // Convert cubemap face texel coordinates and face idx to 3D vector
            // note the U and V coords are integer coords and range from 0 to size-1
            //  this routine can be used to generate a normalizer cube map
            //--------------------------------------------------------------------------------------
            // SL BEGIN
            PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
                var nvcU;
                var nvcV;
                var tempVec;
                // Change from original AMD code
                // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
                // + 0.5f is for texel center addressing
                nvcU = (2.0 * (u + 0.5) / size) - 1.0;
                nvcV = (2.0 * (v + 0.5) / size) - 1.0;
                // warp fixup
                if (fixup && size > 1) {
                    // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
                    var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
                    nvcU = a * Math.pow(nvcU, 3) + nvcU;
                    nvcV = a * Math.pow(nvcV, 3) + nvcV;
                }
                // Get current vector
                // generate x,y,z vector (xform 2d NVC coord to 3D vector)
                // U contribution
                var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
                PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
                PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
                PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
                // V contribution and Sum
                var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
                PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
                PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
                PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
                //add face axis
                var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
                PMREMGenerator._vectorTemp.x += faceAxis[0];
                PMREMGenerator._vectorTemp.y += faceAxis[1];
                PMREMGenerator._vectorTemp.z += faceAxis[2];
                //normalize vector              
                PMREMGenerator._vectorTemp.normalize();
                return PMREMGenerator._vectorTemp;
            };
            //--------------------------------------------------------------------------------------
            // Convert 3D vector to cubemap face texel coordinates and face idx 
            // note the U and V coords are integer coords and range from 0 to size-1
            //  this routine can be used to generate a normalizer cube map
            //
            // returns face IDX and texel coords
            //--------------------------------------------------------------------------------------
            // SL BEGIN
            /*
            Mapping Texture Coordinates to Cube Map Faces
            Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
            is more complicated than the other texturing targets.  The EXT_texture_cube_map extension is purposefully
            designed to be consistent with DirectX 7's cube map arrangement.  This is also consistent with the cube
            map arrangement in Pixar's RenderMan package.
            For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
            emanating from the center of a cube.  (The q coordinate can be ignored since it merely scales the vector
            without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
            selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
            the major axis direction). The target column in the table below explains how the major axis direction
            maps to the 2D image of a particular cube map target.
    
            major axis
            direction     target                              sc     tc    ma
            ----------    ---------------------------------   ---    ---   ---
            +rx          GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT   -rz    -ry   rx
            -rx          GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT   +rz    -ry   rx
            +ry          GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT   +rx    +rz   ry
            -ry          GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT   +rx    -rz   ry
            +rz          GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT   +rx    -ry   rz
            -rz          GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT   -rx    -ry   rz
    
            Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
            an updated (s,t) is calculated as follows
            s   =   ( sc/|ma| + 1 ) / 2
            t   =   ( tc/|ma| + 1 ) / 2
            If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
            (though the result may not lead to GL interruption or termination).  Once the cube map face's 2D mipmap
            set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
            */
            // Note this method return U and V in range from 0 to size-1
            // SL END
            // Store the information in vector3 for convenience (faceindex, u, v)
            PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
                var maxCoord;
                var faceIdx;
                //absolute value 3
                var absX = Math.abs(x);
                var absY = Math.abs(y);
                var absZ = Math.abs(z);
                if (absX >= absY && absX >= absZ) {
                    maxCoord = absX;
                    if (x >= 0) {
                        faceIdx = PMREMGenerator.CP_FACE_X_POS;
                    }
                    else {
                        faceIdx = PMREMGenerator.CP_FACE_X_NEG;
                    }
                }
                else if (absY >= absX && absY >= absZ) {
                    maxCoord = absY;
                    if (y >= 0) {
                        faceIdx = PMREMGenerator.CP_FACE_Y_POS;
                    }
                    else {
                        faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
                    }
                }
                else {
                    maxCoord = absZ;
                    if (z >= 0) {
                        faceIdx = PMREMGenerator.CP_FACE_Z_POS;
                    }
                    else {
                        faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
                    }
                }
                //divide through by max coord so face vector lies on cube face
                var scale = 1 / maxCoord;
                x *= scale;
                y *= scale;
                z *= scale;
                var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
                var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
                temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
                var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
                // Modify original AMD code to return value from 0 to Size - 1
                var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
                var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
                PMREMGenerator._vectorTemp.x = faceIdx;
                PMREMGenerator._vectorTemp.y = u;
                PMREMGenerator._vectorTemp.z = v;
                return PMREMGenerator._vectorTemp;
            };
            //--------------------------------------------------------------------------------------
            //Original code from Ignacio CastaÃ’o
            // This formula is from Manne ÷hrstrˆm's thesis.
            // Take two coordiantes in the range [-1, 1] that define a portion of a
            // cube face and return the area of the projection of that portion on the
            // surface of the sphere.
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.areaElement = function (x, y) {
                return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
            };
            PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
                // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
                // (+ 0.5f is for texel center addressing)
                u = (2.0 * (u + 0.5) / size) - 1.0;
                v = (2.0 * (v + 0.5) / size) - 1.0;
                // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
                var invResolution = 1.0 / size;
                // U and V are the -1..1 texture coordinate on the current face.
                // Get projected area for this texel
                var x0 = u - invResolution;
                var y0 = v - invResolution;
                var x1 = u + invResolution;
                var y1 = v + invResolution;
                var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
                return solidAngle;
            };
            //--------------------------------------------------------------------------------------
            //The key to the speed of these filtering routines is to quickly define a per-face 
            //  bounding box of pixels which enclose all the taps in the filter kernel efficiently.  
            //  Later these pixels are selectively processed based on their dot products to see if 
            //  they reside within the filtering cone.
            //
            //This is done by computing the smallest per-texel angle to get a conservative estimate 
            // of the number of texels needed to be covered in width and height order to filter the
            // region.  the bounding box for the center taps face is defined first, and if the 
            // filtereing region bleeds onto the other faces, bounding boxes for the other faces are 
            // defined next
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
                // note that pixels within these regions may be rejected 
                // based on the anlge    
                var iCubeFace;
                var u;
                var v;
                // bounding box per face to specify region to process
                var filterExtents = [];
                for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
                    filterExtents.push(new CMGBoundinBox());
                }
                // min angle a src texel can cover (in degrees)
                var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
                // angle about center tap to define filter cone
                // filter angle is 1/2 the cone angle
                var filterAngle = filterConeAngle / 2.0;
                //ensure filter angle is larger than a texel
                if (filterAngle < srcTexelAngle) {
                    filterAngle = srcTexelAngle;
                }
                //ensure filter cone is always smaller than the hemisphere
                if (filterAngle > 90.0) {
                    filterAngle = 90.0;
                }
                // the maximum number of texels in 1D the filter cone angle will cover
                //  used to determine bounding box size for filter extents
                var filterSize = Math.ceil(filterAngle / srcTexelAngle);
                // ensure conservative region always covers at least one texel
                if (filterSize < 1) {
                    filterSize = 1;
                }
                // dotProdThresh threshold based on cone angle to determine whether or not taps 
                //  reside within the cone angle
                var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
                // process required faces
                for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
                    //iterate over dst cube map face texel
                    for (v = 0; v < dstSize; v++) {
                        for (u = 0; u < dstSize; u++) {
                            //get center tap direction
                            var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
                            //clear old per-face filter extents
                            this.clearFilterExtents(filterExtents);
                            //define per-face filter extents
                            this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
                            //perform filtering of src faces using filter extents 
                            var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
                            dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
                            dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
                            dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
                        }
                    }
                }
            };
            //--------------------------------------------------------------------------------------
            //Clear filter extents for the 6 cube map faces
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
                for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
                    filterExtents[iCubeFaces].clear();
                }
            };
            //--------------------------------------------------------------------------------------
            //Define per-face bounding box filter extents
            //
            // These define conservative texel regions in each of the faces the filter can possibly 
            // process.  When the pixels in the regions are actually processed, the dot product  
            // between the tap vector and the center tap vector is used to determine the weight of 
            // the tap and whether or not the tap is within the cone.
            //
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
                //neighboring face and bleed over amount, and width of BBOX for
                // left, right, top, and bottom edges of this face
                var bleedOverAmount = [0, 0, 0, 0];
                var bleedOverBBoxMin = [0, 0, 0, 0];
                var bleedOverBBoxMax = [0, 0, 0, 0];
                var neighborFace;
                var neighborEdge;
                var oppositeFaceIdx;
                //get face idx, and u, v info from center tap dir
                var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
                var faceIdx = result.x;
                var u = result.y;
                var v = result.z;
                //define bbox size within face
                filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
                filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
                filterExtents[faceIdx].clampMin(0, 0, 0);
                filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
                //u and v extent in face corresponding to center tap
                var minU = filterExtents[faceIdx].min.x;
                var minV = filterExtents[faceIdx].min.y;
                var maxU = filterExtents[faceIdx].max.x;
                var maxV = filterExtents[faceIdx].max.y;
                //bleed over amounts for face across u=0 edge (left)    
                bleedOverAmount[0] = (bboxSize - u);
                bleedOverBBoxMin[0] = minV;
                bleedOverBBoxMax[0] = maxV;
                //bleed over amounts for face across u=1 edge (right)    
                bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
                bleedOverBBoxMin[1] = minV;
                bleedOverBBoxMax[1] = maxV;
                //bleed over to face across v=0 edge (up)
                bleedOverAmount[2] = (bboxSize - v);
                bleedOverBBoxMin[2] = minU;
                bleedOverBBoxMax[2] = maxU;
                //bleed over to face across v=1 edge (down)
                bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
                bleedOverBBoxMin[3] = minU;
                bleedOverBBoxMax[3] = maxU;
                //compute bleed over regions in neighboring faces
                for (var i = 0; i < 4; i++) {
                    if (bleedOverAmount[i] > 0) {
                        neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
                        neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
                        //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to 
                        //  be flipped: the cases are 
                        // if a left   edge mates with a left or bottom  edge on the neighbor
                        // if a top    edge mates with a top or right edge on the neighbor
                        // if a right  edge mates with a right or top edge on the neighbor
                        // if a bottom edge mates with a bottom or left  edge on the neighbor
                        //Seeing as the edges are enumerated as follows 
                        // left   =0 
                        // right  =1 
                        // top    =2 
                        // bottom =3            
                        // 
                        // so if the edge enums are the same, or the sum of the enums == 3, 
                        //  the bbox needs to be flipped
                        if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
                            bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
                            bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
                        }
                        //The way the bounding box is extended onto the neighboring face
                        // depends on which edge of neighboring face abuts with this one
                        switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
                            case PMREMGenerator.CP_EDGE_LEFT:
                                filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
                                filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
                                break;
                            case PMREMGenerator.CP_EDGE_RIGHT:
                                filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
                                filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
                                break;
                            case PMREMGenerator.CP_EDGE_TOP:
                                filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
                                filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
                                break;
                            case PMREMGenerator.CP_EDGE_BOTTOM:
                                filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
                                filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
                                break;
                        }
                        //clamp filter extents in non-center tap faces to remain within surface
                        filterExtents[neighborFace].clampMin(0, 0, 0);
                        filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
                    }
                    //If the bleed over amount bleeds past the adjacent face onto the opposite face 
                    // from the center tap face, then process the opposite face entirely for now. 
                    //Note that the cases in which this happens, what usually happens is that 
                    // more than one edge bleeds onto the opposite face, and the bounding box 
                    // encompasses the entire cube map face.
                    if (bleedOverAmount[i] > srcSize) {
                        //determine opposite face 
                        switch (faceIdx) {
                            case PMREMGenerator.CP_FACE_X_POS:
                                oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
                                break;
                            case PMREMGenerator.CP_FACE_X_NEG:
                                oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
                                break;
                            case PMREMGenerator.CP_FACE_Y_POS:
                                oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
                                break;
                            case PMREMGenerator.CP_FACE_Y_NEG:
                                oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
                                break;
                            case PMREMGenerator.CP_FACE_Z_POS:
                                oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
                                break;
                            case PMREMGenerator.CP_FACE_Z_NEG:
                                oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
                                break;
                            default:
                                break;
                        }
                        //just encompass entire face for now
                        filterExtents[oppositeFaceIdx].augment(0, 0, 0);
                        filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
                    }
                }
            };
            //--------------------------------------------------------------------------------------
            //ProcessFilterExtents 
            //  Process bounding box in each cube face 
            //
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
                //accumulators are 64-bit floats in order to have the precision needed 
                // over a summation of a large number of pixels 
                var dstAccum = [0, 0, 0, 0];
                var weightAccum = 0;
                var k = 0;
                var nSrcChannels = this.numChannels;
                // norm cube map and srcCubeMap have same face width
                var faceWidth = srcSize;
                //amount to add to pointer to move to next scanline in images
                var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
                var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
                var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
                //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
                // iterate over cubefaces
                for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
                    //if bbox is non empty
                    if (!filterExtents[iFaceIdx].empty()) {
                        var uStart = filterExtents[iFaceIdx].min.x;
                        var vStart = filterExtents[iFaceIdx].min.y;
                        var uEnd = filterExtents[iFaceIdx].max.x;
                        var vEnd = filterExtents[iFaceIdx].max.y;
                        var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
                        var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
                        //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
                        for (var v = vStart; v <= vEnd; v++) {
                            var normCubeRowWalk = 0;
                            var srcCubeRowWalk = 0;
                            for (var u = uStart; u <= uEnd; u++) {
                                //pointer to direction in cube map associated with texel
                                var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
                                var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
                                var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
                                //check dot product to see if texel is within cone
                                var tapDotProd = texelVectX * centerTapDir.x +
                                    texelVectY * centerTapDir.y +
                                    texelVectZ * centerTapDir.z;
                                if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
                                    //solid angle stored in 4th channel of normalizer/solid angle cube map
                                    var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
                                    // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
                                    // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
                                    // so just adding one to specularpower do the trick.					   
                                    weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
                                    //iterate over channels
                                    for (k = 0; k < nSrcChannels; k++) {
                                        dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
                                        srcCubeRowWalk++;
                                    }
                                    weightAccum += weight; //accumulate weight
                                }
                                else {
                                    //step across source pixel
                                    srcCubeRowWalk += nSrcChannels;
                                }
                                normCubeRowWalk += 4; // 4 channels per norm cube map.
                            }
                            startIndexNormCubeMap += normCubePitch;
                            startIndexSrcCubeMap += srcCubePitch;
                        }
                    }
                }
                //divide through by weights if weight is non zero
                if (weightAccum != 0.0) {
                    PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
                    PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
                    PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
                    if (this.numChannels > 3) {
                        PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
                    }
                }
                else {
                    // otherwise sample nearest
                    // get face idx and u, v texel coordinate in face
                    var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
                    PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
                    PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
                    PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
                    if (this.numChannels > 3) {
                        PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
                    }
                }
                return PMREMGenerator._vectorTemp;
            };
            //--------------------------------------------------------------------------------------
            // Fixup cube edges
            //
            // average texels on cube map faces across the edges
            // WARP/BENT Method Only.
            //--------------------------------------------------------------------------------------
            PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
                var k;
                var j;
                var i;
                var iFace;
                var iCorner = 0;
                var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
                var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
                // note that if functionality to filter across the three texels for each corner, then 
                //indexed by corner and face idx. the array contains the face the start points belongs to.
                var cornerPtr = [
                    [[], [], []],
                    [[], [], []],
                    [[], [], []],
                    [[], [], []],
                    [[], [], []],
                    [[], [], []],
                    [[], [], []],
                    [[], [], []]
                ];
                //if there is no fixup, or fixup width = 0, do nothing
                if (cubeMapSize < 1) {
                    return;
                }
                //special case 1x1 cubemap, average face colors
                if (cubeMapSize == 1) {
                    //iterate over channels
                    for (k = 0; k < this.numChannels; k++) {
                        var accum = 0.0;
                        //iterate over faces to accumulate face colors
                        for (iFace = 0; iFace < 6; iFace++) {
                            accum += cubeMap[iFace][k];
                        }
                        //compute average over 6 face colors
                        accum /= 6.0;
                        //iterate over faces to distribute face colors
                        for (iFace = 0; iFace < 6; iFace++) {
                            cubeMap[iFace][k] = accum;
                        }
                    }
                    return;
                }
                //iterate over faces to collect list of corner texel pointers
                for (iFace = 0; iFace < 6; iFace++) {
                    //the 4 corner pointers for this face
                    faceCornerStartIndicies[0] = [iFace, 0];
                    faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
                    faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
                    faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
                    //iterate over face corners to collect cube corner pointers
                    for (iCorner = 0; iCorner < 4; iCorner++) {
                        var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
                        cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
                        cornerNumPtrs[corner]++;
                    }
                }
                //iterate over corners to average across corner tap values
                for (iCorner = 0; iCorner < 8; iCorner++) {
                    for (k = 0; k < this.numChannels; k++) {
                        var cornerTapAccum = 0.0;
                        //iterate over corner texels and average results
                        for (i = 0; i < 3; i++) {
                            cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
                        }
                        //divide by 3 to compute average of corner tap values
                        cornerTapAccum *= (1.0 / 3.0);
                        //iterate over corner texels and average results
                        for (i = 0; i < 3; i++) {
                            cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
                        }
                    }
                }
                //iterate over the twelve edges of the cube to average across edges
                for (i = 0; i < 12; i++) {
                    var face = PMREMGenerator._sgCubeEdgeList[i][0];
                    var edge = PMREMGenerator._sgCubeEdgeList[i][1];
                    var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
                    var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
                    var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
                    var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
                    var edgeWalk = 0;
                    var neighborEdgeWalk = 0;
                    //Determine walking pointers based on edge type
                    // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
                    switch (edge) {
                        case PMREMGenerator.CP_EDGE_LEFT:
                            // no change to faceEdgeStartPtr  
                            edgeWalk = this.numChannels * cubeMapSize;
                            break;
                        case PMREMGenerator.CP_EDGE_RIGHT:
                            edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
                            edgeWalk = this.numChannels * cubeMapSize;
                            break;
                        case PMREMGenerator.CP_EDGE_TOP:
                            // no change to faceEdgeStartPtr  
                            edgeWalk = this.numChannels;
                            break;
                        case PMREMGenerator.CP_EDGE_BOTTOM:
                            edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
                            edgeWalk = this.numChannels;
                            break;
                    }
                    //For certain types of edge abutments, the neighbor edge walk needs to 
                    //  be flipped: the cases are 
                    // if a left   edge mates with a left or bottom  edge on the neighbor
                    // if a top    edge mates with a top or right edge on the neighbor
                    // if a right  edge mates with a right or top edge on the neighbor
                    // if a bottom edge mates with a bottom or left  edge on the neighbor
                    //Seeing as the edges are enumerated as follows 
                    // left   =0 
                    // right  =1 
                    // top    =2 
                    // bottom =3            
                    // 
                    //If the edge enums are the same, or the sum of the enums == 3, 
                    //  the neighbor edge walk needs to be flipped
                    if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
                        switch (neighborEdge) {
                            case PMREMGenerator.CP_EDGE_LEFT:
                                neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
                                neighborEdgeWalk = -(this.numChannels * cubeMapSize);
                                break;
                            case PMREMGenerator.CP_EDGE_RIGHT:
                                neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
                                neighborEdgeWalk = -(this.numChannels * cubeMapSize);
                                break;
                            case PMREMGenerator.CP_EDGE_TOP:
                                neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
                                neighborEdgeWalk = -this.numChannels;
                                break;
                            case PMREMGenerator.CP_EDGE_BOTTOM:
                                neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
                                neighborEdgeWalk = -this.numChannels;
                                break;
                        }
                    }
                    else {
                        //swapped direction neighbor edge walk
                        switch (neighborEdge) {
                            case PMREMGenerator.CP_EDGE_LEFT:
                                //no change to neighborEdgeStartPtr for this case since it points 
                                // to the upper left corner already
                                neighborEdgeWalk = this.numChannels * cubeMapSize;
                                break;
                            case PMREMGenerator.CP_EDGE_RIGHT:
                                neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
                                neighborEdgeWalk = this.numChannels * cubeMapSize;
                                break;
                            case PMREMGenerator.CP_EDGE_TOP:
                                //no change to neighborEdgeStartPtr for this case since it points 
                                // to the upper left corner already
                                neighborEdgeWalk = this.numChannels;
                                break;
                            case PMREMGenerator.CP_EDGE_BOTTOM:
                                neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
                                neighborEdgeWalk = this.numChannels;
                                break;
                        }
                    }
                    //Perform edge walk, to average across the 12 edges and smoothly propagate change to 
                    //nearby neighborhood
                    //step ahead one texel on edge
                    edgeStartIndex += edgeWalk;
                    neighborEdgeStartIndex += neighborEdgeWalk;
                    // note that this loop does not process the corner texels, since they have already been
                    //  averaged across faces across earlier
                    for (j = 1; j < (cubeMapSize - 1); j++) {
                        //for each set of taps along edge, average them
                        // and rewrite the results into the edges
                        for (k = 0; k < this.numChannels; k++) {
                            var edgeTap = cubeMap[face][edgeStartIndex + k];
                            var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
                            //compute average of tap intensity values
                            var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
                            //propagate average of taps to edge taps
                            cubeMap[face][edgeStartIndex + k] = avgTap;
                            cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
                        }
                        edgeStartIndex += edgeWalk;
                        neighborEdgeStartIndex += neighborEdgeWalk;
                    }
                }
            };
            PMREMGenerator.CP_MAX_MIPLEVELS = 16;
            PMREMGenerator.CP_UDIR = 0;
            PMREMGenerator.CP_VDIR = 1;
            PMREMGenerator.CP_FACEAXIS = 2;
            //used to index cube faces
            PMREMGenerator.CP_FACE_X_POS = 0;
            PMREMGenerator.CP_FACE_X_NEG = 1;
            PMREMGenerator.CP_FACE_Y_POS = 2;
            PMREMGenerator.CP_FACE_Y_NEG = 3;
            PMREMGenerator.CP_FACE_Z_POS = 4;
            PMREMGenerator.CP_FACE_Z_NEG = 5;
            //used to index image edges
            // NOTE.. the actual number corresponding to the edge is important
            //  do not change these, or the code will break
            //
            // CP_EDGE_LEFT   is u = 0
            // CP_EDGE_RIGHT  is u = width-1
            // CP_EDGE_TOP    is v = 0
            // CP_EDGE_BOTTOM is v = height-1
            PMREMGenerator.CP_EDGE_LEFT = 0;
            PMREMGenerator.CP_EDGE_RIGHT = 1;
            PMREMGenerator.CP_EDGE_TOP = 2;
            PMREMGenerator.CP_EDGE_BOTTOM = 3;
            //corners of CUBE map (P or N specifys if it corresponds to the 
            //  positive or negative direction each of X, Y, and Z
            PMREMGenerator.CP_CORNER_NNN = 0;
            PMREMGenerator.CP_CORNER_NNP = 1;
            PMREMGenerator.CP_CORNER_NPN = 2;
            PMREMGenerator.CP_CORNER_NPP = 3;
            PMREMGenerator.CP_CORNER_PNN = 4;
            PMREMGenerator.CP_CORNER_PNP = 5;
            PMREMGenerator.CP_CORNER_PPN = 6;
            PMREMGenerator.CP_CORNER_PPP = 7;
            PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
            //3x2 matrices that map cube map indexing vectors in 3d 
            // (after face selection and divide through by the 
            //  _ABSOLUTE VALUE_ of the max coord)
            // into NVC space
            //Note this currently assumes the D3D cube face ordering and orientation
            PMREMGenerator._sgFace2DMapping = [
                //XPOS face
                [[0, 0, -1],
                    [0, -1, 0],
                    [1, 0, 0]],
                //XNEG face
                [[0, 0, 1],
                    [0, -1, 0],
                    [-1, 0, 0]],
                //YPOS face
                [[1, 0, 0],
                    [0, 0, 1],
                    [0, 1, 0]],
                //YNEG face
                [[1, 0, 0],
                    [0, 0, -1],
                    [0, -1, 0]],
                //ZPOS face
                [[1, 0, 0],
                    [0, -1, 0],
                    [0, 0, 1]],
                //ZNEG face
                [[-1, 0, 0],
                    [0, -1, 0],
                    [0, 0, -1]],
            ];
            //------------------------------------------------------------------------------
            // D3D cube map face specification
            //   mapping from 3D x,y,z cube map lookup coordinates 
            //   to 2D within face u,v coordinates
            //
            //   --------------------> U direction 
            //   |                   (within-face texture space)
            //   |         _____
            //   |        |     |
            //   |        | +Y  |
            //   |   _____|_____|_____ _____
            //   |  |     |     |     |     |
            //   |  | -X  | +Z  | +X  | -Z  |
            //   |  |_____|_____|_____|_____|
            //   |        |     |
            //   |        | -Y  |
            //   |        |_____|
            //   |
            //   v   V direction
            //      (within-face texture space)
            //------------------------------------------------------------------------------
            //Information about neighbors and how texture coorrdinates change across faces 
            //  in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0, 
            //  u=1, v=0, v=1 in the 2D coordinate system of the particular face.
            //Note this currently assumes the D3D cube face ordering and orientation
            PMREMGenerator._sgCubeNgh = [
                //XPOS face
                [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
                    [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
                    [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
                    [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
                //XNEG face
                [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
                    [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
                    [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
                    [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
                //YPOS face
                [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
                    [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
                    [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
                    [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
                //YNEG face
                [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
                    [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
                    [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
                    [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
                //ZPOS face
                [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
                    [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
                    [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
                    [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
                //ZNEG face
                [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
                    [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
                    [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
                    [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
            ];
            //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
            // this table is used to average over the edges.
            PMREMGenerator._sgCubeEdgeList = [
                [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
                [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
                [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
                [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
                [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
                [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
                [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
                [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
                [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
                [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
                [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
                [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
            ];
            //Information about which of the 8 cube corners are correspond to the 
            //  the 4 corners in each cube face
            //  the order is upper left, upper right, lower left, lower right
            PMREMGenerator._sgCubeCornerList = [
                [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
                [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
                [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
                [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
                [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
                [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
            ];
            return PMREMGenerator;
        }());
        Internals.PMREMGenerator = PMREMGenerator;
    })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.tools.pmremgenerator.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * This represents a texture coming from an HDR input.
     *
     * The only supported format is currently panorama picture stored in RGBE format.
     * Example of such files can be found on HDRLib: http://hdrlib.com/
     */
    var HDRCubeTexture = (function (_super) {
        __extends(HDRCubeTexture, _super);
        /**
         * Instantiates an HDRTexture from the following parameters.
         *
         * @param url The location of the HDR raw data (Panorama stored in RGBE format)
         * @param scene The scene the texture will be used in
         * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
         * @param noMipmap Forces to not generate the mipmap if true
         * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
         * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
         * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
         */
        function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
            if (noMipmap === void 0) { noMipmap = false; }
            if (generateHarmonics === void 0) { generateHarmonics = true; }
            if (useInGammaSpace === void 0) { useInGammaSpace = false; }
            if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
            _super.call(this, scene);
            this._useInGammaSpace = false;
            this._generateHarmonics = true;
            this._isBABYLONPreprocessed = false;
            /**
             * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
             */
            this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
            /**
             * The spherical polynomial data extracted from the texture.
             */
            this.sphericalPolynomial = null;
            /**
             * Specifies wether the texture has been generated through the PMREMGenerator tool.
             * This is usefull at run time to apply the good shader.
             */
            this.isPMREM = false;
            if (!url) {
                return;
            }
            this.name = url;
            this.url = url;
            this.hasAlpha = false;
            this.isCube = true;
            this._textureMatrix = BABYLON.Matrix.Identity();
            if (size) {
                this._isBABYLONPreprocessed = false;
                this._noMipmap = noMipmap;
                this._size = size;
                this._useInGammaSpace = useInGammaSpace;
                this._usePMREMGenerator = usePMREMGenerator &&
                    scene.getEngine().getCaps().textureLOD &&
                    this.getScene().getEngine().getCaps().textureFloat &&
                    !this._useInGammaSpace;
            }
            else {
                this._isBABYLONPreprocessed = true;
                this._noMipmap = false;
                this._useInGammaSpace = false;
                this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
                    this.getScene().getEngine().getCaps().textureFloat &&
                    !this._useInGammaSpace;
            }
            this.isPMREM = this._usePMREMGenerator;
            this._texture = this._getFromCache(url, this._noMipmap);
            if (!this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    this.loadTexture();
                }
                else {
                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                }
            }
        }
        /**
         * Occurs when the file is a preprocessed .babylon.hdr file.
         */
        HDRCubeTexture.prototype.loadBabylonTexture = function () {
            var _this = this;
            var mipLevels = 0;
            var floatArrayView = null;
            var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
                var mips = [];
                var startIndex = 30;
                for (var level = 0; level < mipLevels; level++) {
                    mips.push([]);
                    // Fill each pixel of the mip level.
                    var faceSize = Math.pow(_this._size >> level, 2) * 3;
                    for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                        var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
                        mips[level].push(faceData);
                        startIndex += faceSize;
                    }
                }
                return mips;
            } : null;
            var callback = function (buffer) {
                // Create Native Array Views
                var intArrayView = new Int32Array(buffer);
                floatArrayView = new Float32Array(buffer);
                // Fill header.
                var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
                _this._size = intArrayView[1]; // CubeMap max mip face size.
                // Update Texture Information.
                _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
                // Fill polynomial information.
                _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
                _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
                _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
                _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
                _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
                _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
                _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
                _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
                _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
                _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
                // Fill pixel data.
                mipLevels = intArrayView[29]; // Number of mip levels.
                var startIndex = 30;
                var data = [];
                var faceSize = Math.pow(_this._size, 2) * 3;
                for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                    data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
                    startIndex += faceSize;
                }
                var results = [];
                var byteArray = null;
                // Push each faces.
                for (var k = 0; k < 6; k++) {
                    var dataFace = null;
                    // If special cases.
                    if (!mipmapGenerator) {
                        var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
                        dataFace = data[j];
                        if (!_this.getScene().getEngine().getCaps().textureFloat) {
                            // 3 channels of 1 bytes per pixel in bytes.
                            var byteBuffer = new ArrayBuffer(faceSize);
                            byteArray = new Uint8Array(byteBuffer);
                        }
                        for (var i = 0; i < _this._size * _this._size; i++) {
                            // Put in gamma space if requested.
                            if (_this._useInGammaSpace) {
                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
                            }
                            // Convert to int texture for fallback.
                            if (byteArray) {
                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
                                // May use luminance instead if the result is not accurate.
                                var max = Math.max(Math.max(r, g), b);
                                if (max > 255) {
                                    var scale = 255 / max;
                                    r *= scale;
                                    g *= scale;
                                    b *= scale;
                                }
                                byteArray[(i * 3) + 0] = r;
                                byteArray[(i * 3) + 1] = g;
                                byteArray[(i * 3) + 2] = b;
                            }
                        }
                    }
                    else {
                        dataFace = data[k];
                    }
                    // Fill the array accordingly.
                    if (byteArray) {
                        results.push(byteArray);
                    }
                    else {
                        results.push(dataFace);
                    }
                }
                return results;
            };
            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
        };
        /**
         * Occurs when the file is raw .hdr file.
         */
        HDRCubeTexture.prototype.loadHDRTexture = function () {
            var _this = this;
            var callback = function (buffer) {
                // Extract the raw linear data.
                var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
                // Generate harmonics if needed.
                if (_this._generateHarmonics) {
                    _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
                }
                var results = [];
                var byteArray = null;
                // Push each faces.
                for (var j = 0; j < 6; j++) {
                    // Create uintarray fallback.
                    if (!_this.getScene().getEngine().getCaps().textureFloat) {
                        // 3 channels of 1 bytes per pixel in bytes.
                        var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
                        byteArray = new Uint8Array(byteBuffer);
                    }
                    var dataFace = data[HDRCubeTexture._facesMapping[j]];
                    // If special cases.
                    if (_this._useInGammaSpace || byteArray) {
                        for (var i = 0; i < _this._size * _this._size; i++) {
                            // Put in gamma space if requested.
                            if (_this._useInGammaSpace) {
                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
                            }
                            // Convert to int texture for fallback.
                            if (byteArray) {
                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
                                // May use luminance instead if the result is not accurate.
                                var max = Math.max(Math.max(r, g), b);
                                if (max > 255) {
                                    var scale = 255 / max;
                                    r *= scale;
                                    g *= scale;
                                    b *= scale;
                                }
                                byteArray[(i * 3) + 0] = r;
                                byteArray[(i * 3) + 1] = g;
                                byteArray[(i * 3) + 2] = b;
                            }
                        }
                    }
                    if (byteArray) {
                        results.push(byteArray);
                    }
                    else {
                        results.push(dataFace);
                    }
                }
                return results;
            };
            var mipmapGenerator = null;
            if (!this._noMipmap &&
                this._usePMREMGenerator) {
                mipmapGenerator = function (data) {
                    // Custom setup of the generator matching with the PBR shader values.
                    var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
                    return generator.filterCubeMap();
                };
            }
            this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
        };
        /**
         * Starts the loading process of the texture.
         */
        HDRCubeTexture.prototype.loadTexture = function () {
            if (this._isBABYLONPreprocessed) {
                this.loadBabylonTexture();
            }
            else {
                this.loadHDRTexture();
            }
        };
        HDRCubeTexture.prototype.clone = function () {
            var size = this._isBABYLONPreprocessed ? null : this._size;
            var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
            // Base texture
            newTexture.level = this.level;
            newTexture.wrapU = this.wrapU;
            newTexture.wrapV = this.wrapV;
            newTexture.coordinatesIndex = this.coordinatesIndex;
            newTexture.coordinatesMode = this.coordinatesMode;
            return newTexture;
        };
        // Methods
        HDRCubeTexture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, this._noMipmap);
            if (!this._texture) {
                this.loadTexture();
            }
        };
        HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
            return this._textureMatrix;
        };
        HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
            var texture = null;
            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
                var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
                texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
                texture.name = parsedTexture.name;
                texture.hasAlpha = parsedTexture.hasAlpha;
                texture.level = parsedTexture.level;
                texture.coordinatesMode = parsedTexture.coordinatesMode;
            }
            return texture;
        };
        HDRCubeTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.hasAlpha = this.hasAlpha;
            serializationObject.isCube = true;
            serializationObject.level = this.level;
            serializationObject.size = this._size;
            serializationObject.coordinatesMode = this.coordinatesMode;
            serializationObject.useInGammaSpace = this._useInGammaSpace;
            serializationObject.generateHarmonics = this._generateHarmonics;
            serializationObject.usePMREMGenerator = this._usePMREMGenerator;
            serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
            serializationObject.customType = "BABYLON.HDRCubeTexture";
            return serializationObject;
        };
        /**
         * Saves as a file the data contained in the texture in a binary format.
         * This can be used to prevent the long loading tie associated with creating the seamless texture as well
         * as the spherical used in the lighting.
         * @param url The HDR file url.
         * @param size The size of the texture data to generate (one of the cubemap face desired width).
         * @param onError Method called if any error happens during download.
         * @return The packed binary data.
         */
        HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
            if (onError === void 0) { onError = null; }
            var callback = function (buffer) {
                var data = new Blob([buffer], { type: 'application/octet-stream' });
                // Returns a URL you can use as a href.
                var objUrl = window.URL.createObjectURL(data);
                // Simulates a link to it and click to dowload.
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style.display = "none";
                a.href = objUrl;
                a.download = "envmap.babylon.hdr";
                a.click();
            };
            HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
        };
        /**
         * Serializes the data contained in the texture in a binary format.
         * This can be used to prevent the long loading tie associated with creating the seamless texture as well
         * as the spherical used in the lighting.
         * @param url The HDR file url.
         * @param size The size of the texture data to generate (one of the cubemap face desired width).
         * @param onError Method called if any error happens during download.
         * @return The packed binary data.
         */
        HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
            if (onError === void 0) { onError = null; }
            // Needs the url tho create the texture.
            if (!url) {
                return null;
            }
            // Check Power of two size.
            if (!BABYLON.Tools.IsExponentOfTwo(size)) {
                return null;
            }
            var getDataCallback = function (dataBuffer) {
                // Extract the raw linear data.
                var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
                // Generate harmonics if needed.
                var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
                // Generate seamless faces
                var mipGeneratorArray = [];
                // Data are known to be in +X +Y +Z -X -Y -Z
                // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
                mipGeneratorArray.push(cubeData.right); // +X
                mipGeneratorArray.push(cubeData.left); // -X
                mipGeneratorArray.push(cubeData.up); // +Y
                mipGeneratorArray.push(cubeData.down); // -Y
                mipGeneratorArray.push(cubeData.front); // +Z
                mipGeneratorArray.push(cubeData.back); // -Z
                // Custom setup of the generator matching with the PBR shader values.
                var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
                var mippedData = generator.filterCubeMap();
                // Compute required byte length.
                var byteLength = 1 * 4; // Raw Data Version int32.
                byteLength += 4; // CubeMap max mip face size int32.
                byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
                // Add data size.
                byteLength += 4; // Number of mip levels int32.
                for (var level = 0; level < mippedData.length; level++) {
                    var mipSize = size >> level;
                    byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
                }
                // Prepare binary structure.
                var buffer = new ArrayBuffer(byteLength);
                var intArrayView = new Int32Array(buffer);
                var floatArrayView = new Float32Array(buffer);
                // Fill header.
                intArrayView[0] = 1; // Version 1.
                intArrayView[1] = size; // CubeMap max mip face size.
                // Fill polynomial information.
                sphericalPolynomial.x.toArray(floatArrayView, 2);
                sphericalPolynomial.y.toArray(floatArrayView, 5);
                sphericalPolynomial.z.toArray(floatArrayView, 8);
                sphericalPolynomial.xx.toArray(floatArrayView, 11);
                sphericalPolynomial.yy.toArray(floatArrayView, 14);
                sphericalPolynomial.zz.toArray(floatArrayView, 17);
                sphericalPolynomial.xy.toArray(floatArrayView, 20);
                sphericalPolynomial.yz.toArray(floatArrayView, 23);
                sphericalPolynomial.zx.toArray(floatArrayView, 26);
                // Fill pixel data.
                intArrayView[29] = mippedData.length; // Number of mip levels.
                var startIndex = 30;
                for (var level = 0; level < mippedData.length; level++) {
                    // Fill each pixel of the mip level.
                    var faceSize = Math.pow(size >> level, 2) * 3;
                    for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                        floatArrayView.set(mippedData[level][faceIndex], startIndex);
                        startIndex += faceSize;
                    }
                }
                // Callback.
                callback(buffer);
            };
            // Download and process.
            BABYLON.Tools.LoadFile(url, function (data) {
                getDataCallback(data);
            }, null, null, true, onError);
        };
        HDRCubeTexture._facesMapping = [
            "right",
            "up",
            "front",
            "left",
            "down",
            "back"
        ];
        return HDRCubeTexture;
    }(BABYLON.BaseTexture));
    BABYLON.HDRCubeTexture = HDRCubeTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.hdrCubeTexture.js.map
 
var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        /**
        * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
        */
        var SkeletonViewer = (function () {
            function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
                if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
                if (renderingGroupId === void 0) { renderingGroupId = 1; }
                this.skeleton = skeleton;
                this.mesh = mesh;
                this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
                this.renderingGroupId = renderingGroupId;
                this.color = BABYLON.Color3.White();
                this._debugLines = [];
                this._isEnabled = false;
                this._scene = scene;
                this.update();
                this._renderFunction = this.update.bind(this);
            }
            Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
                get: function () {
                    return this._isEnabled;
                },
                set: function (value) {
                    if (this._isEnabled === value) {
                        return;
                    }
                    this._isEnabled = value;
                    if (value) {
                        this._scene.registerBeforeRender(this._renderFunction);
                    }
                    else {
                        this._scene.unregisterBeforeRender(this._renderFunction);
                    }
                },
                enumerable: true,
                configurable: true
            });
            SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
                if (x === void 0) { x = 0; }
                if (y === void 0) { y = 0; }
                if (z === void 0) { z = 0; }
                var tmat = BABYLON.Tmp.Matrix[0];
                var parentBone = bone.getParent();
                tmat.copyFrom(bone.getLocalMatrix());
                if (x !== 0 || y !== 0 || z !== 0) {
                    var tmat2 = BABYLON.Tmp.Matrix[1];
                    BABYLON.Matrix.IdentityToRef(tmat2);
                    tmat2.m[12] = x;
                    tmat2.m[13] = y;
                    tmat2.m[14] = z;
                    tmat2.multiplyToRef(tmat, tmat);
                }
                if (parentBone) {
                    tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
                }
                tmat.multiplyToRef(meshMat, tmat);
                position.x = tmat.m[12];
                position.y = tmat.m[13];
                position.z = tmat.m[14];
            };
            SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
                var len = bones.length;
                for (var i = 0; i < len; i++) {
                    var bone = bones[i];
                    var points = this._debugLines[i];
                    if (!points) {
                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                        this._debugLines[i] = points;
                    }
                    this._getBonePosition(points[0], bone, meshMat);
                    this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
                }
            };
            SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
                var len = bones.length;
                var boneNum = 0;
                for (var i = len - 1; i >= 0; i--) {
                    var childBone = bones[i];
                    var parentBone = childBone.getParent();
                    if (!parentBone) {
                        continue;
                    }
                    var points = this._debugLines[boneNum];
                    if (!points) {
                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                        this._debugLines[boneNum] = points;
                    }
                    childBone.getAbsolutePositionToRef(this.mesh, points[0]);
                    parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
                    boneNum++;
                }
            };
            SkeletonViewer.prototype.update = function () {
                if (this.autoUpdateBonesMatrices) {
                    this.skeleton.computeAbsoluteTransforms();
                }
                if (this.skeleton.bones[0].length === undefined) {
                    this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
                }
                else {
                    this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
                }
                if (!this._debugMesh) {
                    this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
                    this._debugMesh.renderingGroupId = this.renderingGroupId;
                }
                else {
                    BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
                }
                this._debugMesh.color = this.color;
            };
            SkeletonViewer.prototype.dispose = function () {
                if (this._debugMesh) {
                    this.isEnabled = false;
                    this._debugMesh.dispose();
                    this._debugMesh = null;
                }
            };
            return SkeletonViewer;
        }());
        Debug.SkeletonViewer = SkeletonViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.skeletonViewer.js.map
 
var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        var AxesViewer = (function () {
            function AxesViewer(scene, scaleLines) {
                if (scaleLines === void 0) { scaleLines = 1; }
                this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                this.scaleLines = 1;
                this.scaleLines = scaleLines;
                this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
                this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
                this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
                this._xmesh.renderingGroupId = 2;
                this._ymesh.renderingGroupId = 2;
                this._zmesh.renderingGroupId = 2;
                this._xmesh.material.checkReadyOnlyOnce = true;
                this._xmesh.color = new BABYLON.Color3(1, 0, 0);
                this._ymesh.material.checkReadyOnlyOnce = true;
                this._ymesh.color = new BABYLON.Color3(0, 1, 0);
                this._zmesh.material.checkReadyOnlyOnce = true;
                this._zmesh.color = new BABYLON.Color3(0, 0, 1);
                this.scene = scene;
            }
            AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
                var scaleLines = this.scaleLines;
                var point1 = this._xline[0];
                var point2 = this._xline[1];
                point1.x = position.x;
                point1.y = position.y;
                point1.z = position.z;
                point2.x = point1.x + xaxis.x * scaleLines;
                point2.y = point1.y + xaxis.y * scaleLines;
                point2.z = point1.z + xaxis.z * scaleLines;
                BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
                point1 = this._yline[0];
                point2 = this._yline[1];
                point1.x = position.x;
                point1.y = position.y;
                point1.z = position.z;
                point2.x = point1.x + yaxis.x * scaleLines;
                point2.y = point1.y + yaxis.y * scaleLines;
                point2.z = point1.z + yaxis.z * scaleLines;
                BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
                point1 = this._zline[0];
                point2 = this._zline[1];
                point1.x = position.x;
                point1.y = position.y;
                point1.z = position.z;
                point2.x = point1.x + zaxis.x * scaleLines;
                point2.y = point1.y + zaxis.y * scaleLines;
                point2.z = point1.z + zaxis.z * scaleLines;
                BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
            };
            AxesViewer.prototype.dispose = function () {
                if (this._xmesh) {
                    this._xmesh.dispose();
                    this._ymesh.dispose();
                    this._zmesh.dispose();
                    this._xmesh = null;
                    this._ymesh = null;
                    this._zmesh = null;
                    this._xline = null;
                    this._yline = null;
                    this._zline = null;
                    this.scene = null;
                }
            };
            return AxesViewer;
        }());
        Debug.AxesViewer = AxesViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.axesViewer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        var BoneAxesViewer = (function (_super) {
            __extends(BoneAxesViewer, _super);
            function BoneAxesViewer(scene, bone, mesh, scaleLines) {
                if (scaleLines === void 0) { scaleLines = 1; }
                _super.call(this, scene, scaleLines);
                this.pos = BABYLON.Vector3.Zero();
                this.xaxis = BABYLON.Vector3.Zero();
                this.yaxis = BABYLON.Vector3.Zero();
                this.zaxis = BABYLON.Vector3.Zero();
                this.mesh = mesh;
                this.bone = bone;
            }
            BoneAxesViewer.prototype.update = function () {
                var bone = this.bone;
                bone.getAbsolutePositionToRef(this.mesh, this.pos);
                bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
                bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
                bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
                _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
            };
            BoneAxesViewer.prototype.dispose = function () {
                if (this.pos) {
                    this.pos = null;
                    this.xaxis = null;
                    this.yaxis = null;
                    this.zaxis = null;
                    this.mesh = null;
                    this.bone = null;
                    _super.prototype.dispose.call(this);
                }
            };
            return BoneAxesViewer;
        }(Debug.AxesViewer));
        Debug.BoneAxesViewer = BoneAxesViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.boneAxesViewer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
     * It can help converting any input color in a desired output one. This can then be used to create effects
     * from sepia, black and white to sixties or futuristic rendering...
     *
     * The only supported format is currently 3dl.
     * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
     */
    var ColorGradingTexture = (function (_super) {
        __extends(ColorGradingTexture, _super);
        /**
         * Instantiates a ColorGradingTexture from the following parameters.
         *
         * @param url The location of the color gradind data (currently only supporting 3dl)
         * @param scene The scene the texture will be used in
         */
        function ColorGradingTexture(url, scene) {
            _super.call(this, scene);
            if (!url) {
                return;
            }
            this._textureMatrix = BABYLON.Matrix.Identity();
            this.name = url;
            this.url = url;
            this.hasAlpha = false;
            this.isCube = false;
            this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this.anisotropicFilteringLevel = 1;
            this._texture = this._getFromCache(url, true);
            if (!this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    this.loadTexture();
                }
                else {
                    this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                }
            }
        }
        /**
         * Returns the texture matrix used in most of the material.
         * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
         */
        ColorGradingTexture.prototype.getTextureMatrix = function () {
            return this._textureMatrix;
        };
        /**
         * Occurs when the file being loaded is a .3dl LUT file.
         */
        ColorGradingTexture.prototype.load3dlTexture = function () {
            var _this = this;
            var mipLevels = 0;
            var floatArrayView = null;
            var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._texture = texture;
            var callback = function (text) {
                var data;
                var tempData;
                var line;
                var lines = text.split('\n');
                var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
                var maxColor = 0;
                for (var i = 0; i < lines.length; i++) {
                    line = lines[i];
                    if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
                        continue;
                    if (line.indexOf('#') === 0)
                        continue;
                    var words = line.split(" ");
                    if (size === 0) {
                        // Number of space + one
                        size = words.length;
                        data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
                        tempData = new Float32Array(size * size * size * 4);
                        continue;
                    }
                    if (size != 0) {
                        var r = Math.max(parseInt(words[0]), 0);
                        var g = Math.max(parseInt(words[1]), 0);
                        var b = Math.max(parseInt(words[2]), 0);
                        maxColor = Math.max(r, maxColor);
                        maxColor = Math.max(g, maxColor);
                        maxColor = Math.max(b, maxColor);
                        var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
                        tempData[pixelStorageIndex + 0] = r;
                        tempData[pixelStorageIndex + 1] = g;
                        tempData[pixelStorageIndex + 2] = b;
                        tempData[pixelStorageIndex + 3] = 0;
                        pixelIndexSlice++;
                        if (pixelIndexSlice % size == 0) {
                            pixelIndexH++;
                            pixelIndexSlice = 0;
                            if (pixelIndexH % size == 0) {
                                pixelIndexW++;
                                pixelIndexH = 0;
                            }
                        }
                    }
                }
                for (var i = 0; i < tempData.length; i++) {
                    var value = tempData[i];
                    data[i] = (value / maxColor * 255);
                }
                _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
                _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
            };
            BABYLON.Tools.LoadFile(this.url, callback);
            return this._texture;
        };
        /**
         * Starts the loading process of the texture.
         */
        ColorGradingTexture.prototype.loadTexture = function () {
            if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
                this.load3dlTexture();
            }
        };
        /**
         * Clones the color gradind texture.
         */
        ColorGradingTexture.prototype.clone = function () {
            var newTexture = new ColorGradingTexture(this.url, this.getScene());
            // Base texture
            newTexture.level = this.level;
            return newTexture;
        };
        /**
         * Called during delayed load for textures.
         */
        ColorGradingTexture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, true);
            if (!this._texture) {
                this.loadTexture();
            }
        };
        /**
        * Binds the color grading to the shader.
        * @param colorGrading The texture to bind
        * @param effect The effect to bind to
        */
        ColorGradingTexture.Bind = function (colorGrading, effect) {
            effect.setTexture("cameraColorGrading2DSampler", colorGrading);
            var x = colorGrading.level; // Texture Level
            var y = colorGrading.getSize().height; // Texture Size example with 8
            var z = y - 1.0; // SizeMinusOne 8 - 1
            var w = 1 / y; // Space of 1 slice 1 / 8
            effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
            var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
            var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8					    // Space of 1 pixel in V direction, e.g. 1/8
            var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
            var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
            var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64 
            var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
            effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
        };
        /**
         * Prepare the list of uniforms associated with the ColorGrading effects.
         * @param uniformsList The list of uniforms used in the effect
         * @param samplersList The list of samplers used in the effect
         */
        ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
            uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
            samplersList.push("cameraColorGrading2DSampler");
        };
        /**
         * Parses a color grading texture serialized by Babylon.
         * @param parsedTexture The texture information being parsedTexture
         * @param scene The scene to load the texture in
         * @param rootUrl The root url of the data assets to load
         * @return A color gradind texture
         */
        ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
            var texture = null;
            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
                texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
                texture.name = parsedTexture.name;
                texture.level = parsedTexture.level;
            }
            return texture;
        };
        /**
         * Serializes the LUT texture to json format.
         */
        ColorGradingTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.level = this.level;
            serializationObject.customType = "BABYLON.ColorGradingTexture";
            return serializationObject;
        };
        /**
         * Empty line regex stored for GC.
         */
        ColorGradingTexture._noneEmptyLineRegex = /\S+/;
        return ColorGradingTexture;
    }(BABYLON.BaseTexture));
    BABYLON.ColorGradingTexture = ColorGradingTexture;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.colorGradingTexture.js.map
 
 
var BABYLON;
(function (BABYLON) {
    /**
     * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
     * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
     * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
     * corresponding to low luminance, medium luminance, and high luminance areas respectively.
     */
    var ColorCurves = (function () {
        function ColorCurves() {
            this._dirty = true;
            this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
            this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._globalHue = 30;
            this._globalDensity = 0;
            this._globalSaturation = 0;
            this._globalExposure = 0;
            this._highlightsHue = 30;
            this._highlightsDensity = 0;
            this._highlightsSaturation = 0;
            this._highlightsExposure = 0;
            this._midtonesHue = 30;
            this._midtonesDensity = 0;
            this._midtonesSaturation = 0;
            this._midtonesExposure = 0;
            this._shadowsHue = 30;
            this._shadowsDensity = 0;
            this._shadowsSaturation = 0;
            this._shadowsExposure = 0;
        }
        Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
            /**
             * Gets the global Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._globalHue;
            },
            /**
             * Sets the global Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._globalHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
            /**
             * Gets the global Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._globalDensity;
            },
            /**
             * Sets the global Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._globalDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
            /**
             * Gets the global Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._globalSaturation;
            },
            /**
             * Sets the global Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._globalSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
            /**
             * Gets the highlights Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._highlightsHue;
            },
            /**
             * Sets the highlights Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._highlightsHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
            /**
             * Gets the highlights Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._highlightsDensity;
            },
            /**
             * Sets the highlights Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._highlightsDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
            /**
             * Gets the highlights Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._highlightsSaturation;
            },
            /**
             * Sets the highlights Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._highlightsSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
            /**
             * Gets the highlights Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._highlightsExposure;
            },
            /**
             * Sets the highlights Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._highlightsExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
            /**
             * Gets the midtones Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._midtonesHue;
            },
            /**
             * Sets the midtones Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._midtonesHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
            /**
             * Gets the midtones Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._midtonesDensity;
            },
            /**
             * Sets the midtones Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._midtonesDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
            /**
             * Gets the midtones Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._midtonesSaturation;
            },
            /**
             * Sets the midtones Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._midtonesSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
            /**
             * Gets the midtones Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._midtonesExposure;
            },
            /**
             * Sets the midtones Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._midtonesExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
            /**
             * Gets the shadows Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._shadowsHue;
            },
            /**
             * Sets the shadows Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._shadowsHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
            /**
             * Gets the shadows Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._shadowsDensity;
            },
            /**
             * Sets the shadows Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._shadowsDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
            /**
             * Gets the shadows Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._shadowsSaturation;
            },
            /**
             * Sets the shadows Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._shadowsSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
            /**
             * Gets the shadows Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._shadowsExposure;
            },
            /**
             * Sets the shadows Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._shadowsExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Binds the color curves to the shader.
         * @param colorCurves The color curve to bind
         * @param effect The effect to bind to
         */
        ColorCurves.Bind = function (colorCurves, effect) {
            if (colorCurves._dirty) {
                colorCurves._dirty = false;
                // Fill in global info.
                colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
                // Compute highlights info.
                colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
                colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
                // Compute midtones info.
                colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
                colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
                // Compute shadows info.
                colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
                colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
                // Compute deltas (neutral is midtones).
                colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
                colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
            }
            effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
            effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
            effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
        };
        /**
         * Prepare the list of uniforms associated with the ColorCurves effects.
         * @param uniformsList The list of uniforms used in the effect
         */
        ColorCurves.PrepareUniforms = function (uniformsList) {
            uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
        };
        /**
         * Returns color grading data based on a hue, density, saturation and exposure value.
         * @param filterHue The hue of the color filter.
         * @param filterDensity The density of the color filter.
         * @param saturation The saturation.
         * @param exposure The exposure.
         * @param result The result data container.
         */
        ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
            if (hue == null) {
                return;
            }
            hue = ColorCurves.clamp(hue, 0, 360);
            density = ColorCurves.clamp(density, -100, 100);
            saturation = ColorCurves.clamp(saturation, -100, 100);
            exposure = ColorCurves.clamp(exposure, -100, 100);
            // Remap the slider/config filter density with non-linear mapping and also scale by half
            // so that the maximum filter density is only 50% control. This provides fine control 
            // for small values and reasonable range.
            density = ColorCurves.applyColorGradingSliderNonlinear(density);
            density *= 0.5;
            exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
            if (density < 0) {
                density *= -1;
                hue = (hue + 180) % 360;
            }
            ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
            result.scaleToRef(2, result);
            result.a = 1 + 0.01 * saturation;
        };
        /**
         * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
         * @param value The input slider value in range [-100,100].
         * @returns Adjusted value.
         */
        ColorCurves.applyColorGradingSliderNonlinear = function (value) {
            value /= 100;
            var x = Math.abs(value);
            x = Math.pow(x, 2);
            if (value < 0) {
                x *= -1;
            }
            x *= 100;
            return x;
        };
        /**
         * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
         * @param hue The hue (H) input.
         * @param saturation The saturation (S) input.
         * @param brightness The brightness (B) input.
         * @result An RGBA color represented as Vector4.
         */
        ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
            var h = ColorCurves.clamp(hue, 0, 360);
            var s = ColorCurves.clamp(saturation / 100, 0, 1);
            var v = ColorCurves.clamp(brightness / 100, 0, 1);
            if (s === 0) {
                result.r = v;
                result.g = v;
                result.b = v;
            }
            else {
                // sector 0 to 5
                h /= 60;
                var i = Math.floor(h);
                // fractional part of h
                var f = h - i;
                var p = v * (1 - s);
                var q = v * (1 - s * f);
                var t = v * (1 - s * (1 - f));
                switch (i) {
                    case 0:
                        result.r = v;
                        result.g = t;
                        result.b = p;
                        break;
                    case 1:
                        result.r = q;
                        result.g = v;
                        result.b = p;
                        break;
                    case 2:
                        result.r = p;
                        result.g = v;
                        result.b = t;
                        break;
                    case 3:
                        result.r = p;
                        result.g = q;
                        result.b = v;
                        break;
                    case 4:
                        result.r = t;
                        result.g = p;
                        result.b = v;
                        break;
                    default:
                        result.r = v;
                        result.g = p;
                        result.b = q;
                        break;
                }
            }
            result.a = 1;
        };
        /**
         * Returns a value clamped between min and max
         * @param value The value to clamp
         * @param min The minimum of value
         * @param max The maximum of value
         * @returns The clamped value.
         */
        ColorCurves.clamp = function (value, min, max) {
            return Math.min(Math.max(value, min), max);
        };
        /**
         * Clones the current color curve instance.
         * @return The cloned curves
         */
        ColorCurves.prototype.clone = function () {
            return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
        };
        /**
         * Serializes the current color curve instance to a json representation.
         * @return a JSON representation
         */
        ColorCurves.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        /**
         * Parses the color curve from a json representation.
         * @param source the JSON source to parse
         * @return The parsed curves
         */
        ColorCurves.Parse = function (source) {
            return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
        };
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalHue", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalDensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalSaturation", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalExposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsHue", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsDensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsSaturation", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsExposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesHue", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesDensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesSaturation", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesExposure", void 0);
        return ColorCurves;
    }());
    BABYLON.ColorCurves = ColorCurves;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.colorCurves.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var PBRMaterialDefines = (function (_super) {
        __extends(PBRMaterialDefines, _super);
        function PBRMaterialDefines() {
            _super.call(this);
            this.ALBEDO = false;
            this.AMBIENT = false;
            this.OPACITY = false;
            this.OPACITYRGB = false;
            this.REFLECTION = false;
            this.EMISSIVE = false;
            this.REFLECTIVITY = false;
            this.BUMP = false;
            this.PARALLAX = false;
            this.PARALLAXOCCLUSION = false;
            this.SPECULAROVERALPHA = false;
            this.CLIPPLANE = false;
            this.ALPHATEST = false;
            this.ALPHAFROMALBEDO = false;
            this.POINTSIZE = false;
            this.FOG = false;
            this.SPECULARTERM = false;
            this.OPACITYFRESNEL = false;
            this.EMISSIVEFRESNEL = false;
            this.FRESNEL = false;
            this.NORMAL = false;
            this.UV1 = false;
            this.UV2 = false;
            this.VERTEXCOLOR = false;
            this.VERTEXALPHA = false;
            this.NUM_BONE_INFLUENCERS = 0;
            this.BonesPerMesh = 0;
            this.INSTANCES = false;
            this.MICROSURFACEFROMREFLECTIVITYMAP = false;
            this.MICROSURFACEAUTOMATIC = false;
            this.EMISSIVEASILLUMINATION = false;
            this.LINKEMISSIVEWITHALBEDO = false;
            this.LIGHTMAP = false;
            this.USELIGHTMAPASSHADOWMAP = false;
            this.REFLECTIONMAP_3D = false;
            this.REFLECTIONMAP_SPHERICAL = false;
            this.REFLECTIONMAP_PLANAR = false;
            this.REFLECTIONMAP_CUBIC = false;
            this.REFLECTIONMAP_PROJECTION = false;
            this.REFLECTIONMAP_SKYBOX = false;
            this.REFLECTIONMAP_EXPLICIT = false;
            this.REFLECTIONMAP_EQUIRECTANGULAR = false;
            this.INVERTCUBICMAP = false;
            this.LOGARITHMICDEPTH = false;
            this.CAMERATONEMAP = false;
            this.CAMERACONTRAST = false;
            this.CAMERACOLORGRADING = false;
            this.CAMERACOLORCURVES = false;
            this.OVERLOADEDVALUES = false;
            this.OVERLOADEDSHADOWVALUES = false;
            this.USESPHERICALFROMREFLECTIONMAP = false;
            this.REFRACTION = false;
            this.REFRACTIONMAP_3D = false;
            this.LINKREFRACTIONTOTRANSPARENCY = false;
            this.REFRACTIONMAPINLINEARSPACE = false;
            this.LODBASEDMICROSFURACE = false;
            this.USEPHYSICALLIGHTFALLOFF = false;
            this.RADIANCEOVERALPHA = false;
            this.USEPMREMREFLECTION = false;
            this.USEPMREMREFRACTION = false;
            this.OPENGLNORMALMAP = false;
            this.INVERTNORMALMAPX = false;
            this.INVERTNORMALMAPY = false;
            this.SHADOWFULLFLOAT = false;
            this.METALLICWORKFLOW = false;
            this.METALLICROUGHNESSGSTOREINALPHA = false;
            this.METALLICROUGHNESSGSTOREINGREEN = false;
            this.rebuild();
        }
        return PBRMaterialDefines;
    }(BABYLON.MaterialDefines));
    /**
     * The Physically based material of BJS.
     *
     * This offers the main features of a standard PBR material.
     * For more information, please refer to the documentation :
     * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
     */
    var PBRMaterial = (function (_super) {
        __extends(PBRMaterial, _super);
        /**
         * Instantiates a new PBRMaterial instance.
         *
         * @param name The material name
         * @param scene The scene the material will be use in.
         */
        function PBRMaterial(name, scene) {
            var _this = this;
            _super.call(this, name, scene);
            /**
             * Intensity of the direct lights e.g. the four lights available in your scene.
             * This impacts both the direct diffuse and specular highlights.
             */
            this.directIntensity = 1.0;
            /**
             * Intensity of the emissive part of the material.
             * This helps controlling the emissive effect without modifying the emissive color.
             */
            this.emissiveIntensity = 1.0;
            /**
             * Intensity of the environment e.g. how much the environment will light the object
             * either through harmonics for rough material or through the refelction for shiny ones.
             */
            this.environmentIntensity = 1.0;
            /**
             * This is a special control allowing the reduction of the specular highlights coming from the
             * four lights of the scene. Those highlights may not be needed in full environment lighting.
             */
            this.specularIntensity = 1.0;
            this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
            /**
             * Debug Control allowing disabling the bump map on this material.
             */
            this.disableBumpMap = false;
            /**
             * Debug Control helping enforcing or dropping the darkness of shadows.
             * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
             */
            this.overloadedShadowIntensity = 1.0;
            /**
             * Debug Control helping dropping the shading effect coming from the diffuse lighting.
             * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
             */
            this.overloadedShadeIntensity = 1.0;
            this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            this.cameraExposure = 1.0;
            /**
             * The camera contrast used on this material.
             * This property is here and not in the camera to allow controlling contrast without full screen post process.
             */
            this.cameraContrast = 1.0;
            /**
             * Color Grading 2D Lookup Texture.
             * This allows special effects like sepia, black and white to sixties rendering style.
             */
            this.cameraColorGradingTexture = null;
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            this.cameraColorCurves = null;
            this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
            this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
            /**
             * Debug Control allowing to overload the ambient color.
             * This as to be use with the overloadedAmbientIntensity parameter.
             */
            this.overloadedAmbient = BABYLON.Color3.White();
            /**
             * Debug Control indicating how much the overloaded ambient color is used against the default one.
             */
            this.overloadedAmbientIntensity = 0.0;
            /**
             * Debug Control allowing to overload the albedo color.
             * This as to be use with the overloadedAlbedoIntensity parameter.
             */
            this.overloadedAlbedo = BABYLON.Color3.White();
            /**
             * Debug Control indicating how much the overloaded albedo color is used against the default one.
             */
            this.overloadedAlbedoIntensity = 0.0;
            /**
             * Debug Control allowing to overload the reflectivity color.
             * This as to be use with the overloadedReflectivityIntensity parameter.
             */
            this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
            /**
             * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
             */
            this.overloadedReflectivityIntensity = 0.0;
            /**
             * Debug Control allowing to overload the emissive color.
             * This as to be use with the overloadedEmissiveIntensity parameter.
             */
            this.overloadedEmissive = BABYLON.Color3.White();
            /**
             * Debug Control indicating how much the overloaded emissive color is used against the default one.
             */
            this.overloadedEmissiveIntensity = 0.0;
            this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
            /**
             * Debug Control allowing to overload the reflection color.
             * This as to be use with the overloadedReflectionIntensity parameter.
             */
            this.overloadedReflection = BABYLON.Color3.White();
            /**
             * Debug Control indicating how much the overloaded reflection color is used against the default one.
             */
            this.overloadedReflectionIntensity = 0.0;
            /**
             * Debug Control allowing to overload the microsurface.
             * This as to be use with the overloadedMicroSurfaceIntensity parameter.
             */
            this.overloadedMicroSurface = 0.0;
            /**
             * Debug Control indicating how much the overloaded microsurface is used against the default one.
             */
            this.overloadedMicroSurfaceIntensity = 0.0;
            this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
            /**
             * AKA Occlusion Texture Intensity in other nomenclature.
             */
            this.ambientTextureStrength = 1.0;
            this.ambientColor = new BABYLON.Color3(0, 0, 0);
            /**
             * AKA Diffuse Color in other nomenclature.
             */
            this.albedoColor = new BABYLON.Color3(1, 1, 1);
            /**
             * AKA Specular Color in other nomenclature.
             */
            this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
            this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
            this.emissiveColor = new BABYLON.Color3(0, 0, 0);
            /**
             * AKA Glossiness in other nomenclature.
             */
            this.microSurface = 0.9;
            /**
             * source material index of refraction (IOR)' / 'destination material IOR.
             */
            this.indexOfRefraction = 0.66;
            /**
             * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
             */
            this.invertRefractionY = false;
            /**
             * This parameters will make the material used its opacity to control how much it is refracting aginst not.
             * Materials half opaque for instance using refraction could benefit from this control.
             */
            this.linkRefractionWithTransparency = false;
            /**
             * The emissive and albedo are linked to never be more than one (Energy conservation).
             */
            this.linkEmissiveWithAlbedo = false;
            this.useLightmapAsShadowmap = false;
            /**
             * In this mode, the emissive informtaion will always be added to the lighting once.
             * A light for instance can be thought as emissive.
             */
            this.useEmissiveAsIllumination = false;
            /**
             * Secifies that the alpha is coming form the albedo channel alpha channel.
             */
            this.useAlphaFromAlbedoTexture = false;
            /**
             * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
             * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
             */
            this.useSpecularOverAlpha = true;
            /**
             * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
             */
            this.useMicroSurfaceFromReflectivityMapAlpha = false;
            /**
             * Specifies if the metallic texture contains the roughness information in its alpha channel.
             */
            this.useRoughnessFromMetallicTextureAlpha = true;
            /**
             * Specifies if the metallic texture contains the roughness information in its green channel.
             */
            this.useRoughnessFromMetallicTextureGreen = false;
            /**
             * In case the reflectivity map does not contain the microsurface information in its alpha channel,
             * The material will try to infer what glossiness each pixel should be.
             */
            this.useAutoMicroSurfaceFromReflectivityMap = false;
            /**
             * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
             * the creation of the material.
             */
            this.useScalarInLinearSpace = false;
            /**
             * BJS is using an harcoded light falloff based on a manually sets up range.
             * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
             * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
             */
            this.usePhysicalLightFalloff = true;
            /**
             * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
             * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
             */
            this.useRadianceOverAlpha = true;
            /**
             * Allows using the bump map in parallax mode.
             */
            this.useParallax = false;
            /**
             * Allows using the bump map in parallax occlusion mode.
             */
            this.useParallaxOcclusion = false;
            /**
             * Controls the scale bias of the parallax mode.
             */
            this.parallaxScaleBias = 0.05;
            /**
             * If sets to true, disables all the lights affecting the material.
             */
            this.disableLighting = false;
            /**
             * Number of Simultaneous lights allowed on the material.
             */
            this.maxSimultaneousLights = 4;
            /**
             * If sets to true, x component of normal map value will invert (x = 1.0 - x).
             */
            this.invertNormalMapX = false;
            /**
             * If sets to true, y component of normal map value will invert (y = 1.0 - y).
             */
            this.invertNormalMapY = false;
            this._renderTargets = new BABYLON.SmartArray(16);
            this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
            this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
            this._tempColor = new BABYLON.Color3();
            this._defines = new PBRMaterialDefines();
            this._cachedDefines = new PBRMaterialDefines();
            this._myScene = null;
            this._myShadowGenerator = null;
            this._cachedDefines.BonesPerMesh = -1;
            this.getRenderTargetTextures = function () {
                _this._renderTargets.reset();
                if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this.reflectionTexture);
                }
                if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this.refractionTexture);
                }
                return _this._renderTargets;
            };
        }
        Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
            get: function () {
                return this._useLogarithmicDepth;
            },
            set: function (value) {
                this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
            },
            enumerable: true,
            configurable: true
        });
        PBRMaterial.prototype.needAlphaBlending = function () {
            if (this.linkRefractionWithTransparency) {
                return false;
            }
            return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
        };
        PBRMaterial.prototype.needAlphaTesting = function () {
            if (this.linkRefractionWithTransparency) {
                return false;
            }
            return this.albedoTexture != null && this.albedoTexture.hasAlpha;
        };
        PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
            return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
        };
        PBRMaterial.prototype.getAlphaTestTexture = function () {
            return this.albedoTexture;
        };
        PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
            if (!mesh) {
                return true;
            }
            if (this._defines.INSTANCES !== useInstances) {
                return false;
            }
            if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
                return true;
            }
            return false;
        };
        PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
            PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
        };
        PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
            if (!useScalarInLinear) {
                color.toLinearSpaceToRef(ref);
            }
            else {
                ref.r = color.r;
                ref.g = color.g;
                ref.b = color.b;
            }
        };
        PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
            var lightIndex = 0;
            var depthValuesAlreadySet = false;
            for (var index = 0; index < scene.lights.length; index++) {
                var light = scene.lights[index];
                if (!light.isEnabled()) {
                    continue;
                }
                if (!light.canAffectMesh(mesh)) {
                    continue;
                }
                BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
                // GAMMA CORRECTION.
                this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
                PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
                effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
                if (defines["SPECULARTERM"]) {
                    this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
                    PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
                    effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
                }
                // Shadows
                if (scene.shadowsEnabled) {
                    depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
                }
                lightIndex++;
                if (lightIndex === maxSimultaneousLights)
                    break;
            }
        };
        PBRMaterial.prototype.isReady = function (mesh, useInstances) {
            if (this.checkReadyOnlyOnce) {
                if (this._wasPreviouslyReady) {
                    return true;
                }
            }
            var scene = this.getScene();
            var engine = scene.getEngine();
            var needNormals = false;
            var needUVs = false;
            this._defines.reset();
            if (scene.lightsEnabled && !this.disableLighting) {
                needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
            }
            if (!this.checkReadyOnEveryCall) {
                if (this._renderId === scene.getRenderId()) {
                    if (this._checkCache(scene, mesh, useInstances)) {
                        return true;
                    }
                }
            }
            if (scene.texturesEnabled) {
                if (scene.getEngine().getCaps().textureLOD) {
                    this._defines.LODBASEDMICROSFURACE = true;
                }
                if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                    if (!this.albedoTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.ALBEDO = true;
                    }
                }
                if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
                    if (!this.ambientTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.AMBIENT = true;
                    }
                }
                if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
                    if (!this.opacityTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.OPACITY = true;
                        if (this.opacityTexture.getAlphaFromRGB) {
                            this._defines.OPACITYRGB = true;
                        }
                    }
                }
                if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                    if (!this.reflectionTexture.isReady()) {
                        return false;
                    }
                    else {
                        needNormals = true;
                        this._defines.REFLECTION = true;
                        if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
                            this._defines.INVERTCUBICMAP = true;
                        }
                        this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
                        switch (this.reflectionTexture.coordinatesMode) {
                            case BABYLON.Texture.CUBIC_MODE:
                            case BABYLON.Texture.INVCUBIC_MODE:
                                this._defines.REFLECTIONMAP_CUBIC = true;
                                break;
                            case BABYLON.Texture.EXPLICIT_MODE:
                                this._defines.REFLECTIONMAP_EXPLICIT = true;
                                break;
                            case BABYLON.Texture.PLANAR_MODE:
                                this._defines.REFLECTIONMAP_PLANAR = true;
                                break;
                            case BABYLON.Texture.PROJECTION_MODE:
                                this._defines.REFLECTIONMAP_PROJECTION = true;
                                break;
                            case BABYLON.Texture.SKYBOX_MODE:
                                this._defines.REFLECTIONMAP_SKYBOX = true;
                                break;
                            case BABYLON.Texture.SPHERICAL_MODE:
                                this._defines.REFLECTIONMAP_SPHERICAL = true;
                                break;
                            case BABYLON.Texture.EQUIRECTANGULAR_MODE:
                                this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
                                break;
                        }
                        if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
                            this._defines.USESPHERICALFROMREFLECTIONMAP = true;
                            needNormals = true;
                            if (this.reflectionTexture.isPMREM) {
                                this._defines.USEPMREMREFLECTION = true;
                            }
                        }
                    }
                }
                if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
                    if (!this.lightmapTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.LIGHTMAP = true;
                        this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
                    }
                }
                if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
                    if (!this.emissiveTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.EMISSIVE = true;
                    }
                }
                if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
                    if (this.metallicTexture) {
                        if (!this.metallicTexture.isReady()) {
                            return false;
                        }
                        else {
                            needUVs = true;
                            this._defines.METALLICWORKFLOW = true;
                            this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
                            this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
                        }
                    }
                    else if (this.reflectivityTexture) {
                        if (!this.reflectivityTexture.isReady()) {
                            return false;
                        }
                        else {
                            needUVs = true;
                            this._defines.REFLECTIVITY = true;
                            this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
                            this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
                        }
                    }
                }
                if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
                    if (!this.bumpTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.BUMP = true;
                        if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                            this._defines.PARALLAX = true;
                            if (this.useParallaxOcclusion) {
                                this._defines.PARALLAXOCCLUSION = true;
                            }
                        }
                        if (this.invertNormalMapX) {
                            this._defines.INVERTNORMALMAPX = true;
                        }
                        if (this.invertNormalMapY) {
                            this._defines.INVERTNORMALMAPY = true;
                        }
                    }
                }
                if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
                    if (!this.refractionTexture.isReady()) {
                        return false;
                    }
                    else {
                        needUVs = true;
                        this._defines.REFRACTION = true;
                        this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
                        if (this.linkRefractionWithTransparency) {
                            this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
                        }
                        if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
                            this._defines.REFRACTIONMAPINLINEARSPACE = true;
                            if (this.refractionTexture.isPMREM) {
                                this._defines.USEPMREMREFRACTION = true;
                            }
                        }
                    }
                }
                if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
                    if (!this.cameraColorGradingTexture.isReady()) {
                        return false;
                    }
                    else {
                        this._defines.CAMERACOLORGRADING = true;
                    }
                }
            }
            // Effect
            if (scene.clipPlane) {
                this._defines.CLIPPLANE = true;
            }
            if (engine.getAlphaTesting()) {
                this._defines.ALPHATEST = true;
            }
            if (this._shouldUseAlphaFromAlbedoTexture()) {
                this._defines.ALPHAFROMALBEDO = true;
            }
            if (this.useEmissiveAsIllumination) {
                this._defines.EMISSIVEASILLUMINATION = true;
            }
            if (this.linkEmissiveWithAlbedo) {
                this._defines.LINKEMISSIVEWITHALBEDO = true;
            }
            if (this.useLogarithmicDepth) {
                this._defines.LOGARITHMICDEPTH = true;
            }
            if (this.cameraContrast != 1) {
                this._defines.CAMERACONTRAST = true;
            }
            if (this.cameraExposure != 1) {
                this._defines.CAMERATONEMAP = true;
            }
            if (this.cameraColorCurves) {
                this._defines.CAMERACOLORCURVES = true;
            }
            if (this.overloadedShadeIntensity != 1 ||
                this.overloadedShadowIntensity != 1) {
                this._defines.OVERLOADEDSHADOWVALUES = true;
            }
            if (this.overloadedMicroSurfaceIntensity > 0 ||
                this.overloadedEmissiveIntensity > 0 ||
                this.overloadedReflectivityIntensity > 0 ||
                this.overloadedAlbedoIntensity > 0 ||
                this.overloadedAmbientIntensity > 0 ||
                this.overloadedReflectionIntensity > 0) {
                this._defines.OVERLOADEDVALUES = true;
            }
            // Point size
            if (this.pointsCloud || scene.forcePointsCloud) {
                this._defines.POINTSIZE = true;
            }
            // Fog
            if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
                this._defines.FOG = true;
            }
            if (BABYLON.StandardMaterial.FresnelEnabled) {
                // Fresnel
                if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
                    this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
                    if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
                        this._defines.OPACITYFRESNEL = true;
                    }
                    if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
                        this._defines.EMISSIVEFRESNEL = true;
                    }
                    needNormals = true;
                    this._defines.FRESNEL = true;
                }
            }
            if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
                this._defines.SPECULAROVERALPHA = true;
            }
            if (this.usePhysicalLightFalloff) {
                this._defines.USEPHYSICALLIGHTFALLOFF = true;
            }
            if (this.useRadianceOverAlpha) {
                this._defines.RADIANCEOVERALPHA = true;
            }
            // Attribs
            if (mesh) {
                if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                    this._defines.NORMAL = true;
                }
                if (needUVs) {
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                        this._defines.UV1 = true;
                    }
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                        this._defines.UV2 = true;
                    }
                }
                if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                    this._defines.VERTEXCOLOR = true;
                    if (mesh.hasVertexAlpha) {
                        this._defines.VERTEXALPHA = true;
                    }
                }
                if (mesh.useBones && mesh.computeBonesUsingShaders) {
                    this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
                    this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
                }
                // Instances
                if (useInstances) {
                    this._defines.INSTANCES = true;
                }
            }
            // Get correct effect
            if (!this._defines.isEqual(this._cachedDefines)) {
                this._defines.cloneTo(this._cachedDefines);
                scene.resetCachedMaterial();
                // Fallbacks
                var fallbacks = new BABYLON.EffectFallbacks();
                if (this._defines.REFLECTION) {
                    fallbacks.addFallback(0, "REFLECTION");
                }
                if (this._defines.REFRACTION) {
                    fallbacks.addFallback(0, "REFRACTION");
                }
                if (this._defines.REFLECTIVITY) {
                    fallbacks.addFallback(0, "REFLECTIVITY");
                }
                if (this._defines.BUMP) {
                    fallbacks.addFallback(0, "BUMP");
                }
                if (this._defines.PARALLAX) {
                    fallbacks.addFallback(1, "PARALLAX");
                }
                if (this._defines.PARALLAXOCCLUSION) {
                    fallbacks.addFallback(0, "PARALLAXOCCLUSION");
                }
                if (this._defines.SPECULAROVERALPHA) {
                    fallbacks.addFallback(0, "SPECULAROVERALPHA");
                }
                if (this._defines.FOG) {
                    fallbacks.addFallback(1, "FOG");
                }
                if (this._defines.POINTSIZE) {
                    fallbacks.addFallback(0, "POINTSIZE");
                }
                if (this._defines.LOGARITHMICDEPTH) {
                    fallbacks.addFallback(0, "LOGARITHMICDEPTH");
                }
                BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
                if (this._defines.SPECULARTERM) {
                    fallbacks.addFallback(0, "SPECULARTERM");
                }
                if (this._defines.OPACITYFRESNEL) {
                    fallbacks.addFallback(1, "OPACITYFRESNEL");
                }
                if (this._defines.EMISSIVEFRESNEL) {
                    fallbacks.addFallback(2, "EMISSIVEFRESNEL");
                }
                if (this._defines.FRESNEL) {
                    fallbacks.addFallback(3, "FRESNEL");
                }
                if (this._defines.NUM_BONE_INFLUENCERS > 0) {
                    fallbacks.addCPUSkinningFallback(0, mesh);
                }
                //Attributes
                var attribs = [BABYLON.VertexBuffer.PositionKind];
                if (this._defines.NORMAL) {
                    attribs.push(BABYLON.VertexBuffer.NormalKind);
                }
                if (this._defines.UV1) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                }
                if (this._defines.UV2) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (this._defines.VERTEXCOLOR) {
                    attribs.push(BABYLON.VertexBuffer.ColorKind);
                }
                BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
                BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
                // Legacy browser patch
                var join = this._defines.toString();
                var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
                    "vFogInfos", "vFogColor", "pointSize",
                    "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
                    "mBones",
                    "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
                    "depthValues",
                    "opacityParts", "emissiveLeftColor", "emissiveRightColor",
                    "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
                    "logarithmicDepthConstant",
                    "vSphericalX", "vSphericalY", "vSphericalZ",
                    "vSphericalXX", "vSphericalYY", "vSphericalZZ",
                    "vSphericalXY", "vSphericalYZ", "vSphericalZX",
                    "vMicrosurfaceTextureLods",
                    "vCameraInfos"
                ];
                var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
                BABYLON.ColorCurves.PrepareUniforms(uniforms);
                BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
                BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
                this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
            }
            if (!this._effect.isReady()) {
                return false;
            }
            this._renderId = scene.getRenderId();
            this._wasPreviouslyReady = true;
            if (mesh) {
                if (!mesh._materialDefines) {
                    mesh._materialDefines = new PBRMaterialDefines();
                }
                this._defines.cloneTo(mesh._materialDefines);
            }
            return true;
        };
        PBRMaterial.prototype.unbind = function () {
            if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
                this._effect.setTexture("reflection2DSampler", null);
            }
            if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
                this._effect.setTexture("refraction2DSampler", null);
            }
            _super.prototype.unbind.call(this);
        };
        PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
            this._effect.setMatrix("world", world);
        };
        PBRMaterial.prototype.bind = function (world, mesh) {
            this._myScene = this.getScene();
            // Matrices        
            this.bindOnlyWorldMatrix(world);
            // Bones
            BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
            if (this._myScene.getCachedMaterial() !== this) {
                this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
                if (BABYLON.StandardMaterial.FresnelEnabled) {
                    if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
                        this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
                    }
                    if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
                        this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
                        this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
                    }
                }
                // Textures        
                if (this._myScene.texturesEnabled) {
                    if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                        this._effect.setTexture("albedoSampler", this.albedoTexture);
                        this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
                        this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
                    }
                    if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
                        this._effect.setTexture("ambientSampler", this.ambientTexture);
                        this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
                        this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
                    }
                    if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
                        this._effect.setTexture("opacitySampler", this.opacityTexture);
                        this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
                        this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
                    }
                    if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
                        if (this.reflectionTexture.isCube) {
                            this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
                        }
                        else {
                            this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
                        }
                        this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
                        this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
                        if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
                            this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
                            this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
                            this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
                            this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
                            this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
                            this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
                            this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
                            this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
                            this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
                        }
                    }
                    if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
                        this._effect.setTexture("emissiveSampler", this.emissiveTexture);
                        this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
                        this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
                    }
                    if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
                        this._effect.setTexture("lightmapSampler", this.lightmapTexture);
                        this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
                        this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
                    }
                    if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
                        if (this.metallicTexture) {
                            this._effect.setTexture("reflectivitySampler", this.metallicTexture);
                            this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
                            this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
                        }
                        else if (this.reflectivityTexture) {
                            this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
                            this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
                            this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
                        }
                    }
                    if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
                        this._effect.setTexture("bumpSampler", this.bumpTexture);
                        this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
                        this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
                    }
                    if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
                        this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
                        var depth = 1.0;
                        if (this.refractionTexture.isCube) {
                            this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
                        }
                        else {
                            this._effect.setTexture("refraction2DSampler", this.refractionTexture);
                            this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
                            if (this.refractionTexture.depth) {
                                depth = this.refractionTexture.depth;
                            }
                        }
                        this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
                    }
                    if ((this.reflectionTexture || this.refractionTexture)) {
                        this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
                    }
                    if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
                        BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
                    }
                }
                // Clip plane
                BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
                // Point size
                if (this.pointsCloud) {
                    this._effect.setFloat("pointSize", this.pointSize);
                }
                // Colors
                this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
                // GAMMA CORRECTION.
                this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
                this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
                this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
                this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
                // GAMMA CORRECTION.
                this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
                this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
                // GAMMA CORRECTION.
                this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
                this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
            }
            if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
                // GAMMA CORRECTION.
                this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
                this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
                // Lights
                if (this._myScene.lightsEnabled && !this.disableLighting) {
                    PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
                }
                // View
                if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
                    this._effect.setMatrix("view", this._myScene.getViewMatrix());
                }
                // Fog
                BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
                this._lightingInfos.x = this.directIntensity;
                this._lightingInfos.y = this.emissiveIntensity;
                this._lightingInfos.z = this.environmentIntensity;
                this._lightingInfos.w = this.specularIntensity;
                this._effect.setVector4("vLightingIntensity", this._lightingInfos);
                this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
                this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
                this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
                this._cameraInfos.x = this.cameraExposure;
                this._cameraInfos.y = this.cameraContrast;
                this._effect.setVector4("vCameraInfos", this._cameraInfos);
                if (this.cameraColorCurves) {
                    BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
                }
                this._overloadedIntensity.x = this.overloadedAmbientIntensity;
                this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
                this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
                this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
                this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
                this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
                this._effect.setColor3("vOverloadedAmbient", this._tempColor);
                this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
                this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
                this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
                this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
                this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
                this._effect.setColor3("vOverloadedEmissive", this._tempColor);
                this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
                this._effect.setColor3("vOverloadedReflection", this._tempColor);
                this._overloadedMicroSurface.x = this.overloadedMicroSurface;
                this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
                this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
                this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
                // Log. depth
                BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
            }
            _super.prototype.bind.call(this, world, mesh);
            this._myScene = null;
        };
        PBRMaterial.prototype.getAnimatables = function () {
            var results = [];
            if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
                results.push(this.albedoTexture);
            }
            if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
                results.push(this.ambientTexture);
            }
            if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
                results.push(this.opacityTexture);
            }
            if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
                results.push(this.reflectionTexture);
            }
            if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
                results.push(this.emissiveTexture);
            }
            if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
                results.push(this.metallicTexture);
            }
            else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
                results.push(this.reflectivityTexture);
            }
            if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
                results.push(this.bumpTexture);
            }
            if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
                results.push(this.lightmapTexture);
            }
            if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
                results.push(this.refractionTexture);
            }
            if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
                results.push(this.cameraColorGradingTexture);
            }
            return results;
        };
        PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeTextures) {
                if (this.albedoTexture) {
                    this.albedoTexture.dispose();
                }
                if (this.ambientTexture) {
                    this.ambientTexture.dispose();
                }
                if (this.opacityTexture) {
                    this.opacityTexture.dispose();
                }
                if (this.reflectionTexture) {
                    this.reflectionTexture.dispose();
                }
                if (this.emissiveTexture) {
                    this.emissiveTexture.dispose();
                }
                if (this.metallicTexture) {
                    this.metallicTexture.dispose();
                }
                if (this.reflectivityTexture) {
                    this.reflectivityTexture.dispose();
                }
                if (this.bumpTexture) {
                    this.bumpTexture.dispose();
                }
                if (this.lightmapTexture) {
                    this.lightmapTexture.dispose();
                }
                if (this.refractionTexture) {
                    this.refractionTexture.dispose();
                }
                if (this.cameraColorGradingTexture) {
                    this.cameraColorGradingTexture.dispose();
                }
            }
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        PBRMaterial.prototype.clone = function (name) {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
        };
        PBRMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.PBRMaterial";
            return serializationObject;
        };
        // Statics
        PBRMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        PBRMaterial._scaledAlbedo = new BABYLON.Color3();
        PBRMaterial._scaledReflectivity = new BABYLON.Color3();
        PBRMaterial._scaledEmissive = new BABYLON.Color3();
        PBRMaterial._scaledReflection = new BABYLON.Color3();
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "directIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "emissiveIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "environmentIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "specularIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "disableBumpMap", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "cameraExposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "cameraContrast", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
        __decorate([
            BABYLON.serializeAsColorCurves()
        ], PBRMaterial.prototype, "cameraColorCurves", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], PBRMaterial.prototype, "overloadedAmbient", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], PBRMaterial.prototype, "overloadedEmissive", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], PBRMaterial.prototype, "overloadedReflection", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "albedoTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "ambientTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "opacityTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "reflectionTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "emissiveTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "reflectivityTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "metallicTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "bumpTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "lightmapTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], PBRMaterial.prototype, "refractionTexture", void 0);
        __decorate([
            BABYLON.serializeAsColor3("ambient")
        ], PBRMaterial.prototype, "ambientColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("albedo")
        ], PBRMaterial.prototype, "albedoColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("reflectivity")
        ], PBRMaterial.prototype, "reflectivityColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("reflection")
        ], PBRMaterial.prototype, "reflectionColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("emissive")
        ], PBRMaterial.prototype, "emissiveColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "microSurface", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "indexOfRefraction", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "invertRefractionY", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters()
        ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useParallax", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "disableLighting", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "invertNormalMapX", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "invertNormalMapY", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useLogarithmicDepth", null);
        return PBRMaterial;
    }(BABYLON.Material));
    BABYLON.PBRMaterial = PBRMaterial;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.pbrMaterial.js.map
 
var BABYLON;
(function (BABYLON) {
    var DebugLayer = (function () {
        function DebugLayer(scene) {
            var _this = this;
            this._transformationMatrix = BABYLON.Matrix.Identity();
            this._enabled = false;
            this._labelsEnabled = false;
            this._displayStatistics = true;
            this._displayTree = false;
            this._displayLogs = false;
            this._skeletonViewers = new Array();
            this._identityMatrix = BABYLON.Matrix.Identity();
            this.axisRatio = 0.02;
            this.accentColor = "orange";
            this._scene = scene;
            this._syncPositions = function () {
                var engine = _this._scene.getEngine();
                var canvasRect = engine.getRenderingCanvasClientRect();
                if (_this._showUI) {
                    _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
                    _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
                    _this._statsDiv.style.width = "400px";
                    _this._statsDiv.style.height = "auto";
                    _this._statsSubsetDiv.style.maxHeight = "240px";
                    _this._optionsDiv.style.left = "0px";
                    _this._optionsDiv.style.top = "10px";
                    _this._optionsDiv.style.width = "200px";
                    _this._optionsDiv.style.height = "auto";
                    _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
                    _this._logDiv.style.left = "0px";
                    _this._logDiv.style.top = (canvasRect.height - 170) + "px";
                    _this._logDiv.style.width = "600px";
                    _this._logDiv.style.height = "160px";
                    _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
                    _this._treeDiv.style.top = "10px";
                    _this._treeDiv.style.width = "300px";
                    _this._treeDiv.style.height = "auto";
                    _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
                }
                _this._globalDiv.style.left = canvasRect.left + "px";
                _this._globalDiv.style.top = canvasRect.top + "px";
                _this._drawingCanvas.style.left = "0px";
                _this._drawingCanvas.style.top = "0px";
                _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
                _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
                var devicePixelRatio = window.devicePixelRatio || 1;
                var context = _this._drawingContext;
                var backingStoreRatio = context.webkitBackingStorePixelRatio ||
                    context.mozBackingStorePixelRatio ||
                    context.msBackingStorePixelRatio ||
                    context.oBackingStorePixelRatio ||
                    context.backingStorePixelRatio || 1;
                _this._ratio = devicePixelRatio / backingStoreRatio;
                _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
                _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
            };
            this._onCanvasClick = function (evt) {
                _this._clickPosition = {
                    x: evt.clientX * _this._ratio,
                    y: evt.clientY * _this._ratio
                };
            };
            this._syncUI = function () {
                if (_this._showUI) {
                    if (_this._displayStatistics) {
                        _this._displayStats();
                        _this._statsDiv.style.display = "";
                    }
                    else {
                        _this._statsDiv.style.display = "none";
                    }
                    if (_this._displayLogs) {
                        _this._logDiv.style.display = "";
                    }
                    else {
                        _this._logDiv.style.display = "none";
                    }
                    if (_this._displayTree) {
                        _this._treeDiv.style.display = "";
                        if (_this._needToRefreshMeshesTree) {
                            _this._needToRefreshMeshesTree = false;
                            _this._refreshMeshesTreeContent();
                        }
                    }
                    else {
                        _this._treeDiv.style.display = "none";
                    }
                }
            };
            this._syncData = function () {
                if (_this._labelsEnabled || !_this._showUI) {
                    _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
                    _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
                    var engine = _this._scene.getEngine();
                    var viewport = _this._camera.viewport;
                    var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
                    // Meshes
                    var meshes = _this._camera.getActiveMeshes();
                    var index;
                    var projectedPosition;
                    for (index = 0; index < meshes.length; index++) {
                        var mesh = meshes.data[index];
                        var position = mesh.getBoundingInfo().boundingSphere.center;
                        projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
                        if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
                            _this._renderAxis(projectedPosition, mesh, globalViewport);
                        }
                        if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
                            _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
                        }
                    }
                    // Cameras
                    var cameras = _this._scene.cameras;
                    for (index = 0; index < cameras.length; index++) {
                        var camera = cameras[index];
                        if (camera === _this._camera) {
                            continue;
                        }
                        projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
                        if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
                            _this._renderLabel(camera.name, projectedPosition, 12, function () {
                                _this._camera.detachControl(engine.getRenderingCanvas());
                                _this._camera = camera;
                                _this._camera.attachControl(engine.getRenderingCanvas());
                            }, function () { return "purple"; });
                        }
                    }
                    // Lights
                    var lights = _this._scene.lights;
                    for (index = 0; index < lights.length; index++) {
                        var light = lights[index];
                        if (light.position) {
                            projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
                            if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
                                _this._renderLabel(light.name, projectedPosition, -20, function () {
                                    light.setEnabled(!light.isEnabled());
                                }, function () { return light.isEnabled() ? "orange" : "gray"; });
                            }
                        }
                    }
                }
                _this._clickPosition = undefined;
            };
        }
        DebugLayer.prototype._refreshMeshesTreeContent = function () {
            while (this._treeSubsetDiv.hasChildNodes()) {
                this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
            }
            // Add meshes
            var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
            sortedArray.sort(function (a, b) {
                if (a.name === b.name) {
                    return 0;
                }
                return (a.name > b.name) ? 1 : -1;
            });
            for (var index = 0; index < sortedArray.length; index++) {
                var mesh = sortedArray[index];
                if (!mesh.isEnabled()) {
                    continue;
                }
                this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
                    m.isVisible = element.checked;
                }, mesh);
            }
        };
        DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
            this._drawingContext.beginPath();
            this._drawingContext.moveTo(zero.x, zero.y);
            this._drawingContext.lineTo(unit.x, unit.y);
            this._drawingContext.strokeStyle = color;
            this._drawingContext.lineWidth = 4;
            this._drawingContext.stroke();
            this._drawingContext.font = "normal 14px Segoe UI";
            this._drawingContext.fillStyle = color;
            this._drawingContext.fillText(label, unitText.x, unitText.y);
        };
        DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
            var position = mesh.getBoundingInfo().boundingSphere.center;
            var worldMatrix = mesh.getWorldMatrix();
            var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
            var unit = (unprojectedVector.subtract(position)).length();
            var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
            var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
            this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
            var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
            var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
            this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
            var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
            var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
            this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
        };
        DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
            if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
                this._drawingContext.font = "normal 12px Segoe UI";
                var textMetrics = this._drawingContext.measureText(text);
                var centerX = projectedPosition.x - textMetrics.width / 2;
                var centerY = projectedPosition.y;
                var clientRect = this._drawingCanvas.getBoundingClientRect();
                if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
                    onClick();
                }
                this._drawingContext.beginPath();
                this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
                this._drawingContext.fillStyle = getFillStyle();
                this._drawingContext.globalAlpha = 0.5;
                this._drawingContext.fill();
                this._drawingContext.globalAlpha = 1.0;
                this._drawingContext.strokeStyle = '#FFFFFF';
                this._drawingContext.lineWidth = 1;
                this._drawingContext.stroke();
                this._drawingContext.fillStyle = "#FFFFFF";
                this._drawingContext.fillText(text, centerX, centerY - labelOffset);
                this._drawingContext.beginPath();
                this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
                this._drawingContext.fill();
            }
        };
        DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
            if (!this._clickPosition) {
                return false;
            }
            if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
                return false;
            }
            if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
                return false;
            }
            return true;
        };
        DebugLayer.prototype.isVisible = function () {
            return this._enabled;
        };
        DebugLayer.prototype.hide = function () {
            if (!this._enabled) {
                return;
            }
            this._enabled = false;
            var engine = this._scene.getEngine();
            this._scene.unregisterBeforeRender(this._syncData);
            this._scene.unregisterAfterRender(this._syncUI);
            this._rootElement.removeChild(this._globalDiv);
            this._scene.forceShowBoundingBoxes = false;
            this._scene.forceWireframe = false;
            BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
            BABYLON.StandardMaterial.AmbientTextureEnabled = true;
            BABYLON.StandardMaterial.SpecularTextureEnabled = true;
            BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
            BABYLON.StandardMaterial.BumpTextureEnabled = true;
            BABYLON.StandardMaterial.OpacityTextureEnabled = true;
            BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
            BABYLON.StandardMaterial.LightmapTextureEnabled = true;
            BABYLON.StandardMaterial.RefractionTextureEnabled = true;
            BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
            this._scene.shadowsEnabled = true;
            this._scene.particlesEnabled = true;
            this._scene.postProcessesEnabled = true;
            this._scene.collisionsEnabled = true;
            this._scene.lightsEnabled = true;
            this._scene.texturesEnabled = true;
            this._scene.lensFlaresEnabled = true;
            this._scene.proceduralTexturesEnabled = true;
            this._scene.renderTargetsEnabled = true;
            this._scene.probesEnabled = true;
            engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
            this._clearSkeletonViewers();
        };
        DebugLayer.prototype._clearSkeletonViewers = function () {
            for (var index = 0; index < this._skeletonViewers.length; index++) {
                this._skeletonViewers[index].dispose();
            }
            this._skeletonViewers = [];
        };
        DebugLayer.prototype.show = function (showUI, camera, rootElement) {
            if (showUI === void 0) { showUI = true; }
            if (camera === void 0) { camera = null; }
            if (rootElement === void 0) { rootElement = null; }
            if (this._enabled) {
                return;
            }
            this._enabled = true;
            if (camera) {
                this._camera = camera;
            }
            else {
                this._camera = this._scene.activeCamera;
            }
            this._showUI = showUI;
            var engine = this._scene.getEngine();
            this._globalDiv = document.createElement("div");
            this._rootElement = rootElement || document.body;
            this._rootElement.appendChild(this._globalDiv);
            this._generateDOMelements();
            engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
            this._syncPositions();
            this._scene.registerBeforeRender(this._syncData);
            this._scene.registerAfterRender(this._syncUI);
        };
        DebugLayer.prototype._clearLabels = function () {
            this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
            for (var index = 0; index < this._scene.meshes.length; index++) {
                var mesh = this._scene.meshes[index];
                mesh.renderOverlay = false;
            }
        };
        DebugLayer.prototype._generateheader = function (root, text) {
            var header = document.createElement("div");
            header.innerHTML = text + "&nbsp;";
            header.style.textAlign = "right";
            header.style.width = "100%";
            header.style.color = "white";
            header.style.backgroundColor = "Black";
            header.style.padding = "5px 5px 4px 0px";
            header.style.marginLeft = "-5px";
            header.style.fontWeight = "bold";
            root.appendChild(header);
        };
        DebugLayer.prototype._generateTexBox = function (root, title, color) {
            var label = document.createElement("label");
            label.style.display = "inline";
            label.innerHTML = title;
            label.style.color = color;
            root.appendChild(label);
            root.appendChild(document.createElement("br"));
        };
        DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
            if (tag === void 0) { tag = null; }
            var label = document.createElement("label");
            label.style.display = "inline";
            var boundingBoxesCheckbox = document.createElement("input");
            boundingBoxesCheckbox.type = "checkbox";
            boundingBoxesCheckbox.checked = initialState;
            boundingBoxesCheckbox.style.display = "inline";
            boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
            boundingBoxesCheckbox.style.verticalAlign = "sub";
            boundingBoxesCheckbox.addEventListener("change", function (evt) {
                task(evt.target, tag);
            });
            label.appendChild(boundingBoxesCheckbox);
            var container = document.createElement("span");
            var leftPart = document.createElement("span");
            var rightPart = document.createElement("span");
            rightPart.style.cssFloat = "right";
            leftPart.innerHTML = leftTitle;
            rightPart.innerHTML = rightTitle;
            rightPart.style.fontSize = "12px";
            rightPart.style.maxWidth = "200px";
            container.appendChild(leftPart);
            container.appendChild(rightPart);
            label.appendChild(container);
            root.appendChild(label);
            root.appendChild(document.createElement("br"));
        };
        DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
            if (tag === void 0) { tag = null; }
            var label = document.createElement("label");
            label.style.display = "inline";
            var checkBox = document.createElement("input");
            checkBox.type = "checkbox";
            checkBox.checked = initialState;
            checkBox.style.display = "inline";
            checkBox.style.margin = "0px 5px 0px 0px";
            checkBox.style.verticalAlign = "sub";
            checkBox.addEventListener("change", function (evt) {
                task(evt.target, tag);
            });
            label.appendChild(checkBox);
            label.appendChild(document.createTextNode(title));
            root.appendChild(label);
            root.appendChild(document.createElement("br"));
        };
        DebugLayer.prototype._generateButton = function (root, title, task, tag) {
            if (tag === void 0) { tag = null; }
            var button = document.createElement("button");
            button.innerHTML = title;
            button.style.height = "24px";
            button.style.width = "150px";
            button.style.marginBottom = "5px";
            button.style.color = "#444444";
            button.style.border = "1px solid white";
            button.className = "debugLayerButton";
            button.addEventListener("click", function (evt) {
                task(evt.target, tag);
            });
            root.appendChild(button);
            root.appendChild(document.createElement("br"));
        };
        DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
            if (tag === void 0) { tag = null; }
            var label = document.createElement("label");
            label.style.display = "inline";
            var boundingBoxesRadio = document.createElement("input");
            boundingBoxesRadio.type = "radio";
            boundingBoxesRadio.name = name;
            boundingBoxesRadio.checked = initialState;
            boundingBoxesRadio.style.display = "inline";
            boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
            boundingBoxesRadio.style.verticalAlign = "sub";
            boundingBoxesRadio.addEventListener("change", function (evt) {
                task(evt.target, tag);
            });
            label.appendChild(boundingBoxesRadio);
            label.appendChild(document.createTextNode(title));
            root.appendChild(label);
            root.appendChild(document.createElement("br"));
        };
        DebugLayer.prototype._generateDOMelements = function () {
            var _this = this;
            this._globalDiv.id = "DebugLayer";
            this._globalDiv.style.position = "absolute";
            this._globalDiv.style.fontFamily = "Segoe UI, Arial";
            this._globalDiv.style.fontSize = "14px";
            this._globalDiv.style.color = "white";
            // Drawing canvas
            this._drawingCanvas = document.createElement("canvas");
            this._drawingCanvas.id = "DebugLayerDrawingCanvas";
            this._drawingCanvas.style.position = "absolute";
            this._drawingCanvas.style.pointerEvents = "none";
            this._drawingCanvas.style.backgroundColor = "transparent";
            this._drawingContext = this._drawingCanvas.getContext("2d");
            this._globalDiv.appendChild(this._drawingCanvas);
            if (this._showUI) {
                var background = "rgba(128, 128, 128, 0.4)";
                var border = "rgb(180, 180, 180) solid 1px";
                // Stats
                this._statsDiv = document.createElement("div");
                this._statsDiv.id = "DebugLayerStats";
                this._statsDiv.style.border = border;
                this._statsDiv.style.position = "absolute";
                this._statsDiv.style.background = background;
                this._statsDiv.style.padding = "0px 0px 0px 5px";
                this._generateheader(this._statsDiv, "STATISTICS");
                this._statsSubsetDiv = document.createElement("div");
                this._statsSubsetDiv.style.paddingTop = "5px";
                this._statsSubsetDiv.style.paddingBottom = "5px";
                this._statsSubsetDiv.style.overflowY = "auto";
                this._statsDiv.appendChild(this._statsSubsetDiv);
                // Tree
                this._treeDiv = document.createElement("div");
                this._treeDiv.id = "DebugLayerTree";
                this._treeDiv.style.border = border;
                this._treeDiv.style.position = "absolute";
                this._treeDiv.style.background = background;
                this._treeDiv.style.padding = "0px 0px 0px 5px";
                this._treeDiv.style.display = "none";
                this._generateheader(this._treeDiv, "MESHES TREE");
                this._treeSubsetDiv = document.createElement("div");
                this._treeSubsetDiv.style.paddingTop = "5px";
                this._treeSubsetDiv.style.paddingRight = "5px";
                this._treeSubsetDiv.style.overflowY = "auto";
                this._treeSubsetDiv.style.maxHeight = "300px";
                this._treeDiv.appendChild(this._treeSubsetDiv);
                this._needToRefreshMeshesTree = true;
                // Logs
                this._logDiv = document.createElement("div");
                this._logDiv.style.border = border;
                this._logDiv.id = "DebugLayerLogs";
                this._logDiv.style.position = "absolute";
                this._logDiv.style.background = background;
                this._logDiv.style.padding = "0px 0px 0px 5px";
                this._logDiv.style.display = "none";
                this._generateheader(this._logDiv, "LOGS");
                this._logSubsetDiv = document.createElement("div");
                this._logSubsetDiv.style.height = "127px";
                this._logSubsetDiv.style.paddingTop = "5px";
                this._logSubsetDiv.style.overflowY = "auto";
                this._logSubsetDiv.style.fontSize = "12px";
                this._logSubsetDiv.style.fontFamily = "consolas";
                this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
                this._logDiv.appendChild(this._logSubsetDiv);
                BABYLON.Tools.OnNewCacheEntry = function (entry) {
                    _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
                };
                // Options
                this._optionsDiv = document.createElement("div");
                this._optionsDiv.id = "DebugLayerOptions";
                this._optionsDiv.style.border = border;
                this._optionsDiv.style.position = "absolute";
                this._optionsDiv.style.background = background;
                this._optionsDiv.style.padding = "0px 0px 0px 5px";
                this._optionsDiv.style.overflowY = "auto";
                this._generateheader(this._optionsDiv, "OPTIONS");
                this._optionsSubsetDiv = document.createElement("div");
                this._optionsSubsetDiv.style.paddingTop = "5px";
                this._optionsSubsetDiv.style.paddingBottom = "5px";
                this._optionsSubsetDiv.style.overflowY = "auto";
                this._optionsSubsetDiv.style.maxHeight = "200px";
                this._optionsDiv.appendChild(this._optionsSubsetDiv);
                this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
                this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
                    _this._displayTree = element.checked;
                    _this._needToRefreshMeshesTree = true;
                });
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
                this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
                    _this._labelsEnabled = element.checked;
                    if (!_this._labelsEnabled) {
                        _this._clearLabels();
                    }
                });
                this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
                    if (element.checked) {
                        BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
                    }
                    else {
                        BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
                    }
                });
                ;
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
                this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
                    if (element.checked) {
                        _this._scene.forceWireframe = false;
                        _this._scene.forcePointsCloud = false;
                    }
                });
                this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
                    if (element.checked) {
                        _this._scene.forceWireframe = true;
                        _this._scene.forcePointsCloud = false;
                    }
                });
                this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
                    if (element.checked) {
                        _this._scene.forceWireframe = false;
                        _this._scene.forcePointsCloud = true;
                    }
                });
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
                this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
                this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
                this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
                if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
                    this._optionsSubsetDiv.appendChild(document.createElement("br"));
                    this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
                    this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
                        if (element.checked) {
                            _this._scene.headphone = true;
                        }
                    });
                    this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
                        if (element.checked) {
                            _this._scene.headphone = false;
                        }
                    });
                    this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
                        _this._scene.audioEnabled = !element.checked;
                    });
                }
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
                this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
                    if (!element.checked) {
                        _this._clearSkeletonViewers();
                        return;
                    }
                    for (var index = 0; index < _this._scene.meshes.length; index++) {
                        var mesh = _this._scene.meshes[index];
                        if (mesh.skeleton) {
                            var found = false;
                            for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
                                if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
                                    found = true;
                                    break;
                                }
                            }
                            if (found) {
                                continue;
                            }
                            var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
                            viewer.isEnabled = true;
                            _this._skeletonViewers.push(viewer);
                        }
                    }
                });
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
                this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
                this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
                this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
                    if (_this._camera) {
                        console.log(_this._camera);
                    }
                    else {
                        console.warn("No camera defined, or debug layer created before camera creation!");
                    }
                });
                this._optionsSubsetDiv.appendChild(document.createElement("br"));
                this._globalDiv.appendChild(this._statsDiv);
                this._globalDiv.appendChild(this._logDiv);
                this._globalDiv.appendChild(this._optionsDiv);
                this._globalDiv.appendChild(this._treeDiv);
            }
        };
        DebugLayer.prototype._displayStats = function () {
            var scene = this._scene;
            var engine = scene.getEngine();
            var glInfo = engine.getGlInfo();
            this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
                + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
                + "<b>Count</b><br>"
                + "Total meshes: " + scene.meshes.length + "<br>"
                + "Total lights: " + scene.lights.length + "<br>"
                + "Total vertices: " + scene.getTotalVertices() + "<br>"
                + "Total materials: " + scene.materials.length + "<br>"
                + "Total textures: " + scene.textures.length + "<br>"
                + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
                + "Active indices: " + scene.getActiveIndices() + "<br>"
                + "Active bones: " + scene.getActiveBones() + "<br>"
                + "Active particles: " + scene.getActiveParticles() + "<br>"
                + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
                + "<b>Duration</b><br>"
                + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
                + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
                + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
                + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
                + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
                + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
                + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
                + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
                + "</div>"
                + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
                + "<b>Extensions</b><br>"
                + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
                + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
                + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
                + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
                + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
                + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
                + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
                + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
                + "</div><br>"
                + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
                + "<b>Caps.</b><br>"
                + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
                + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
                + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
                + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
                + "<b>Info</b><br>"
                + "WebGL feature level: " + engine.webGLVersion + "<br>"
                + glInfo.version + "<br>"
                + "</div><br>"
                + glInfo.renderer + "<br>";
            if (this.customStatsFunction) {
                this._statsSubsetDiv.innerHTML += this.customStatsFunction();
            }
        };
        return DebugLayer;
    }());
    BABYLON.DebugLayer = DebugLayer;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.debugLayer.js.map
 
 
 
 
 
 
 
var BABYLON;
(function (BABYLON) {
    var StandardRenderingPipeline = (function (_super) {
        __extends(StandardRenderingPipeline, _super);
        /**
         * @constructor
         * @param {string} name - The rendering pipeline name
         * @param {BABYLON.Scene} scene - The scene linked to this pipeline
         * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
         * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
         */
        function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
            var _this = this;
            if (originalPostProcess === void 0) { originalPostProcess = null; }
            _super.call(this, scene.getEngine(), name);
            this.downSampleX4PostProcess = null;
            this.brightPassPostProcess = null;
            this.gaussianBlurHPostProcesses = [];
            this.gaussianBlurVPostProcesses = [];
            this.textureAdderPostProcess = null;
            this.textureAdderFinalPostProcess = null;
            this.lensFlarePostProcess = null;
            this.lensFlareComposePostProcess = null;
            this.depthOfFieldPostProcess = null;
            // Values
            this.brightThreshold = 1.0;
            this.blurWidth = 2.0;
            this.gaussianCoefficient = 0.25;
            this.gaussianMean = 1.0;
            this.gaussianStandardDeviation = 1.0;
            this.exposure = 1.0;
            this.lensTexture = null;
            this.lensColorTexture = null;
            this.lensFlareStrength = 20.0;
            this.lensFlareGhostDispersal = 1.4;
            this.lensFlareHaloWidth = 0.7;
            this.lensFlareDistortionStrength = 16.0;
            this.lensStarTexture = null;
            this.lensFlareDirtTexture = null;
            this.depthOfFieldDistance = 10.0;
            // IAnimatable
            this.animations = [];
            this._depthRenderer = null;
            // Getters and setters
            this._depthOfFieldEnabled = true;
            this._lensFlareEnabled = true;
            // Initialize
            this._scene = scene;
            // Create pass post-processe
            if (!originalPostProcess) {
                this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
            }
            else {
                this.originalPostProcess = originalPostProcess;
            }
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
            // Create down sample X4 post-process
            this._createDownSampleX4PostProcess(scene, ratio / 2);
            // Create bright pass post-process
            this._createBrightPassPostProcess(scene, ratio / 2);
            // Create gaussian blur post-processes (down sampling blurs)
            this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
            this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
            this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
            this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
            // Create texture adder post-process
            this._createTextureAdderPostProcess(scene, ratio);
            // Create depth-of-field source post-process
            this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
            // Create lens flare post-process
            this._createLensFlarePostProcess(scene, ratio);
            // Create gaussian blur used by depth-of-field
            this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
            // Create depth-of-field post-process
            this._createDepthOfFieldPostProcess(scene, ratio);
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(this);
            if (cameras !== null) {
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
            }
            // Deactivate
            this.LensFlareEnabled = false;
            this.DepthOfFieldEnabled = false;
        }
        Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
            get: function () {
                return this._depthOfFieldEnabled;
            },
            set: function (enabled) {
                var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
                if (enabled && !this._depthOfFieldEnabled) {
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
                    this._depthRenderer = this._scene.enableDepthRenderer();
                }
                else if (!enabled && this._depthOfFieldEnabled) {
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
                }
                this._depthOfFieldEnabled = enabled;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
            get: function () {
                return this._lensFlareEnabled;
            },
            set: function (enabled) {
                var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
                if (enabled && !this._lensFlareEnabled) {
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
                }
                else if (!enabled && this._lensFlareEnabled) {
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
                    this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
                }
                this._lensFlareEnabled = enabled;
            },
            enumerable: true,
            configurable: true
        });
        // Down Sample X4 Post-Processs
        StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
            var _this = this;
            var downSampleX4Offsets = new Array(32);
            this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.downSampleX4PostProcess.onApply = function (effect) {
                var id = 0;
                for (var i = -2; i < 2; i++) {
                    for (var j = -2; j < 2; j++) {
                        downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
                        downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
                        id += 2;
                    }
                }
                effect.setArray2("dsOffsets", downSampleX4Offsets);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
        };
        // Brightpass Post-Process
        StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
            var _this = this;
            var brightOffsets = new Array(8);
            this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.brightPassPostProcess.onApply = function (effect) {
                var sU = (1.0 / _this.brightPassPostProcess.width);
                var sV = (1.0 / _this.brightPassPostProcess.height);
                brightOffsets[0] = -0.5 * sU;
                brightOffsets[1] = 0.5 * sV;
                brightOffsets[2] = 0.5 * sU;
                brightOffsets[3] = 0.5 * sV;
                brightOffsets[4] = -0.5 * sU;
                brightOffsets[5] = -0.5 * sV;
                brightOffsets[6] = 0.5 * sU;
                brightOffsets[7] = -0.5 * sV;
                effect.setArray2("dsOffsets", brightOffsets);
                effect.setFloat("brightThreshold", _this.brightThreshold);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
        };
        // Create gaussian blur H&V post-processes
        StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
            var _this = this;
            var blurOffsets = new Array(9);
            var blurWeights = new Array(9);
            var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
            var callback = function (height) {
                return function (effect) {
                    // Weights
                    var x = 0.0;
                    for (var i = 0; i < 9; i++) {
                        x = (i - 4.0) / 4.0;
                        blurWeights[i] =
                            _this.gaussianCoefficient
                                * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
                                * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
                    }
                    var lastOutputDimensions = {
                        width: scene.getEngine().getRenderWidth(),
                        height: scene.getEngine().getRenderHeight()
                    };
                    for (var i = 0; i < 9; i++) {
                        var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
                        blurOffsets[i] = value;
                    }
                    effect.setArray("blurOffsets", blurOffsets);
                    effect.setArray("blurWeights", blurWeights);
                    effect.setFloat("blurWidth", _this.blurWidth);
                };
            };
            // Create horizontal gaussian blur post-processes
            var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            gaussianBlurHPostProcess.onApply = callback(false);
            // Create vertical gaussian blur post-process
            var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            gaussianBlurVPostProcess.onApply = callback(true);
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
            // Finish
            this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
            this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
        };
        // Create texture adder post-process
        StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
            var _this = this;
            var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
            this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.textureAdderPostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
                effect.setTexture("lensSampler", _this.lensTexture);
                effect.setFloat("exposure", _this.exposure);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
        };
        // Create lens flare post-process
        StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
            var _this = this;
            this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
            this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
            this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
            var resolution = new BABYLON.Vector2(0, 0);
            // Lens flare
            this.lensFlarePostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
                effect.setTexture("lensColorSampler", _this.lensColorTexture);
                effect.setFloat("strength", _this.lensFlareStrength);
                effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
                effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
                // Shift
                resolution.x = _this.lensFlarePostProcess.width;
                resolution.y = _this.lensFlarePostProcess.height;
                effect.setVector2("resolution", resolution);
                effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
            };
            // Compose
            var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
            var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
            this.lensFlareComposePostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
                effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
                effect.setTexture("lensStarSampler", _this.lensStarTexture);
                // Lens start rotation matrix
                var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
                var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
                var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
                camRot *= 4.0;
                var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
                var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
                effect.setMatrix("lensStarMatrix", lensStarMatrix);
            };
        };
        // Create depth-of-field post-process
        StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
            var _this = this;
            this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.depthOfFieldPostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
                effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
                effect.setFloat("distance", _this.depthOfFieldDistance);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
        };
        // Dispose
        StandardRenderingPipeline.prototype.dispose = function () {
            for (var i = 0; i < this._scene.cameras.length; i++) {
                var camera = this._scene.cameras[i];
                this.originalPostProcess.dispose(camera);
                this.downSampleX4PostProcess.dispose(camera);
                this.brightPassPostProcess.dispose(camera);
                this.textureAdderPostProcess.dispose(camera);
                for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
                    this.gaussianBlurHPostProcesses[j].dispose(camera);
                }
                for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
                    this.gaussianBlurVPostProcesses[j].dispose(camera);
                }
                this.textureAdderFinalPostProcess.dispose(camera);
                this.lensFlarePostProcess.dispose(camera);
                this.lensFlareComposePostProcess.dispose(camera);
                this.depthOfFieldPostProcess.dispose(camera);
            }
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
            _super.prototype.dispose.call(this);
        };
        return StandardRenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
})(BABYLON || (BABYLON = {}));
 
//# sourceMappingURL=babylon.standardRenderingPipeline.js.map
 
BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n=this.z,r=this.x,o=this.y,e=this.w,s=e*e,h=n*n,a=r*r,u=o*o,m=o*n-r*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(r*o+n*e),-h-a+u+s),t.x=Math.asin(-2*(n*o-r*e)),t.y=Math.atan2(2*(n*r+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o=t.Identity();return t.SlerpToRef(i,n,r,o),o},t.SlerpToRef=function(t,i,n,r){var o,e,s=n,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}r.x=e*t.x+o*i.x,r.y=e*t.y+o*i.y,r.z=e*t.z+o*i.z,r.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+n*_+r*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,q=s*y-h*m,D=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*q)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*H-n*D+o*N)*b,t.m[15]=(i*q-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this;\n},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.prototype.getRotationMatrix=function(){var i=t.Identity();return this.getRotationMatrixToRef(i),i},t.prototype.getRotationMatrixToRef=function(i){var n=this.m,r=n[0]*n[1]*n[2]*n[3]<0?-1:1,o=n[4]*n[5]*n[6]*n[7]<0?-1:1,e=n[8]*n[9]*n[10]*n[11]<0?-1:1,s=r*Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),h=o*Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),a=e*Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]);t.FromValuesToRef(n[0]/s,n[1]/s,n[2]/s,0,n[4]/h,n[5]/h,n[6]/h,0,n[8]/a,n[9]/a,n[10]/a,0,0,0,0,1,i)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t.FromXYZAxesToRef=function(t,i,n,r){r.m[0]=t.x,r.m[1]=t.y,r.m[2]=t.z,r.m[3]=0,r.m[4]=i.x,r.m[5]=i.y,r.m[6]=i.z,r.m[7]=0,r.m[8]=n.x,r.m[9]=n.y,r.m[10]=n.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.FromQuaternionToRef=function(t,i){var n=t.x*t.x,r=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(r+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+n),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(r+n),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return n<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
    module.exports = BABYLON;
};
 
 
Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.noworker.js

npmtest-babylonjs (v0.0.1)

Code coverage report for node-npmtest-babylonjs/node_modules/babylonjs/babylon.noworker.js

Statements: 3.89% (500 / 12865)      Branches: 0.26% (32 / 12390)      Functions: 1.19% (56 / 4700)      Lines: 97.06% (33 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 3830 16 2 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1        
var __decorate=this&&this.__decorate||function(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s},__extends=this&&this.__extends||function(e,t){function i(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);i.prototype=t.prototype,e.prototype=new i},BABYLON;!(function(e){e.ToGammaSpace=1/2.2,e.ToLinearSpace=2.2,e.Epsilon=.001;var t=(function(){function e(){}return e.WithinEpsilon=function(e,t,i){void 0===i&&(i=1.401298e-45);var r=e-t;return-i<=r&&r<=i},e.ToHex=function(e){var t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()},e.Sign=function(e){return e=+e,0===e||isNaN(e)?e:e>0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e})();e.MathTools=t;var i=(function(){function i(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.r=e,this.g=t,this.b=i}return i.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},i.prototype.getClassName=function(){return"Color3"},i.prototype.getHashCode=function(){var e=this.r||0;return e=397*e^(this.g||0),e=397*e^(this.b||0)},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this},i.prototype.toColor4=function(e){return void 0===e&&(e=1),new r(this.r,this.g,this.b,e)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(e){return new i(this.r*e.r,this.g*e.g,this.b*e.b)},i.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this},i.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b},i.prototype.equalsFloats=function(e,t,i){return this.r===e&&this.g===t&&this.b===i},i.prototype.scale=function(e){return new i(this.r*e,this.g*e,this.b*e)},i.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this},i.prototype.add=function(e){return new i(this.r+e.r,this.g+e.g,this.b+e.b)},i.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this},i.prototype.subtract=function(e){return new i(this.r-e.r,this.g-e.g,this.b-e.b)},i.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},i.prototype.copyFromFloats=function(e,t,i){return this.r=e,this.g=t,this.b=i,this},i.prototype.toHexString=function(){var e=255*this.r|0,i=255*this.g|0,r=255*this.b|0;return"#"+t.ToHex(e)+t.ToHex(i)+t.ToHex(r)},i.prototype.toLinearSpace=function(){var e=new i;return this.toLinearSpaceToRef(e),e},i.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,e.ToLinearSpace),t.g=Math.pow(this.g,e.ToLinearSpace),t.b=Math.pow(this.b,e.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var e=new i;return this.toGammaSpaceToRef(e),e},i.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,e.ToGammaSpace),t.g=Math.pow(this.g,e.ToGammaSpace),t.b=Math.pow(this.b,e.ToGammaSpace),this},i.FromHexString=function(e){if("#"!==e.substring(0,1)||7!==e.length)return new i(0,0,0);var t=parseInt(e.substring(1,3),16),r=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return i.FromInts(t,r,n)},i.FromArray=function(e,t){return void 0===t&&(t=0),new i(e[t],e[t+1],e[t+2])},i.FromInts=function(e,t,r){return new i(e/255,t/255,r/255)},i.Lerp=function(e,t,r){var n=e.r+(t.r-e.r)*r,o=e.g+(t.g-e.g)*r,s=e.b+(t.b-e.b)*r;return new i(n,o,s)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i})();e.Color3=i;var r=(function(){function e(e,t,i,r){this.r=e,this.g=t,this.b=i,this.a=r}return e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this},e.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t,this.a*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t},e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},e.prototype.getClassName=function(){return"Color4"},e.prototype.getHashCode=function(){var e=this.r||0;return e=397*e^(this.g||0),e=397*e^(this.b||0),e=397*e^(this.a||0)},e.prototype.clone=function(){return new e(this.r,this.g,this.b,this.a)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},e.prototype.toHexString=function(){var e=255*this.r|0,i=255*this.g|0,r=255*this.b|0,n=255*this.a|0;return"#"+t.ToHex(e)+t.ToHex(i)+t.ToHex(r)+t.ToHex(n)},e.FromHexString=function(t){if("#"!==t.substring(0,1)||9!==t.length)return new e(0,0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16),o=parseInt(t.substring(7,9),16);return e.FromInts(i,r,n,o)},e.Lerp=function(t,i,r){var n=new e(0,0,0,0);return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromInts=function(t,i,r,n){return new e(t/255,i/255,r/255,n/255)},e.CheckColors4=function(e,t){if(e.length===3*t){for(var i=[],r=0;r<e.length;r+=3){var n=r/3*4;i[n]=e[r],i[n+1]=e[r+1],i[n+2]=e[r+2],i[n+3]=1}return i}return e},e})();e.Color4=r;var n=(function(){function i(e,t){this.x=e,this.y=t}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+"}"},i.prototype.getClassName=function(){return"Vector2"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0)},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,this},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this},i.prototype.copyFromFloats=function(e,t){return this.x=e,this.y=t,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,this},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this},i.prototype.addVector3=function(e){return new i(this.x+e.x,this.y+e.y)},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,this},i.prototype.multiplyByFloats=function(e,t){return new i(this.x*e,this.y*t)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,this},i.prototype.negate=function(){return new i((-this.x),(-this.y))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e)},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(e,t){return void 0===t&&(t=0),new i(e[t],e[t+1])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1]},i.CatmullRom=function(e,t,r,n,o){var s=o*o,a=o*s,h=.5*(2*t.x+(-e.x+r.x)*o+(2*e.x-5*t.x+4*r.x-n.x)*s+(-e.x+3*t.x-3*r.x+n.x)*a),c=.5*(2*t.y+(-e.y+r.y)*o+(2*e.y-5*t.y+4*r.y-n.y)*s+(-e.y+3*t.y-3*r.y+n.y)*a);return new i(h,c)},i.Clamp=function(e,t,r){var n=e.x;n=n>r.x?r.x:n,n=n<t.x?t.x:n;var o=e.y;return o=o>r.y?r.y:o,o=o<t.y?t.y:o,new i(n,o)},i.Hermite=function(e,t,r,n,o){var s=o*o,a=o*s,h=2*a-3*s+1,c=-2*a+3*s,l=a-2*s+o,u=a-s,d=e.x*h+r.x*c+t.x*l+n.x*u,f=e.y*h+r.y*c+t.y*l+n.y*u;return new i(d,f)},i.Lerp=function(e,t,r){var n=e.x+(t.x-e.x)*r,o=e.y+(t.y-e.y)*r;return new i(n,o)},i.Dot=function(e,t){return e.x*t.x+e.y*t.y},i.Normalize=function(e){var t=e.clone();return t.normalize(),t},i.Minimize=function(e,t){var r=e.x<t.x?e.x:t.x,n=e.y<t.y?e.y:t.y;return new i(r,n)},i.Maximize=function(e,t){var r=e.x>t.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new i(r,n)},i.Transform=function(e,t){var r=i.Zero();return i.TransformToRef(e,t,r),r},i.TransformToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+t.m[13];i.x=r,i.y=n},i.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,s=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*n*o},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i.DistanceOfPointFromSegment=function(e,t,r){var n=i.DistanceSquared(t,r);if(0===n)return i.Distance(e,t);var o=r.subtract(t),s=Math.max(0,Math.min(1,i.Dot(e.subtract(t),o)/n)),a=t.add(o.multiplyByFloats(s,s));return i.Distance(e,a)},i})();e.Vector2=n;var o=(function(){function i(e,t,i){this.x=e,this.y=t,this.z=i}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},i.prototype.getClassName=function(){return"Vector3"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},i.prototype.toQuaternion=function(){var e=new h(0,0,0,1),t=Math.cos(.5*(this.x+this.z)),i=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),o=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return e.x=r*s,e.y=-n*s,e.z=i*o,e.w=t*o,e},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y,this.z+e.z)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y,this.z-e.z)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,this},i.prototype.subtractFromFloats=function(e,t,r){return new i(this.x-e,this.y-t,this.z-r)},i.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-i,this},i.prototype.negate=function(){return new i((-this.x),(-this.y),(-this.z))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e,this.z*e)},i.prototype.scaleToRef=function(e,t){t.x=this.x*e,t.y=this.y*e,t.z=this.z*e},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)&&t.WithinEpsilon(this.z,i.z,r)},i.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y,this.z*e.z)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,this},i.prototype.multiplyByFloats=function(e,t,r){return new i(this.x*e,this.y*t,this.z*r)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y,this.z/e.z)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,this},i.prototype.MinimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this},i.prototype.MaximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var e=this.length();if(0===e||1===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},i.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},i.GetClipFactor=function(e,t,r,n){var o=i.Dot(e,r)-n,s=i.Dot(t,r)-n,a=o/(o-s);return a},i.FromArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2])},i.FromFloatArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},i.FromFloatArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},i.FromFloatsToRef=function(e,t,i,r){r.x=e,r.y=t,r.z=i},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.Forward=function(){return new i(0,0,1)},i.Right=function(){return new i(1,0,0)},i.Left=function(){return new i((-1),0,0)},i.TransformCoordinates=function(e,t){var r=i.Zero();return i.TransformCoordinatesToRef(e,t,r),r},i.TransformCoordinatesToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8]+t.m[12],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9]+t.m[13],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10]+t.m[14],s=e.x*t.m[3]+e.y*t.m[7]+e.z*t.m[11]+t.m[15];i.x=r/s,i.y=n/s,i.z=o/s},i.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=e*r.m[0]+t*r.m[4]+i*r.m[8]+r.m[12],s=e*r.m[1]+t*r.m[5]+i*r.m[9]+r.m[13],a=e*r.m[2]+t*r.m[6]+i*r.m[10]+r.m[14],h=e*r.m[3]+t*r.m[7]+i*r.m[11]+r.m[15];n.x=o/h,n.y=s/h,n.z=a/h},i.TransformNormal=function(e,t){var r=i.Zero();return i.TransformNormalToRef(e,t,r),r},i.TransformNormalToRef=function(e,t,i){var r=e.x*t.m[0]+e.y*t.m[4]+e.z*t.m[8],n=e.x*t.m[1]+e.y*t.m[5]+e.z*t.m[9],o=e.x*t.m[2]+e.y*t.m[6]+e.z*t.m[10];i.x=r,i.y=n,i.z=o},i.TransformNormalFromFloatsToRef=function(e,t,i,r,n){n.x=e*r.m[0]+t*r.m[4]+i*r.m[8],n.y=e*r.m[1]+t*r.m[5]+i*r.m[9],n.z=e*r.m[2]+t*r.m[6]+i*r.m[10]},i.CatmullRom=function(e,t,r,n,o){var s=o*o,a=o*s,h=.5*(2*t.x+(-e.x+r.x)*o+(2*e.x-5*t.x+4*r.x-n.x)*s+(-e.x+3*t.x-3*r.x+n.x)*a),c=.5*(2*t.y+(-e.y+r.y)*o+(2*e.y-5*t.y+4*r.y-n.y)*s+(-e.y+3*t.y-3*r.y+n.y)*a),l=.5*(2*t.z+(-e.z+r.z)*o+(2*e.z-5*t.z+4*r.z-n.z)*s+(-e.z+3*t.z-3*r.z+n.z)*a);return new i(h,c,l)},i.Clamp=function(e,t,r){var n=e.x;n=n>r.x?r.x:n,n=n<t.x?t.x:n;var o=e.y;o=o>r.y?r.y:o,o=o<t.y?t.y:o;var s=e.z;return s=s>r.z?r.z:s,s=s<t.z?t.z:s,new i(n,o,s)},i.Hermite=function(e,t,r,n,o){var s=o*o,a=o*s,h=2*a-3*s+1,c=-2*a+3*s,l=a-2*s+o,u=a-s,d=e.x*h+r.x*c+t.x*l+n.x*u,f=e.y*h+r.y*c+t.y*l+n.y*u,p=e.z*h+r.z*c+t.z*l+n.z*u;return new i(d,f,p)},i.Lerp=function(e,t,r){var n=e.x+(t.x-e.x)*r,o=e.y+(t.y-e.y)*r,s=e.z+(t.z-e.z)*r;return new i(n,o,s)},i.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z},i.Cross=function(e,t){var r=i.Zero();return i.CrossToRef(e,t,r),r},i.CrossToRef=function(e,t,i){P.Vector3[0].x=e.y*t.z-e.z*t.y,P.Vector3[0].y=e.z*t.x-e.x*t.z,P.Vector3[0].z=e.x*t.y-e.y*t.x,i.copyFrom(P.Vector3[0])},i.Normalize=function(e){var t=i.Zero();return i.NormalizeToRef(e,t),t},i.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},i.Project=function(e,t,r,n){var o=n.width,s=n.height,a=n.x,h=n.y,l=i._viewportMatrixCache?i._viewportMatrixCache:i._viewportMatrixCache=new c;c.FromValuesToRef(o/2,0,0,0,0,-s/2,0,0,0,0,1,0,a+o/2,s/2+h,0,1,l);var u=i._matrixCache?i._matrixCache:i._matrixCache=new c;return t.multiplyToRef(r,u),u.multiplyToRef(l,u),i.TransformCoordinates(e,u)},i.UnprojectFromTransform=function(e,r,n,o,s){var a=i._matrixCache?i._matrixCache:i._matrixCache=new c;o.multiplyToRef(s,a),a.invert(),e.x=e.x/r*2-1,e.y=-(e.y/n*2-1);var h=i.TransformCoordinates(e,a),l=e.x*a.m[3]+e.y*a.m[7]+e.z*a.m[11]+a.m[15];return t.WithinEpsilon(l,1)&&(h=h.scale(1/l)),h},i.Unproject=function(e,r,n,o,s,a){var h=i._matrixCache?i._matrixCache:i._matrixCache=new c;o.multiplyToRef(s,h),h.multiplyToRef(a,h),h.invert();var l=new i(e.x/r*2-1,(-(e.y/n*2-1)),e.z),u=i.TransformCoordinates(l,h),d=l.x*h.m[3]+l.y*h.m[7]+l.z*h.m[11]+h.m[15];return t.WithinEpsilon(d,1)&&(u=u.scale(1/d)),u},i.Minimize=function(e,t){var i=e.clone();return i.MinimizeInPlace(t),i},i.Maximize=function(e,t){var i=e.clone();return i.MaximizeInPlace(t),i},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z;return i*i+r*r+n*n},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i.RotationFromAxis=function(e,t,r){var n=i.Zero();return i.RotationFromAxisToRef(e,t,r,n),n},i.RotationFromAxisToRef=function(r,n,o,s){var a=r.normalize(),h=o.normalize(),c=f.X,l=f.Y,u=0,d=0,p=0,_=0,m=0,g=0,v=0,y=-1,x=0,b=P.Vector3[0],A=0,T=P.Vector3[1];t.WithinEpsilon(h.z,0,e.Epsilon)?g=1:t.WithinEpsilon(h.x,0,e.Epsilon)?_=1:(v=h.z/h.x,_=-v*Math.sqrt(1/(1+v*v)),g=Math.sqrt(1/(1+v*v))),T.x=_,T.y=m,T.z=g,T.normalize(),i.CrossToRef(a,T,b),b.normalize(),i.Dot(h,b)<0&&(y=1),A=i.Dot(a,T),A=Math.min(1,Math.max(-1,A)),p=Math.acos(A)*y,i.Dot(T,c)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),x++);var E=P.Vector3[2],S=P.Vector3[3];_=0,m=0,g=0,y=-1,t.WithinEpsilon(h.z,0,e.Epsilon)?_=1:(v=T.z/T.x,_=-v*Math.sqrt(1/(1+v*v)),g=Math.sqrt(1/(1+v*v))),E.x=_,E.y=m,E.z=g,E.normalize(),i.CrossToRef(E,T,S),S.normalize(),i.CrossToRef(h,E,b),b.normalize(),i.Dot(T,b)<0&&(y=1),A=i.Dot(h,E),A=Math.min(1,Math.max(-1,A)),d=Math.acos(A)*y,i.Dot(S,l)<0&&(d=Math.PI+d,x++),y=-1,i.CrossToRef(c,T,b),b.normalize(),i.Dot(b,l)<0&&(y=1),A=i.Dot(T,c),A=Math.min(1,Math.max(-1,A)),u=-Math.acos(A)*y,A<0&&x<2&&(u=Math.PI+u),s.x=d,s.y=u,s.z=p},i})();e.Vector3=o;var s=(function(){function i(e,t,i,r){this.x=e,this.y=t,this.z=i,this.w=r}return i.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},i.prototype.getClassName=function(){return"Vector4"},i.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},i.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},i.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this},i.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},i.prototype.add=function(e){return new i(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)},i.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,this},i.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},i.prototype.subtract=function(e){return new i(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)},i.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,this},i.prototype.subtractFromFloats=function(e,t,r,n){return new i(this.x-e,this.y-t,this.z-r,this.w-n)},i.prototype.subtractFromFloatsToRef=function(e,t,i,r,n){return n.x=this.x-e,n.y=this.y-t,n.z=this.z-i,n.w=this.w-r,this},i.prototype.negate=function(){return new i((-this.x),(-this.y),(-this.z),(-this.w))},i.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},i.prototype.scale=function(e){return new i(this.x*e,this.y*e,this.z*e,this.w*e)},i.prototype.scaleToRef=function(e,t){t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e},i.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},i.prototype.equalsWithEpsilon=function(i,r){return void 0===r&&(r=e.Epsilon),i&&t.WithinEpsilon(this.x,i.x,r)&&t.WithinEpsilon(this.y,i.y,r)&&t.WithinEpsilon(this.z,i.z,r)&&t.WithinEpsilon(this.w,i.w,r)},i.prototype.equalsToFloats=function(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r},i.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},i.prototype.multiply=function(e){return new i(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)},i.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,this},i.prototype.multiplyByFloats=function(e,t,r,n){return new i(this.x*e,this.y*t,this.z*r,this.w*n)},i.prototype.divide=function(e){return new i(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)},i.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,this},i.prototype.MinimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this},i.prototype.MaximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toVector3=function(){return new o(this.x,this.y,this.z)},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},i.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},i.FromArray=function(e,t){return t||(t=0),new i(e[t],e[t+1],e[t+2],e[t+3])},i.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},i.FromFloatArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},i.FromFloatsToRef=function(e,t,i,r,n){n.x=e,n.y=t,n.z=i,n.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(e){var t=i.Zero();return i.NormalizeToRef(e,t),t},i.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},i.Minimize=function(e,t){var i=e.clone();return i.MinimizeInPlace(t),i},i.Maximize=function(e,t){var i=e.clone();return i.MaximizeInPlace(t),i},i.Distance=function(e,t){return Math.sqrt(i.DistanceSquared(e,t))},i.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},i.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},i})();e.Vector4=s;var a=(function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){this.width=e,this.height=t},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){var i=new e(this.width+t.width,this.height+t.height);return i},e.prototype.substract=function(t){var i=new e(this.width-t.width,this.height-t.height);return i},e.Lerp=function(t,i,r){var n=t.width+(i.width-t.width)*r,o=t.height+(i.height-t.height)*r;return new e(n,o)},e})();e.Size=a;var h=(function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*e^(this.y||0),e=397*e^(this.z||0),e=397*e^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,r=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,n=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,r,n,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){var t=new e((-this.x),(-this.y),(-this.z),this.w);return t},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=1/this.length();return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=o.Zero();return this.toEulerAnglesToRef(t,e),t},e.prototype.toEulerAnglesToRef=function(e,t){void 0===t&&(t="YZX");var i=this.z,r=this.x,n=this.y,o=this.w,s=o*o,a=i*i,h=r*r,c=n*n,l=n*i-r*o,u=.4999999;return l<-u?(e.y=2*Math.atan2(n,o),e.x=Math.PI/2,e.z=0):l>u?(e.y=2*Math.atan2(n,o),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(r*n+i*o),-a-h+c+s),e.x=Math.asin(-2*(i*n-r*o)),e.y=Math.atan2(2*(i*r+n*o),a-h-c+s)),this},e.prototype.toRotationMatrix=function(e){var t=this.x*this.x,i=this.y*this.y,r=this.z*this.z,n=this.x*this.y,o=this.z*this.w,s=this.z*this.x,a=this.y*this.w,h=this.y*this.z,c=this.x*this.w;return e.m[0]=1-2*(i+r),e.m[1]=2*(n+o),e.m[2]=2*(s-a),e.m[3]=0,e.m[4]=2*(n-o),e.m[5]=1-2*(r+t),e.m[6]=2*(h+c),e.m[7]=0,e.m[8]=2*(s+a),e.m[9]=2*(h-c),e.m[10]=1-2*(i+t),e.m[11]=0,e.m[12]=0,e.m[13]=0,e.m[14]=0,e.m[15]=1,this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],s=r[8],a=r[1],h=r[5],c=r[9],l=r[2],u=r[6],d=r[10],f=n+h+d;f>0?(i=.5/Math.sqrt(f+1),t.w=.25/i,t.x=(u-c)*i,t.y=(s-l)*i,t.z=(a-o)*i):n>h&&n>d?(i=2*Math.sqrt(1+n-h-d),t.w=(u-c)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+l)/i):h>d?(i=2*Math.sqrt(1+h-n-d),t.w=(s-l)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(c+u)/i):(i=2*Math.sqrt(1+d-n-h),t.w=(a-o)/i,t.x=(s+l)/i,t.y=(c+u)/i,t.z=.25*i)},e.Inverse=function(t){return new e((-t.x),(-t.y),(-t.z),t.w)},e.Identity=function(){return new e(0,0,0,1)},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*r,i.y=e.y*r,i.z=e.z*r,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,s=.5*e,a=Math.sin(n),h=Math.cos(n),c=Math.sin(o),l=Math.cos(o),u=Math.sin(s),d=Math.cos(s);r.x=d*c*h+u*l*a,r.y=u*l*h-d*c*a,r.z=d*l*a-u*c*h,r.w=d*l*h+u*c*a},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),s=.5*t;r.x=Math.cos(o)*Math.sin(s),r.y=Math.sin(o)*Math.sin(s),r.z=Math.sin(n)*Math.cos(s),r.w=Math.cos(n)*Math.cos(s)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,s=i,a=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,h=!1;if(a<0&&(h=!0,a=-a),a>.999999)o=1-s,n=h?-s:s;else{var c=Math.acos(a),l=1/Math.sin(c);o=Math.sin((1-s)*c)*l,n=h?-Math.sin(s*c)*l:Math.sin(s*c)*l}r.x=o*e.x+n*t.x,r.y=o*e.y+n*t.y,r.z=o*e.z+n*t.z,r.w=o*e.w+n*t.w},e})();e.Quaternion=h;var c=(function(){function e(){this.m=new Float32Array(16)}return e.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},e.prototype.determinant=function(){var e=this.m[10]*this.m[15]-this.m[11]*this.m[14],t=this.m[9]*this.m[15]-this.m[11]*this.m[13],i=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=this.m[8]*this.m[14]-this.m[10]*this.m[12],o=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*e-this.m[6]*t+this.m[7]*i)-this.m[1]*(this.m[4]*e-this.m[6]*r+this.m[7]*n)+this.m[2]*(this.m[4]*t-this.m[5]*r+this.m[7]*o)-this.m[3]*(this.m[4]*i-this.m[5]*n+this.m[6]*o)},e.prototype.toArray=function(){return this.m},e.prototype.asArray=function(){return this.toArray()},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){for(var e=0;e<16;e++)this.m[e]=0;return this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=0;i<16;i++)t.m[i]=this.m[i]+e.m[i];return this},e.prototype.addToSelf=function(e){for(var t=0;t<16;t++)this.m[t]+=e.m[t];return this},e.prototype.invertToRef=function(e){var t=this.m[0],i=this.m[1],r=this.m[2],n=this.m[3],o=this.m[4],s=this.m[5],a=this.m[6],h=this.m[7],c=this.m[8],l=this.m[9],u=this.m[10],d=this.m[11],f=this.m[12],p=this.m[13],_=this.m[14],m=this.m[15],g=u*m-d*_,v=l*m-d*p,y=l*_-u*p,x=c*m-d*f,b=c*_-u*f,A=c*p-l*f,T=s*g-a*v+h*y,E=-(o*g-a*x+h*b),P=o*v-s*x+h*A,S=-(o*y-s*b+a*A),M=1/(t*T+i*E+r*P+n*S),C=a*m-h*_,R=s*m-h*p,O=s*_-a*p,D=o*m-h*f,I=o*_-a*f,L=o*p-s*f,w=a*d-h*u,B=s*d-h*l,F=s*u-a*l,V=o*d-h*c,N=o*u-a*c,U=o*l-s*c;return e.m[0]=T*M,e.m[4]=E*M,e.m[8]=P*M,e.m[12]=S*M,e.m[1]=-(i*g-r*v+n*y)*M,e.m[5]=(t*g-r*x+n*b)*M,e.m[9]=-(t*v-i*x+n*A)*M,e.m[13]=(t*y-i*b+r*A)*M,e.m[2]=(i*C-r*R+n*O)*M,
e.m[6]=-(t*C-r*D+n*I)*M,e.m[10]=(t*R-i*D+n*L)*M,e.m[14]=-(t*O-i*I+r*L)*M,e.m[3]=-(i*w-r*B+n*F)*M,e.m[7]=(t*w-r*V+n*N)*M,e.m[11]=-(t*B-i*V+n*U)*M,e.m[15]=(t*F-i*N+r*U)*M,this},e.prototype.setTranslation=function(e){return this.m[12]=e.x,this.m[13]=e.y,this.m[14]=e.z,this},e.prototype.getTranslation=function(){return new o(this.m[12],this.m[13],this.m[14])},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){for(var t=0;t<16;t++)this.m[t]=e.m[t];return this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this.m[i];return this},e.prototype.multiplyToRef=function(e,t){return this.multiplyToArray(e,t.m,0),this},e.prototype.multiplyToArray=function(e,t,i){var r=this.m[0],n=this.m[1],o=this.m[2],s=this.m[3],a=this.m[4],h=this.m[5],c=this.m[6],l=this.m[7],u=this.m[8],d=this.m[9],f=this.m[10],p=this.m[11],_=this.m[12],m=this.m[13],g=this.m[14],v=this.m[15],y=e.m[0],x=e.m[1],b=e.m[2],A=e.m[3],T=e.m[4],E=e.m[5],P=e.m[6],S=e.m[7],M=e.m[8],C=e.m[9],R=e.m[10],O=e.m[11],D=e.m[12],I=e.m[13],L=e.m[14],w=e.m[15];return t[i]=r*y+n*T+o*M+s*D,t[i+1]=r*x+n*E+o*C+s*I,t[i+2]=r*b+n*P+o*R+s*L,t[i+3]=r*A+n*S+o*O+s*w,t[i+4]=a*y+h*T+c*M+l*D,t[i+5]=a*x+h*E+c*C+l*I,t[i+6]=a*b+h*P+c*R+l*L,t[i+7]=a*A+h*S+c*O+l*w,t[i+8]=u*y+d*T+f*M+p*D,t[i+9]=u*x+d*E+f*C+p*I,t[i+10]=u*b+d*P+f*R+p*L,t[i+11]=u*A+d*S+f*O+p*w,t[i+12]=_*y+m*T+g*M+v*D,t[i+13]=_*x+m*E+g*C+v*I,t[i+14]=_*b+m*P+g*R+v*L,t[i+15]=_*A+m*S+g*O+v*w,this},e.prototype.equals=function(e){return e&&this.m[0]===e.m[0]&&this.m[1]===e.m[1]&&this.m[2]===e.m[2]&&this.m[3]===e.m[3]&&this.m[4]===e.m[4]&&this.m[5]===e.m[5]&&this.m[6]===e.m[6]&&this.m[7]===e.m[7]&&this.m[8]===e.m[8]&&this.m[9]===e.m[9]&&this.m[10]===e.m[10]&&this.m[11]===e.m[11]&&this.m[12]===e.m[12]&&this.m[13]===e.m[13]&&this.m[14]===e.m[14]&&this.m[15]===e.m[15]},e.prototype.clone=function(){return e.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this.m[0]||0,t=1;t<16;t++)e=397*e^(this.m[t]||0);return e},e.prototype.decompose=function(i,r,n){n.x=this.m[12],n.y=this.m[13],n.z=this.m[14];var o=t.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=t.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return i.x=o*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),i.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),i.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===i.x||0===i.y||0===i.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(e.FromValuesToRef(this.m[0]/i.x,this.m[1]/i.x,this.m[2]/i.x,0,this.m[4]/i.y,this.m[5]/i.y,this.m[6]/i.y,0,this.m[8]/i.z,this.m[9]/i.z,this.m[10]/i.z,0,0,0,0,1,P.Matrix[0]),h.FromRotationMatrixToRef(P.Matrix[0],r),!0)},e.prototype.getRotationMatrix=function(){var t=e.Identity();return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=this.m,r=i[0]*i[1]*i[2]*i[3]<0?-1:1,n=i[4]*i[5]*i[6]*i[7]<0?-1:1,o=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=r*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),a=n*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),h=o*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);e.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/a,i[5]/a,i[6]/a,0,i[8]/h,i[9]/h,i[10]/h,0,0,0,0,1,t)},e.FromArray=function(t,i){var r=new e;return i||(i=0),e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i.m[r]=e[r+t]},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r.m[n]=e[n+t]*i},e.FromValuesToRef=function(e,t,i,r,n,o,s,a,h,c,l,u,d,f,p,_,m){m.m[0]=e,m.m[1]=t,m.m[2]=i,m.m[3]=r,m.m[4]=n,m.m[5]=o,m.m[6]=s,m.m[7]=a,m.m[8]=h,m.m[9]=c,m.m[10]=l,m.m[11]=u,m.m[12]=d,m.m[13]=f,m.m[14]=p,m.m[15]=_},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new s(this.m[t+0],this.m[t+1],this.m[t+2],this.m[t+3])},e.prototype.setRow=function(e,t){if(e<0||e>3)return this;var i=4*e;return this.m[i+0]=t.x,this.m[i+1]=t.y,this.m[i+2]=t.z,this.m[i+3]=t.w,this},e.FromValues=function(t,i,r,n,o,s,a,h,c,l,u,d,f,p,_,m){var g=new e;return g.m[0]=t,g.m[1]=i,g.m[2]=r,g.m[3]=n,g.m[4]=o,g.m[5]=s,g.m[6]=a,g.m[7]=h,g.m[8]=c,g.m[9]=l,g.m[10]=u,g.m[11]=d,g.m[12]=f,g.m[13]=p,g.m[14]=_,g.m[15]=m,g},e.Compose=function(t,i,r){var n=e.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),o=e.Identity();return i.toRotationMatrix(o),n=n.multiply(o),n.setTranslation(r),n},e.Identity=function(){return e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},e.Zero=function(){return e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[0]=1,t.m[15]=1,t.m[5]=r,t.m[10]=r,t.m[9]=-i,t.m[6]=i,t.m[1]=0,t.m[2]=0,t.m[3]=0,t.m[4]=0,t.m[7]=0,t.m[8]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[5]=1,t.m[15]=1,t.m[0]=r,t.m[2]=-i,t.m[8]=i,t.m[10]=r,t.m[1]=0,t.m[3]=0,t.m[4]=0,t.m[6]=0,t.m[7]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(e,t){var i=Math.sin(e),r=Math.cos(e);t.m[10]=1,t.m[15]=1,t.m[0]=r,t.m[1]=i,t.m[4]=-i,t.m[5]=r,t.m[2]=0,t.m[3]=0,t.m[6]=0,t.m[7]=0,t.m[8]=0,t.m[9]=0,t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0},e.RotationAxis=function(t,i){var r=e.Zero();return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize(),i.m[0]=e.x*e.x*o+n,i.m[1]=e.x*e.y*o-e.z*r,i.m[2]=e.x*e.z*o+e.y*r,i.m[3]=0,i.m[4]=e.y*e.x*o+e.z*r,i.m[5]=e.y*e.y*o+n,i.m[6]=e.y*e.z*o-e.x*r,i.m[7]=0,i.m[8]=e.z*e.x*o-e.y*r,i.m[9]=e.z*e.y*o+e.x*r,i.m[10]=e.z*e.z*o+n,i.m[11]=0,i.m[15]=1},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){h.RotationYawPitchRollToRef(e,t,i,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},e.Scaling=function(t,i,r){var n=e.Zero();return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(e,t,i,r){r.m[0]=e,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=t,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=i,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},e.Translation=function(t,i,r){var n=e.Identity();return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n)},e.Lerp=function(t,i,r){for(var n=e.Zero(),o=0;o<16;o++)n.m[o]=t.m[o]*(1-r)+i.m[o]*r;return n},e.DecomposeLerp=function(t,i,r){var n=new o(0,0,0),s=new h,a=new o(0,0,0);t.decompose(n,s,a);var c=new o(0,0,0),l=new h,u=new o(0,0,0);i.decompose(c,l,u);var d=o.Lerp(n,c,r),f=h.Slerp(s,l,r),p=o.Lerp(a,u,r);return e.Compose(d,f,p)},e.LookAtLH=function(t,i,r){var n=e.Zero();return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,n){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-o.Dot(this._xAxis,t),a=-o.Dot(this._yAxis,t),h=-o.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,h,1,n)},e.LookAtRH=function(t,i,r){var n=e.Zero();return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,n){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-o.Dot(this._xAxis,t),a=-o.Dot(this._yAxis,t),h=-o.Dot(this._zAxis,t);return e.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,a,h,1,n)},e.OrthoLH=function(t,i,r,n){var o=e.Zero();return e.OrthoLHToRef(t,i,r,n,o),o},e.OrthoLHToRef=function(t,i,r,n,o){var s=2/t,a=2/i,h=1/(n-r),c=r/(r-n);e.FromValuesToRef(s,0,0,0,0,a,0,0,0,0,h,0,0,0,c,1,o)},e.OrthoOffCenterLH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterLHToRef=function(e,t,i,r,n,o,s){s.m[0]=2/(t-e),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-i),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(o-n),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(e+t)/(e-t),s.m[13]=(r+i)/(i-r),s.m[14]=-n/(o-n),s.m[15]=1},e.OrthoOffCenterRH=function(t,i,r,n,o,s){var a=e.Zero();return e.OrthoOffCenterRHToRef(t,i,r,n,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,s,a){e.OrthoOffCenterLHToRef(t,i,r,n,o,s,a),a.m[10]*=-1},e.PerspectiveLH=function(t,i,r,n){var o=e.Zero();return o.m[0]=2*r/t,o.m[1]=o.m[2]=o.m[3]=0,o.m[5]=2*r/i,o.m[4]=o.m[6]=o.m[7]=0,o.m[10]=-n/(r-n),o.m[8]=o.m[9]=0,o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n),o},e.PerspectiveFovLH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovLHToRef(t,i,r,n,o),o},e.PerspectiveFovLHToRef=function(e,t,i,r,n,o){void 0===o&&(o=!0);var s=1/Math.tan(.5*e);o?n.m[0]=s/t:n.m[0]=s,n.m[1]=n.m[2]=n.m[3]=0,o?n.m[5]=s:n.m[5]=s*t,n.m[4]=n.m[6]=n.m[7]=0,n.m[8]=n.m[9]=0,n.m[10]=r/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(i*r)/(r-i)},e.PerspectiveFovRH=function(t,i,r,n){var o=e.Zero();return e.PerspectiveFovRHToRef(t,i,r,n,o),o},e.PerspectiveFovRHToRef=function(e,t,i,r,n,o){void 0===o&&(o=!0);var s=1/Math.tan(.5*e);o?n.m[0]=s/t:n.m[0]=s,n.m[1]=n.m[2]=n.m[3]=0,o?n.m[5]=s:n.m[5]=s*t,n.m[4]=n.m[6]=n.m[7]=0,n.m[8]=n.m[9]=0,n.m[10]=r/(i-r),n.m[11]=-1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},e.PerspectiveFovWebVRToRef=function(e,t,i,r,n){void 0===n&&(n=!0);var o=Math.tan(e.upDegrees*Math.PI/180),s=Math.tan(e.downDegrees*Math.PI/180),a=Math.tan(e.leftDegrees*Math.PI/180),h=Math.tan(e.rightDegrees*Math.PI/180),c=2/(a+h),l=2/(o+s);r.m[0]=c,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=l,r.m[6]=r.m[7]=0,r.m[8]=(a-h)*c*.5,r.m[9]=-((o-s)*l*.5),r.m[10]=-i/(t-i),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=t*i/(t-i)},e.GetFinalMatrix=function(t,i,r,n,o,s){var a=t.width,h=t.height,c=t.x,l=t.y,u=e.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,s-o,0,c+a/2,h/2+l,o,1);return i.multiply(r).multiply(n).multiply(u)},e.GetAsMatrix2x2=function(e){return new Float32Array([e.m[0],e.m[1],e.m[4],e.m[5]])},e.GetAsMatrix3x3=function(e){return new Float32Array([e.m[0],e.m[1],e.m[2],e.m[4],e.m[5],e.m[6],e.m[8],e.m[9],e.m[10]])},e.Transpose=function(t){var i=new e;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(e,t){e.normalize();var i=e.normal.x,r=e.normal.y,n=e.normal.z,o=-2*i,s=-2*r,a=-2*n;t.m[0]=o*i+1,t.m[1]=s*i,t.m[2]=a*i,t.m[3]=0,t.m[4]=o*r,t.m[5]=s*r+1,t.m[6]=a*r,t.m[7]=0,t.m[8]=o*n,t.m[9]=s*n,t.m[10]=a*n+1,t.m[11]=0,t.m[12]=o*e.d,t.m[13]=s*e.d,t.m[14]=a*e.d,t.m[15]=1},e.FromXYZAxesToRef=function(e,t,i,r){r.m[0]=e.x,r.m[1]=e.y,r.m[2]=e.z,r.m[3]=0,r.m[4]=t.x,r.m[5]=t.y,r.m[6]=t.z,r.m[7]=0,r.m[8]=i.x,r.m[9]=i.y,r.m[10]=i.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,r=e.y*e.y,n=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,h=e.y*e.w,c=e.y*e.z,l=e.x*e.w;t.m[0]=1-2*(r+n),t.m[1]=2*(o+s),t.m[2]=2*(a-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(n+i),t.m[6]=2*(c+l),t.m[7]=0,t.m[8]=2*(a+h),t.m[9]=2*(c-l),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1},e._tempQuaternion=new h,e._xAxis=o.Zero(),e._yAxis=o.Zero(),e._zAxis=o.Zero(),e})();e.Matrix=c;var l=(function(){function e(e,t,i,r){this.normal=new o(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=c.Transpose(t),r=this.normal.x,n=this.normal.y,o=this.normal.z,s=this.d,a=r*i.m[0]+n*i.m[1]+o*i.m[2]+s*i.m[3],h=r*i.m[4]+n*i.m[5]+o*i.m[6]+s*i.m[7],l=r*i.m[8]+n*i.m[9]+o*i.m[10]+s*i.m[11],u=r*i.m[12]+n*i.m[13]+o*i.m[14]+s*i.m[15];return new e(a,h,l,u)},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,h=i.y-e.y,c=i.z-e.z,l=o*c-s*h,u=s*a-n*c,d=n*h-o*a,f=Math.sqrt(l*l+u*u+d*d);return r=0!==f?1/f:0,this.normal.x=l*r,this.normal.y=u*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){var i=o.Dot(this.normal,e);return i<=t},e.prototype.signedDistanceTo=function(e){return o.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return i.normalize(),r.normal=i,r.d=-(i.x*t.x+i.y*t.y+i.z*t.z),r},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return o.Dot(i,t)+r},e})();e.Plane=l;var u=(function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){return new e(this.x*t,this.y*i,this.width*t,this.height*i)},e})();e.Viewport=u;var d=(function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new l(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetPlanesToRef=function(e,t){t[0].normal.x=e.m[3]+e.m[2],t[0].normal.y=e.m[7]+e.m[6],t[0].normal.z=e.m[11]+e.m[10],t[0].d=e.m[15]+e.m[14],t[0].normalize(),t[1].normal.x=e.m[3]-e.m[2],t[1].normal.y=e.m[7]-e.m[6],t[1].normal.z=e.m[11]-e.m[10],t[1].d=e.m[15]-e.m[14],t[1].normalize(),t[2].normal.x=e.m[3]+e.m[0],t[2].normal.y=e.m[7]+e.m[4],t[2].normal.z=e.m[11]+e.m[8],t[2].d=e.m[15]+e.m[12],t[2].normalize(),t[3].normal.x=e.m[3]-e.m[0],t[3].normal.y=e.m[7]-e.m[4],t[3].normal.z=e.m[11]-e.m[8],t[3].d=e.m[15]-e.m[12],t[3].normalize(),t[4].normal.x=e.m[3]-e.m[1],t[4].normal.y=e.m[7]-e.m[5],t[4].normal.z=e.m[11]-e.m[9],t[4].d=e.m[15]-e.m[13],t[4].normalize(),t[5].normal.x=e.m[3]+e.m[1],t[5].normal.y=e.m[7]+e.m[5],t[5].normal.z=e.m[11]+e.m[9],t[5].d=e.m[15]+e.m[13],t[5].normalize()},e})();e.Frustum=d,(function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD"})(e.Space||(e.Space={}));var f=(e.Space,(function(){function e(){}return e.X=new o(1,0,0),e.Y=new o(0,1,0),e.Z=new o(0,0,1),e})());e.Axis=f;var p=(function(){function e(){}return e.interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,s=3*r-6*t,a=3*t,h=e,c=0;c<5;c++){var l=h*h,u=l*h,d=o*u+s*l+a*h,f=1/(3*o*l+2*s*h+a);h-=(d-e)*f,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*i+3*(1-h)*Math.pow(h,2)*n+Math.pow(h,3)},e})();e.BezierCurve=p,(function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"})(e.Orientation||(e.Orientation={}));var _=e.Orientation,m=(function(){function e(e){var t=this;this.degrees=function(){return 180*t._radians/Math.PI},this.radians=function(){return t._radians},this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.BetweenTwoPoints=function(t,i){var r=i.subtract(t),n=Math.atan2(r.y,r.x);return new e(n)},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e})();e.Angle=m;var g=(function(){function e(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var r=Math.pow(t.x,2)+Math.pow(t.y,2),o=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,s=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new n((o*(t.y-i.y)-s*(e.y-t.y))/a,((e.x-t.x)*s-(t.x-i.x)*o)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=m.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),c=m.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=m.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-h>180&&(c-=360),c-h<-180&&(c+=360),l-c>180&&(l-=360),l-c<-180&&(l+=360),this.orientation=c-h<0?_.CW:_.CCW,this.angle=m.FromDegrees(this.orientation===_.CW?h-l:l-h)}return e})();e.Arc2=g;var v=(function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(e,t))}return e.prototype.addLineTo=function(e,t){if(closed)return this;var i=new n(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this},e.prototype.addArcTo=function(e,t,i,r,o){if(void 0===o&&(o=36),closed)return this;var s=this._points[this._points.length-1],a=new n(e,t),h=new n(i,r),c=new g(s,a,h),l=c.angle.radians()/o;c.orientation===_.CW&&(l*=-1);for(var u=c.startAngle.radians()+l,d=0;d<o;d++){var f=Math.cos(u)*c.radius+c.centerPoint.x,p=Math.sin(u)*c.radius+c.centerPoint.y;this.addLineTo(f,p),u+=l}return this},e.prototype.close=function(){return this.closed=!0,this},e.prototype.length=function(){var e=this._length;if(!this.closed){var t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e},e.prototype.getPoints=function(){return this._points},e.prototype.getPointAtLengthPosition=function(e){if(e<0||e>1)return n.Zero();for(var t=e*this.length(),i=0,r=0;r<this._points.length;r++){var o=(r+1)%this._points.length,s=this._points[r],a=this._points[o],h=a.subtract(s),c=h.length()+i;if(t>=i&&t<=c){var l=h.normalize(),u=t-i;return new n(s.x+l.x*u,s.y+l.y*u)}i=c}return n.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e})();e.Path2=v;var y=(function(){function i(e,t,i){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<e.length;r++)this._curve[r]=e[r].clone();this._raw=i||!1,this._compute(t)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(e,t){for(var i=0;i<e.length;i++)this._curve[i].x=e[i].x,this._curve[i].y=e[i].y,this._curve[i].z=e[i].z;return this._compute(t),this},i.prototype._compute=function(e){var t=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[t-1]=this._curve[t-1].subtract(this._curve[t-2]),this._raw||this._tangents[t-1].normalize();var i=this._tangents[0],r=this._normalVector(this._curve[0],i,e);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(i,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var n,s,a,h,c=1;c<t;c++)n=this._getLastNonNullVector(c),c<t-1&&(s=this._getFirstNonNullVector(c),this._tangents[c]=n.add(s),this._tangents[c].normalize()),this._distances[c]=this._distances[c-1]+n.length(),a=this._tangents[c],h=this._binormals[c-1],this._normals[c]=o.Cross(h,a),this._raw||this._normals[c].normalize(),this._binormals[c]=o.Cross(a,this._normals[c]),this._raw||this._binormals[c].normalize()},i.prototype._getFirstNonNullVector=function(e){for(var t=1,i=this._curve[e+t].subtract(this._curve[e]);0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i},i.prototype._getLastNonNullVector=function(e){for(var t=1,i=this._curve[e].subtract(this._curve[e-t]);0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},i.prototype._normalVector=function(i,r,n){var s,a=r.length();if(0===a&&(a=1),void 0===n||null===n){var h;t.WithinEpsilon(Math.abs(r.y)/a,1,e.Epsilon)?t.WithinEpsilon(Math.abs(r.x)/a,1,e.Epsilon)?t.WithinEpsilon(Math.abs(r.z)/a,1,e.Epsilon)||(h=new o(0,0,1)):h=new o(1,0,0):h=new o(0,(-1),0),s=o.Cross(r,h)}else s=o.Cross(r,n),o.CrossToRef(s,r,s);return s.normalize(),s},i})();e.Path3D=y;var x=(function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,n){n=n>2?n:3;for(var s=new Array,a=function(e,t,i,r){var n=(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;return n},h=0;h<=n;h++)s.push(new o(a(h/n,t.x,i.x,r.x),a(h/n,t.y,i.y,r.y),a(h/n,t.z,i.z,r.z)));return new e(s)},e.CreateCubicBezier=function(t,i,r,n,s){s=s>3?s:4;for(var a=new Array,h=function(e,t,i,r,n){var o=(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n;return o},c=0;c<=s;c++)a.push(new o(h(c/s,t.x,i.x,r.x,n.x),h(c/s,t.y,i.y,r.y,n.y),h(c/s,t.z,i.z,r.z,n.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,n,s){for(var a=new Array,h=1/s,c=0;c<=s;c++)a.push(o.Hermite(t,i,r,n,c*h));return new e(a)},e.prototype.getPoints=function(){return this._points},e.prototype.length=function(){return this._length},e.prototype["continue"]=function(t){for(var i=this._points[this._points.length-1],r=this._points.slice(),n=t.getPoints(),o=1;o<n.length;o++)r.push(n[o].subtract(n[0]).add(i));var s=new e(r);return s},e.prototype._computeLength=function(e){for(var t=0,i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t},e})();e.Curve3=x;var b=(function(){function e(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return e.prototype.addLight=function(e,t,i){var r=new o(t.r,t.g,t.b),n=r.scale(i);this.L00=this.L00.add(n.scale(.282095)),this.L1_1=this.L1_1.add(n.scale(.488603*e.y)),this.L10=this.L10.add(n.scale(.488603*e.z)),this.L11=this.L11.add(n.scale(.488603*e.x)),this.L2_2=this.L2_2.add(n.scale(1.092548*e.x*e.y)),this.L2_1=this.L2_1.add(n.scale(1.092548*e.y*e.z)),this.L21=this.L21.add(n.scale(1.092548*e.x*e.z)),this.L20=this.L20.add(n.scale(.315392*(3*e.z*e.z-1))),this.L22=this.L22.add(n.scale(.546274*(e.x*e.x-e.y*e.y)))},e.prototype.scale=function(e){this.L00=this.L00.scale(e),this.L1_1=this.L1_1.scale(e),this.L10=this.L10.scale(e),this.L11=this.L11.scale(e),this.L2_2=this.L2_2.scale(e),this.L2_1=this.L2_1.scale(e),this.L20=this.L20.scale(e),this.L21=this.L21.scale(e),this.L22=this.L22.scale(e)},e})();e.SphericalHarmonics=b;var A=(function(){function e(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return e.prototype.addAmbient=function(e){var t=new o(e.r,e.g,e.b);this.xx=this.xx.add(t),this.yy=this.yy.add(t),this.zz=this.zz.add(t)},e.getSphericalPolynomialFromHarmonics=function(t){var i=new e;return i.x=t.L11.scale(1.02333),i.y=t.L1_1.scale(1.02333),i.z=t.L10.scale(1.02333),i.xx=t.L00.scale(.886277).subtract(t.L20.scale(.247708)).add(t.L22.scale(.429043)),i.yy=t.L00.scale(.886277).subtract(t.L20.scale(.247708)).subtract(t.L22.scale(.429043)),i.zz=t.L00.scale(.886277).add(t.L20.scale(.495417)),i.yz=t.L2_1.scale(.858086),i.zx=t.L21.scale(.858086),i.xy=t.L2_2.scale(.858086),i},e})();e.SphericalPolynomial=A;var T=(function(){function e(e,t){void 0===e&&(e=o.Zero()),void 0===t&&(t=o.Up()),this.position=e,this.normal=t}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone())},e})();e.PositionNormalVertex=T;var E=(function(){function e(e,t,i){void 0===e&&(e=o.Zero()),void 0===t&&(t=o.Up()),void 0===i&&(i=n.Zero()),this.position=e,this.normal=t,this.uv=i}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone(),this.uv.clone())},e})();e.PositionNormalTextureVertex=E;var P=(function(){function e(){}return e.Color3=[i.Black(),i.Black(),i.Black()],e.Vector2=[n.Zero(),n.Zero(),n.Zero()],e.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],e.Vector4=[s.Zero(),s.Zero(),s.Zero()],e.Quaternion=[new h(0,0,0,0)],e.Matrix=[c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero(),c.Zero()],e})();e.Tmp=P})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){function t(e,t){return function(i,r){i.__serializableMembers||(i.__serializableMembers={}),i.__serializableMembers[r]||(i.__serializableMembers[r]={type:e,sourceName:t})}}function i(e){return t(0,e)}function r(e){return t(1,e)}function n(e){return t(2,e)}function o(e){return t(3,e)}function s(e){return t(4,e)}function a(e){return t(5,e)}function h(e){return t(6,e)}function c(e){return t(7,e)}e.serialize=i,e.serializeAsTexture=r,e.serializeAsColor3=n,e.serializeAsFresnelParameters=o,e.serializeAsVector2=s,e.serializeAsVector3=a,e.serializeAsMeshReference=h,e.serializeAsColorCurves=c;var l=(function(){function t(){}return t.Serialize=function(t,i){i||(i={}),i.tags=e.Tags.GetTags(t);for(var r in t.__serializableMembers){var n=t.__serializableMembers[r],o=n.sourceName||r,s=n.type,a=t[r];if(void 0!==a&&null!==a)switch(s){case 0:i[o]=a;break;case 1:i[o]=a.serialize();break;case 2:i[o]=a.asArray();break;case 3:i[o]=a.serialize();break;case 4:i[o]=a.asArray();break;case 5:i[o]=a.asArray();break;case 6:i[o]=a.id;break;case 7:i[o]=a.serialize()}}return i},t.Parse=function(t,i,r,n){var o=t();e.Tags.AddTagsTo(o,i.tags);for(var s in o.__serializableMembers){var a=o.__serializableMembers[s],h=i[a.sourceName||s],c=a.type;if(void 0!==h&&null!==h)switch(c){case 0:o[s]=h;break;case 1:o[s]=e.Texture.Parse(h,r,n);break;case 2:o[s]=e.Color3.FromArray(h);break;case 3:o[s]=e.FresnelParameters.Parse(h);break;case 4:o[s]=e.Vector2.FromArray(h);break;case 5:o[s]=e.Vector3.FromArray(h);break;case 6:o[s]=r.getLastMeshByID(h);break;case 7:o[s]=e.ColorCurves.Parse(h)}}return o},t.Clone=function(t,i){var r=t();e.Tags.AddTagsTo(r,i.tags);for(var n in r.__serializableMembers){var o=r.__serializableMembers[n],s=i[n],a=o.type;if(void 0!==s&&null!==s)switch(a){case 0:case 6:r[n]=s;break;case 1:case 2:case 3:case 4:case 5:case 7:r[n]=s.clone()}}return r},t})();e.SerializationHelper=l})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t){void 0===t&&(t=!1),this.initalize(e,t)}return e.prototype.initalize=function(e,t){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this},e})();e.EventState=t;var i=(function(){function e(e,t){this.callback=e,this.mask=t}return e})();e.Observer=i;var r=(function(){function e(){this._observers=new Array,this._eventState=new t(0)}return e.prototype.add=function(e,t,r){if(void 0===t&&(t=-1),void 0===r&&(r=!1),!e)return null;var n=new i(e,t);return r?this._observers.unshift(n):this._observers.push(n),n},e.prototype.remove=function(e){var t=this._observers.indexOf(e);return t!==-1&&(this._observers.splice(t,1),!0)},e.prototype.removeCallback=function(e){for(var t=0;t<this._observers.length;t++)if(this._observers[t].callback===e)return this._observers.splice(t,1),!0;return!1},e.prototype.notifyObservers=function(e,t){void 0===t&&(t=-1);var i=this._eventState;i.mask=t,i.skipNextObservers=!1;for(var r=0,n=this._observers;r<n.length;r++){var o=n[r];if(o.mask&t&&o.callback(e,i),i.skipNextObservers)return!1}return!0},e.prototype.hasObservers=function(){return this._observers.length>0},e.prototype.clear=function(){this._observers=new Array},e.prototype.clone=function(){var t=new e;return t._observers=this._observers.slice(0),t},e})();e.Observable=r})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,i){this.idbFactory=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,this.callbackManifestChecked=i,this.currentSceneUrl=t.ReturnFullUrlLocation(e),this.db=null,this.enableSceneOffline=!1,this.enableTexturesOffline=!1,this.manifestVersionFound=0,this.mustUpdateRessources=!1,this.hasReachedQuota=!1,t.IDBStorageEnabled?this.checkManifestFile():this.callbackManifestChecked(!0)}return t.prototype.checkManifestFile=function(){function t(){r.enableSceneOffline=!1,r.enableTexturesOffline=!1,r.callbackManifestChecked(!1)}var i=this,r=this,n=!1,o=this.currentSceneUrl+".manifest",s=new XMLHttpRequest;navigator.onLine&&(n=!0,o=o+(null==o.match(/\?/)?"?":"&")+(new Date).getTime()),s.open("GET",o,!0),s.addEventListener("load",(function(){if(200===s.status||e.Tools.ValidateXHRData(s,1))try{var r=JSON.parse(s.response);i.enableSceneOffline=r.enableSceneOffline,i.enableTexturesOffline=r.enableTexturesOffline,r.version&&!isNaN(parseInt(r.version))&&(i.manifestVersionFound=r.version),i.callbackManifestChecked&&i.callbackManifestChecked(!0)}catch(n){t()}else t()}),!1),s.addEventListener("error",(function(e){if(n){n=!1;var r=i.currentSceneUrl+".manifest";s.open("GET",r,!0),s.send()}else t()}),!1);try{s.send()}catch(a){e.Tools.Error("Error on XHR send request."),r.callbackManifestChecked(!1)}},t.prototype.openAsync=function(t,i){function r(){o.isSupported=!1,i&&i()}var n=this,o=this;if(this.idbFactory&&(this.enableSceneOffline||this.enableTexturesOffline))if(this.db)t&&t();else{this.hasReachedQuota=!1,this.isSupported=!0;var s=this.idbFactory.open("babylonjs",1);s.onerror=function(e){r()},s.onblocked=function(t){e.Tools.Error("IDB request blocked. Please reload the page."),r()},s.onsuccess=function(e){n.db=s.result,t()},s.onupgradeneeded=function(t){n.db=t.target.result;try{n.db.createObjectStore("scenes",{keyPath:"sceneUrl"}),n.db.createObjectStore("versions",{keyPath:"sceneUrl"}),n.db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(i){e.Tools.Error("Error while creating object stores. Exception: "+i.message),r()}}}else this.isSupported=!1,i&&i()},t.prototype.loadImageFromDB=function(e,i){var r=this,n=t.ReturnFullUrlLocation(e),o=function(){r.hasReachedQuota||null===r.db?i.src=e:r._saveImageIntoDBAsync(n,i)};this.mustUpdateRessources?o():this._loadImageFromDBAsync(n,i,o)},t.prototype._loadImageFromDBAsync=function(t,i,r){if(this.isSupported&&null!==this.db){var n,o=this.db.transaction(["textures"]);o.onabort=function(e){i.src=t},o.oncomplete=function(o){var s;if(n){var a=window.URL||window.webkitURL;s=a.createObjectURL(n.data,{oneTimeOnly:!0}),i.onerror=function(){e.Tools.Error("Error loading image from blob URL: "+s+" switching back to web url: "+t),i.src=t},i.src=s}else r()};var s=o.objectStore("textures").get(t);s.onsuccess=function(e){n=e.target.result},s.onerror=function(r){e.Tools.Error("Error loading texture "+t+" from DB."),i.src=t}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i.src=t},t.prototype._saveImageIntoDBAsync=function(i,r){var n=this;if(this.isSupported){var o=function(){var e;if(s){var t=window.URL||window.webkitURL;try{e=t.createObjectURL(s,{oneTimeOnly:!0})}catch(i){e=t.createObjectURL(s)}}r.src=e};if(t.IsUASupportingBlobStorage){var s,a=new XMLHttpRequest;a.open("GET",i,!0),a.responseType="blob",a.addEventListener("load",(function(){if(200===a.status){s=a.response;var e=n.db.transaction(["textures"],"readwrite");e.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(n.hasReachedQuota=!0)}catch(t){}o()},e.oncomplete=function(e){o()};var h={textureUrl:i,data:s};try{var c=e.objectStore("textures").put(h);c.onsuccess=function(e){},c.onerror=function(e){o()}}catch(l){25===l.code&&(t.IsUASupportingBlobStorage=!1),r.src=i}}else r.src=i}),!1),a.addEventListener("error",(function(t){e.Tools.Error("Error in XHR request in BABYLON.Database."),r.src=i}),!1),a.send()}else r.src=i}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),
r.src=i},t.prototype._checkVersionFromDB=function(e,t){var i=this,r=function(r){i._saveVersionIntoDBAsync(e,t)};this._loadVersionFromDBAsync(e,t,r)},t.prototype._loadVersionFromDBAsync=function(t,i,r){var n=this;if(this.isSupported){var o;try{var s=this.db.transaction(["versions"]);s.oncomplete=function(e){o?n.manifestVersionFound>o.data?(n.mustUpdateRessources=!0,r()):i(o.data):(n.mustUpdateRessources=!0,r())},s.onabort=function(e){i(-1)};var a=s.objectStore("versions").get(t);a.onsuccess=function(e){o=e.target.result},a.onerror=function(r){e.Tools.Error("Error loading version for scene "+t+" from DB."),i(-1)}}catch(h){e.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: "+h.message),i(-1)}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i(-1)},t.prototype._saveVersionIntoDBAsync=function(t,i){var r=this;if(this.isSupported&&!this.hasReachedQuota)try{var n=this.db.transaction(["versions"],"readwrite");n.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(r.hasReachedQuota=!0)}catch(t){}i(-1)},n.oncomplete=function(e){i(r.manifestVersionFound)};var o={sceneUrl:t,data:this.manifestVersionFound},s=n.objectStore("versions").put(o);s.onsuccess=function(e){},s.onerror=function(t){e.Tools.Error("Error in DB add version request in BABYLON.Database.")}}catch(a){e.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+a.message),i(-1)}else i(-1)},t.prototype.loadFileFromDB=function(e,i,r,n,o){var s=this,a=t.ReturnFullUrlLocation(e),h=function(e){s._saveFileIntoDBAsync(a,i,r)};this._checkVersionFromDB(a,(function(e){e!==-1?s.mustUpdateRessources?s._saveFileIntoDBAsync(a,i,r,o):s._loadFileFromDBAsync(a,i,h,o):n()}))},t.prototype._loadFileFromDBAsync=function(t,i,r,n){if(this.isSupported){var o;o=t.indexOf(".babylon")!==-1?"scenes":"textures";var s,a=this.db.transaction([o]);a.oncomplete=function(e){s?i(s.data):r()},a.onabort=function(e){r()};var h=a.objectStore(o).get(t);h.onsuccess=function(e){s=e.target.result},h.onerror=function(i){e.Tools.Error("Error loading file "+t+" from DB."),r()}}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.prototype._saveFileIntoDBAsync=function(t,i,r,n){var o=this;if(this.isSupported){var s;s=t.indexOf(".babylon")!==-1?"scenes":"textures";var a,h=new XMLHttpRequest;h.open("GET",t,!0),n&&(h.responseType="arraybuffer"),h.onprogress=r,h.addEventListener("load",(function(){if(200===h.status||e.Tools.ValidateXHRData(h,n?6:1))if(a=n?h.response:h.responseText,o.hasReachedQuota)i(a);else{var r=o.db.transaction([s],"readwrite");r.onabort=function(e){try{e.srcElement.error&&"QuotaExceededError"===e.srcElement.error.name&&(o.hasReachedQuota=!0)}catch(t){}i(a)},r.oncomplete=function(e){i(a)};var c;c="scenes"===s?{sceneUrl:t,data:a,version:o.manifestVersionFound}:{textureUrl:t,data:a};try{var l=r.objectStore(s).put(c);l.onsuccess=function(e){},l.onerror=function(t){e.Tools.Error("Error in DB add file request in BABYLON.Database.")}}catch(u){i(a)}}else i()}),!1),h.addEventListener("error",(function(t){e.Tools.Error("error on XHR request."),i()}),!1),h.send()}else e.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),i()},t.IsUASupportingBlobStorage=!0,t.IDBStorageEnabled=!0,t.parseURL=function(e){var t=document.createElement("a");t.href=e;var i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),n=e.substring(0,e.indexOf(r,0));return n},t.ReturnFullUrlLocation=function(e){return e.indexOf("http:/")===-1?t.parseURL(window.location.href)+e:e},t})();e.Database=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){}return t.GetTGAHeader=function(e){var t=0,i={id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]};return i},t.UploadContent=function(i,r){if(r.length<19)return void e.Tools.Error("Unable to load TGA file - Not enough data to contain header");var n=18,o=t.GetTGAHeader(r);if(o.id_length+n>r.length)return void e.Tools.Error("Unable to load TGA file - Not enough data");n+=o.id_length;var s=!1,a=!1,h=!1,c=!1;switch(o.image_type){case t._TYPE_RLE_INDEXED:s=!0;case t._TYPE_INDEXED:a=!0;break;case t._TYPE_RLE_RGB:s=!0;case t._TYPE_RGB:h=!0;break;case t._TYPE_RLE_GREY:s=!0;case t._TYPE_GREY:c=!0}var l,u,d=(15&o.flags,o.pixel_size>>3),f=o.width*o.height*d;if(a&&(u=r.subarray(n,n+=o.colormap_length*(o.colormap_size>>3))),s){l=new Uint8Array(f);for(var p,_,m,g=0,v=new Uint8Array(d);n<f&&g<f;)if(p=r[n++],_=(127&p)+1,128&p){for(m=0;m<d;++m)v[m]=r[n++];for(m=0;m<_;++m)l.set(v,g+m*d);g+=d*_}else{for(_*=d,m=0;m<_;++m)l[g+m]=r[n++];g+=_}}else l=r.subarray(n,n+=a?o.width*o.height:f);var y,x,b,A,T,E;switch((o.flags&t._ORIGIN_MASK)>>t._ORIGIN_SHIFT){default:case t._ORIGIN_UL:y=0,b=1,E=o.width,x=0,A=1,T=o.height;break;case t._ORIGIN_BL:y=0,b=1,E=o.width,x=o.height-1,A=-1,T=-1;break;case t._ORIGIN_UR:y=o.width-1,b=-1,E=-1,x=0,A=1,T=o.height;break;case t._ORIGIN_BR:y=o.width-1,b=-1,E=-1,x=o.height-1,A=-1,T=-1}var P="_getImageData"+(c?"Grey":"")+o.pixel_size+"bits",S=t[P](o,u,l,x,A,T,y,b,E);i.texImage2D(i.TEXTURE_2D,0,i.RGBA,o.width,o.height,0,i.RGBA,i.UNSIGNED_BYTE,S)},t._getImageData8bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,d=i,f=t,p=e.width,_=e.height,m=0,g=new Uint8Array(p*_*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,m++)c=d[m],g[4*(l+p*u)+3]=255,g[4*(l+p*u)+2]=f[3*c+0],g[4*(l+p*u)+1]=f[3*c+1],g[4*(l+p*u)+0]=f[3*c+2];return g},t._getImageData16bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,_+=2)c=d[_+0]+(d[_+1]<<8),m[4*(l+f*u)+0]=(31744&c)>>7,m[4*(l+f*u)+1]=(992&c)>>2,m[4*(l+f*u)+2]=(31&c)>>3,m[4*(l+f*u)+3]=32768&c?0:255;return m},t._getImageData24bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=3)_[4*(c+d*l)+3]=255,_[4*(c+d*l)+2]=u[p+0],_[4*(c+d*l)+1]=u[p+1],_[4*(c+d*l)+0]=u[p+2];return _},t._getImageData32bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=4)_[4*(c+d*l)+2]=u[p+0],_[4*(c+d*l)+1]=u[p+1],_[4*(c+d*l)+0]=u[p+2],_[4*(c+d*l)+3]=u[p+3];return _},t._getImageDataGrey8bits=function(e,t,i,r,n,o,s,a,h){var c,l,u,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(u=r;u!==o;u+=n)for(l=s;l!==h;l+=a,_++)c=d[_],m[4*(l+f*u)+0]=c,m[4*(l+f*u)+1]=c,m[4*(l+f*u)+2]=c,m[4*(l+f*u)+3]=255;return m},t._getImageDataGrey16bits=function(e,t,i,r,n,o,s,a,h){var c,l,u=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(l=r;l!==o;l+=n)for(c=s;c!==h;c+=a,p+=2)_[4*(c+d*l)+0]=u[p+0],_[4*(c+d*l)+1]=u[p+0],_[4*(c+d*l)+2]=u[p+0],_[4*(c+d*l)+3]=u[p+1];return _},t._TYPE_NO_DATA=0,t._TYPE_INDEXED=1,t._TYPE_RGB=2,t._TYPE_GREY=3,t._TYPE_RLE_INDEXED=9,t._TYPE_RLE_RGB=10,t._TYPE_RLE_GREY=11,t._ORIGIN_MASK=48,t._ORIGIN_SHIFT=4,t._ORIGIN_BL=0,t._ORIGIN_BR=1,t._ORIGIN_UL=2,t._ORIGIN_UR=3,t})();t.TGATools=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(t){this.length=0,this._duplicateId=0,this.data=new Array(t),this._id=e._GlobalId++}return e.prototype.push=function(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId},e.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},e.prototype.sort=function(e){this.data.sort(e)},e.prototype.reset=function(){this.length=0,this._duplicateId++},e.prototype.concat=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}},e.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++){var i=(e.data||e)[t];this.pushNoDuplicate(i)}}},e.prototype.indexOf=function(e){var t=this.data.indexOf(e);return t>=this.length?-1:t},e._GlobalId=0,e})();e.SmartArray=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._count=0,this._data={}}return e.prototype.copyFrom=function(e){var t=this;this.clear(),e.forEach((function(e,i){return t.add(e,i)}))},e.prototype.get=function(e){var t=this._data[e];if(void 0!==t)return t},e.prototype.getOrAddWithFactory=function(e,t){var i=this.get(e);return void 0!==i?i:(i=t(e),i&&this.add(e,i),i)},e.prototype.getOrAdd=function(e,t){var i=this.get(e);return void 0!==i?i:(this.add(e,t),t)},e.prototype.contains=function(e){return void 0!==this._data[e]},e.prototype.add=function(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)},e.prototype.set=function(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)},e.prototype.getAndRemove=function(e){var t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null},e.prototype.remove=function(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)},e.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(e.prototype,"count",{get:function(){return this._count},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e){for(var t in this._data){var i=this._data[t];e(t,i)}},e.prototype.first=function(e){for(var t in this._data){var i=this._data[t],r=e(t,i);if(r)return r}return null},e})();e.StringDictionary=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){function t(e,t){return function(i){i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}var i,r=function(t,i){return t?t instanceof e.Mesh?null:t instanceof e.SubMesh?t.clone(i):t.clone?t.clone():null:null},n=(function(){function t(){}return t.Instantiate=function(e){for(var t=e.split("."),i=window||this,r=0,n=t.length;r<n;r++)i=i[t[r]];return"function"!=typeof i?null:i},t.SetImmediate=function(e){window.setImmediate?window.setImmediate(e):setTimeout(e,1)},t.IsExponentOfTwo=function(e){var t=1;do t*=2;while(t<e);return t===e},t.GetExponentOfTwo=function(e,t){var i=1;do i*=2;while(i<e);return i>t&&(i=t),i},t.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},t.GetDOMTextContent=function(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t},t.ToDegrees=function(e){return 180*e/Math.PI},t.ToRadians=function(e){return e*Math.PI/180},t.EncodeArrayBufferTobase64=function(e){for(var t,i,r,n,o,s,a,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",l=0,u=new Uint8Array(e);l<u.length;)t=u[l++],i=l<u.length?u[l++]:Number.NaN,r=l<u.length?u[l++]:Number.NaN,n=t>>2,o=(3&t)<<4|i>>4,s=(15&i)<<2|r>>6,a=63&r,isNaN(i)?s=a=64:isNaN(r)&&(a=64),c+=h.charAt(n)+h.charAt(o)+h.charAt(s)+h.charAt(a);return"data:image/png;base64,"+c},t.ExtractMinAndMaxIndexed=function(t,i,r,n,o){void 0===o&&(o=null);for(var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE)),h=r;h<r+n;h++){var c=new e.Vector3(t[3*i[h]],t[3*i[h]+1],t[3*i[h]+2]);s=e.Vector3.Minimize(c,s),a=e.Vector3.Maximize(c,a)}return o&&(s.x-=s.x*o.x+o.y,s.y-=s.y*o.x+o.y,s.z-=s.z*o.x+o.y,a.x+=a.x*o.x+o.y,a.y+=a.y*o.x+o.y,a.z+=a.z*o.x+o.y),{minimum:s,maximum:a}},t.ExtractMinAndMax=function(t,i,r,n,o){void 0===n&&(n=null);var s=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE));o||(o=3);for(var h=i;h<i+r;h++){var c=new e.Vector3(t[h*o],t[h*o+1],t[h*o+2]);s=e.Vector3.Minimize(c,s),a=e.Vector3.Maximize(c,a)}return n&&(s.x-=s.x*n.x+n.y,s.y-=s.y*n.x+n.y,s.z-=s.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:s,maximum:a}},t.Vector2ArrayFeeder=function(t){return function(i){var r=void 0!==t.BYTES_PER_ELEMENT,n=r?t.length/2:t.length;if(i>=n)return null;if(r){var o=t;return new e.Vector2(o[2*i+0],o[2*i+1])}var s=t;return s[i]}},t.ExtractMinAndMaxVector2=function(t,i){void 0===i&&(i=null);for(var r=new e.Vector2(Number.MAX_VALUE,Number.MAX_VALUE),n=new e.Vector2((-Number.MAX_VALUE),(-Number.MAX_VALUE)),o=0,s=t(o++);s;)r=e.Vector2.Minimize(s,r),n=e.Vector2.Maximize(s,n),s=t(o++);return i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y),{minimum:r,maximum:n}},t.MakeArray=function(e,t){if(t===!0||void 0!==e&&null!=e)return Array.isArray(e)?e:[e]},t.GetPointerPrefix=function(){var e="pointer";return window.PointerEvent||navigator.pointerEnabled||(e="mouse"),e},t.QueueNewFrame=function(e,t){void 0===t&&(t=window),t.requestAnimationFrame?t.requestAnimationFrame(e):t.msRequestAnimationFrame?t.msRequestAnimationFrame(e):t.webkitRequestAnimationFrame?t.webkitRequestAnimationFrame(e):t.mozRequestAnimationFrame?t.mozRequestAnimationFrame(e):t.oRequestAnimationFrame?t.oRequestAnimationFrame(e):window.setTimeout(e,16)},t.RequestFullscreen=function(e){var t=e.requestFullscreen||e.msRequestFullscreen||e.webkitRequestFullscreen||e.mozRequestFullScreen;t&&t.call(e)},t.ExitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msCancelFullScreen&&document.msCancelFullScreen()},t.SetCorsBehavior=function(e,i){if(t.CorsBehavior)switch(typeof t.CorsBehavior){case"function":var r=t.CorsBehavior(e);if(r)return r;break;case"string":default:i.crossOrigin=t.CorsBehavior}},t.CleanUrl=function(e){return e=e.replace(/#/gm,"%23")},t.LoadImage=function(i,r,n,o){i instanceof ArrayBuffer&&(i=t.EncodeArrayBufferTobase64(i)),i=t.CleanUrl(i);var s=new Image;"data:"!==i.substr(0,5)&&t.SetCorsBehavior(i,s),s.onload=function(){r(s)},s.onerror=function(e){t.Error("Error while trying to load texture: "+i),t.UseFallbackTexture?(s.src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",r(s)):n()};var a=function(){s.src=i},h=function(){o.loadImageFromDB(i,s)};if("data:"!==i.substr(0,5)&&o&&o.enableTexturesOffline&&e.Database.IsUASupportingBlobStorage)o.openAsync(h,a);else if(i.indexOf("file:")===-1)a();else try{var c,l=i.substring(5).toLowerCase();try{c=URL.createObjectURL(e.FilesInput.FilesTextures[l],{oneTimeOnly:!0})}catch(u){c=URL.createObjectURL(e.FilesInput.FilesTextures[l])}s.src=c}catch(d){s.src=null}return s},t.LoadFile=function(i,r,n,o,s,a){i=t.CleanUrl(i);var h=function(){var e=new XMLHttpRequest,o=t.BaseUrl+i;e.open("GET",o,!0),s&&(e.responseType="arraybuffer"),e.onprogress=n,e.onreadystatechange=function(){if(4===e.readyState)if(e.onreadystatechange=null,e.status>=200&&e.status<300||navigator.isCocoonJS&&0===e.status)r(s?e.response:e.responseText);else{if(!a)throw new Error("Error status: "+e.status+" - Unable to load "+o);a()}},e.send(null)},c=function(){o.loadFileFromDB(i,r,n,h,s)};if(i.indexOf("file:")!==-1){var l=i.substring(5).toLowerCase();t.ReadFile(e.FilesInput.FilesToLoad[l],r,n,s)}else o&&o.enableSceneOffline?o.openAsync(c,h):h()},t.ReadFileAsDataURL=function(e,t,i){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onprogress=i,r.readAsDataURL(e)},t.ReadFile=function(e,i,r,n){var o=new FileReader;o.onerror=function(r){t.Log("Error while reading file: "+e.name),i(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},o.onload=function(e){i(e.target.result)},o.onprogress=r,n?o.readAsArrayBuffer(e):o.readAsText(e)},t.FileAsURL=function(e){var t=new Blob([e]),i=window.URL||window.webkitURL,r=i.createObjectURL(t);return r},t.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},t.CheckExtends=function(e,t,i){e.x<t.x&&(t.x=e.x),e.y<t.y&&(t.y=e.y),e.z<t.z&&(t.z=e.z),e.x>i.x&&(i.x=e.x),e.y>i.y&&(i.y=e.y),e.z>i.z&&(i.z=e.z)},t.DeepCopy=function(e,t,i,n){for(var o in e)if(("_"!==o[0]||n&&n.indexOf(o)!==-1)&&(!i||i.indexOf(o)===-1)){var s=e[o],a=typeof s;if("function"!==a)if("object"===a)if(s instanceof Array){if(t[o]=[],s.length>0)if("object"==typeof s[0])for(var h=0;h<s.length;h++){var c=r(s[h],t);t[o].indexOf(c)===-1&&t[o].push(c)}else t[o]=s.slice(0)}else t[o]=r(s,t);else t[o]=s}},t.IsEmpty=function(e){for(var t in e)return!1;return!0},t.RegisterTopRootEvents=function(e){for(var t=0;t<e.length;t++){var i=e[t];window.addEventListener(i.name,i.handler,!1);try{window.parent&&window.parent.addEventListener(i.name,i.handler,!1)}catch(r){}}},t.UnregisterTopRootEvents=function(e){for(var t=0;t<e.length;t++){var i=e[t];window.removeEventListener(i.name,i.handler);try{window.parent&&window.parent.removeEventListener(i.name,i.handler)}catch(r){}}},t.DumpFramebuffer=function(e,r,n,o,s){void 0===s&&(s="image/png");for(var a=4*e,h=r/2,c=n.readPixels(0,0,e,r),l=0;l<h;l++)for(var u=0;u<a;u++){var d=u+l*a,f=r-l-1,p=u+f*a,_=c[d];c[d]=c[p],c[p]=_}i||(i=document.createElement("canvas")),i.width=e,i.height=r;var m=i.getContext("2d"),g=m.createImageData(e,r),v=g.data;v.set(c),m.putImageData(g,0,0),t.EncodeScreenshotCanvasData(o,s)},t.EncodeScreenshotCanvasData=function(e,t){void 0===t&&(t="image/png");var r=i.toDataURL(t);if(e)e(r);else if("download"in document.createElement("a")){var n=window.document.createElement("a");n.href=r;var o=new Date,s=(o.getFullYear()+"-"+(o.getMonth()+1)).slice(-2)+"-"+o.getDate()+"_"+o.getHours()+"-"+("0"+o.getMinutes()).slice(-2);n.setAttribute("download","screenshot_"+s+".png"),window.document.body.appendChild(n),n.addEventListener("click",(function(){n.parentElement.removeChild(n)})),n.click()}else{var a=window.open(""),h=a.document.createElement("img");h.src=r,a.document.body.appendChild(h)}},t.CreateScreenshot=function(e,r,n,o,s){void 0===s&&(s="image/png");var a,h;if(n.precision)a=Math.round(e.getRenderWidth()*n.precision),h=Math.round(a/e.getAspectRatio(r));else if(n.width&&n.height)a=n.width,h=n.height;else if(n.width&&!n.height)a=n.width,h=Math.round(a/e.getAspectRatio(r));else if(n.height&&!n.width)h=n.height,a=Math.round(h*e.getAspectRatio(r));else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");h=n,a=n}i||(i=document.createElement("canvas")),i.width=a,i.height=h;var c=i.getContext("2d");c.drawImage(e.getRenderingCanvas(),0,0,a,h),t.EncodeScreenshotCanvasData(o,s)},t.CreateScreenshotUsingRenderTarget=function(i,r,n,o,s){void 0===s&&(s="image/png");var a,h;if(n.precision)a=Math.round(i.getRenderWidth()*n.precision),h=Math.round(a/i.getAspectRatio(r)),n={width:a,height:h};else if(n.width&&n.height)a=n.width,h=n.height;else if(n.width&&!n.height)a=n.width,h=Math.round(a/i.getAspectRatio(r)),n={width:a,height:h};else if(n.height&&!n.width)h=n.height,a=Math.round(h*i.getAspectRatio(r)),n={width:a,height:h};else{if(isNaN(n))return void t.Error("Invalid 'size' parameter !");h=n,a=n}var c=r.getScene(),l=null;c.activeCamera!==r&&(l=c.activeCamera,c.activeCamera=r);var u=new e.RenderTargetTexture("screenShot",n,c,(!1),(!1));u.renderList=c.meshes,u.onAfterRenderObservable.add((function(){t.DumpFramebuffer(a,h,i,o,s)})),c.incrementRenderId(),c.resetCachedMaterial(),u.render(!0),u.dispose(),l&&(c.activeCamera=l),r.getProjectionMatrix(!0)},t.ValidateXHRData=function(t,i){void 0===i&&(i=7);try{if(1&i){if(t.responseText&&t.responseText.length>0)return!0;if(1===i)return!1}if(2&i){var r=e.Internals.TGATools.GetTGAHeader(t.response);if(r.width&&r.height&&r.width>0&&r.height>0)return!0;if(2===i)return!1}if(4&i){var n=new Uint8Array(t.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(o){}return!1},t.RandomId=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0,i="x"===e?t:3&t|8;return i.toString(16)}))},Object.defineProperty(t,"NoneLogLevel",{get:function(){return t._NoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MessageLogLevel",{get:function(){return t._MessageLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WarningLogLevel",{get:function(){return t._WarningLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ErrorLogLevel",{get:function(){return t._ErrorLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"AllLogLevel",{get:function(){return t._MessageLogLevel|t._WarningLogLevel|t._ErrorLogLevel},enumerable:!0,configurable:!0}),t._AddLogEntry=function(e){t._LogCache=e+t._LogCache,t.OnNewCacheEntry&&t.OnNewCacheEntry(e)},t._FormatMessage=function(e){var t=function(e){return e<10?"0"+e:""+e},i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e},t._LogDisabled=function(e){},t._LogEnabled=function(e){var i=t._FormatMessage(e);console.log("BJS - "+i);var r="<div style='color:white'>"+i+"</div><br>";t._AddLogEntry(r)},t._WarnDisabled=function(e){},t._WarnEnabled=function(e){var i=t._FormatMessage(e);console.warn("BJS - "+i);var r="<div style='color:orange'>"+i+"</div><br>";t._AddLogEntry(r)},t._ErrorDisabled=function(e){},t._ErrorEnabled=function(e){t.errorsCount++;var i=t._FormatMessage(e);console.error("BJS - "+i);var r="<div style='color:red'>"+i+"</div><br>";t._AddLogEntry(r)},Object.defineProperty(t,"LogCache",{get:function(){return t._LogCache},enumerable:!0,configurable:!0}),t.ClearLogCache=function(){t._LogCache="",t.errorsCount=0},Object.defineProperty(t,"LogLevels",{set:function(e){(e&t.MessageLogLevel)===t.MessageLogLevel?t.Log=t._LogEnabled:t.Log=t._LogDisabled,(e&t.WarningLogLevel)===t.WarningLogLevel?t.Warn=t._WarnEnabled:t.Warn=t._WarnDisabled,(e&t.ErrorLogLevel)===t.ErrorLogLevel?t.Error=t._ErrorEnabled:t.Error=t._ErrorDisabled},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceNoneLogLevel",{get:function(){return t._PerformanceNoneLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceUserMarkLogLevel",{get:function(){return t._PerformanceUserMarkLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceConsoleLogLevel",{get:function(){return t._PerformanceConsoleLogLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PerformanceLogLevel",{set:function(e){return(e&t.PerformanceUserMarkLogLevel)===t.PerformanceUserMarkLogLevel?(t.StartPerformanceCounter=t._StartUserMark,void(t.EndPerformanceCounter=t._EndUserMark)):(e&t.PerformanceConsoleLogLevel)===t.PerformanceConsoleLogLevel?(t.StartPerformanceCounter=t._StartPerformanceConsole,void(t.EndPerformanceCounter=t._EndPerformanceConsole)):(t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,void(t.EndPerformanceCounter=t._EndPerformanceCounterDisabled))},enumerable:!0,configurable:!0}),t._StartPerformanceCounterDisabled=function(e,t){},t._EndPerformanceCounterDisabled=function(e,t){},t._StartUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&t._performance.mark(e+"-Begin")},t._EndUserMark=function(e,i){void 0===i&&(i=!0),i&&t._performance.mark&&(t._performance.mark(e+"-End"),t._performance.measure(e,e+"-Begin",e+"-End"))},t._StartPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._StartUserMark(e,i),console.time&&console.time(e))},t._EndPerformanceConsole=function(e,i){void 0===i&&(i=!0),i&&(t._EndUserMark(e,i),console.time&&console.timeEnd(e))},Object.defineProperty(t,"Now",{get:function(){return window.performance&&window.performance.now?window.performance.now():(new Date).getTime()},enumerable:!0,configurable:!0}),t.getClassName=function(e,t){void 0===t&&(t=!1);var i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i},t.first=function(e,t){for(var i=0,r=e;i<r.length;i++){var n=r[i];if(t(n))return n}},t.getFullClassName=function(e,t){void 0===t&&(t=!1);var i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,r=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null},t.arrayOrStringFeeder=function(e){return function(i){if(i>=e.length)return null;var r=e.charCodeAt?e.charCodeAt(i):e[i];return r&&r.getHashCode&&(r=r.getHashCode()),"string"==typeof r?t.hashCodeFromStream(t.arrayOrStringFeeder(r)):r}},t.hashCodeFromStream=function(e){for(var t=0,i=0,r=e(i++);null!=r;)t=(t<<5)-t+r,t|=0,r=e(i++);return t},t.BaseUrl="",t.CorsBehavior="anonymous",t.UseFallbackTexture=!0,t._NoneLogLevel=0,t._MessageLogLevel=1,t._WarningLogLevel=2,t._ErrorLogLevel=4,t._LogCache="",t.errorsCount=0,t.Log=t._LogEnabled,t.Warn=t._WarnEnabled,t.Error=t._ErrorEnabled,t._PerformanceNoneLogLevel=0,t._PerformanceUserMarkLogLevel=1,t._PerformanceConsoleLogLevel=2,t._performance=window.performance,t.StartPerformanceCounter=t._StartPerformanceCounterDisabled,t.EndPerformanceCounter=t._EndPerformanceCounterDisabled,t})();e.Tools=n;var o=(function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(e,t){this._current+=e,t&&this._fetchResult()},e.prototype.beginMonitoring=function(){this._startMonitoringTime=n.Now},e.prototype.endMonitoring=function(e){void 0===e&&(e=!0),e&&this.fetchNewFrame();var t=n.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=n.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e})();e.PerfCounter=o,e.className=t;var s=(function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this._fn=t,this._successCallback=i,this.index=r-1,this._done=!1}return e.prototype.executeNext=function(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())},e.prototype.breakLoop=function(){this._done=!0,this._successCallback()},e.Run=function(t,i,r,n){void 0===n&&(n=0);var o=new e(t,i,r,n);return o.executeNext(),o},e.SyncAsyncForLoop=function(t,i,r,n,o,s){void 0===s&&(s=0),e.Run(Math.ceil(t/i),(function(e){o&&o()?e.breakLoop():setTimeout((function(){for(var n=0;n<i;++n){var s=e.index*i+n;if(s>=t)break;if(r(s),o&&o()){e.breakLoop();break}}e.executeNext()}),s)}),n)},e})();e.AsyncLoop=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._alphaBlend=!1,this._blendFunctionParameters=new Array(4),this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)},enumerable:!0,configurable:!0
}),e.prototype.setAlphaBlendFunctionParameters=function(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)},e.prototype.reset=function(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1))},e})();e._AlphaState=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)},enumerable:!0,configurable:!0}),e.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,0)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1))},e})();e._DepthCullingState=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.reset()}return Object.defineProperty(t.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFunc",{get:function(){return this._stencilFunc},set:function(e){this._stencilFunc!==e&&(this._stencilFunc=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFuncRef",{get:function(){return this._stencilFuncRef},set:function(e){this._stencilFuncRef!==e&&(this._stencilFuncRef=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilFuncMask",{get:function(){return this._stencilFuncMask},set:function(e){this._stencilFuncMask!==e&&(this._stencilFuncMask=e,this._isStencilFuncDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpStencilFail",{get:function(){return this._stencilOpStencilFail},set:function(e){this._stencilOpStencilFail!==e&&(this._stencilOpStencilFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpDepthFail",{get:function(){return this._stencilOpDepthFail},set:function(e){this._stencilOpDepthFail!==e&&(this._stencilOpDepthFail=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilOpStencilDepthPass",{get:function(){return this._stencilOpStencilDepthPass},set:function(e){this._stencilOpStencilDepthPass!==e&&(this._stencilOpStencilDepthPass=e,this._isStencilOpDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilMask",{get:function(){return this._stencilMask},set:function(e){this._stencilMask!==e&&(this._stencilMask=e,this._isStencilMaskDirty=!0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stencilTest",{get:function(){return this._stencilTest},set:function(e){this._stencilTest!==e&&(this._stencilTest=e,this._isStencilTestDirty=!0)},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=e.Engine.ALWAYS,this._stencilFuncRef=1,this._stencilFuncMask=255,this._stencilOpStencilFail=e.Engine.KEEP,this._stencilOpDepthFail=e.Engine.KEEP,this._stencilOpStencilDepthPass=e.Engine.REPLACE,this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},t.prototype.apply=function(e){this.isDirty&&(this._isStencilTestDirty&&(this.stencilTest?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.stencilMask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.stencilFunc,this.stencilFuncRef,this.stencilFuncMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.stencilOpStencilFail,this.stencilOpDepthFail,this.stencilOpStencilDepthPass),this._isStencilOpDirty=!1))},t})();t._StencilState=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t,i,r){var n=e.createShader("vertex"===i?e.VERTEX_SHADER:e.FRAGMENT_SHADER);if(e.shaderSource(n,(r?r+"\n":"")+t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error(e.getShaderInfoLog(n));return n},i=36193,r=function(e,t){return t===l.TEXTURETYPE_FLOAT?e.FLOAT:t===l.TEXTURETYPE_HALF_FLOAT?i:e.UNSIGNED_BYTE},n=function(t,i,r){var n=r.NEAREST,o=r.NEAREST;return t===e.Texture.BILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=i?r.LINEAR_MIPMAP_NEAREST:r.LINEAR):t===e.Texture.TRILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=i?r.LINEAR_MIPMAP_LINEAR:r.LINEAR):t===e.Texture.NEAREST_SAMPLINGMODE&&(n=r.NEAREST,o=i?r.NEAREST_MIPMAP_LINEAR:r.NEAREST),{min:o,mag:n}},o=function(t,i,r,o,s,a,h,c,l,u){void 0===u&&(u=e.Texture.TRILINEAR_SAMPLINGMODE);var d=r.getEngine(),f=e.Tools.GetExponentOfTwo(o,d.getCaps().maxTextureSize),p=e.Tools.GetExponentOfTwo(s,d.getCaps().maxTextureSize);d._bindTextureDirectly(i.TEXTURE_2D,t),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,void 0===a?1:a?1:0),t._baseWidth=o,t._baseHeight=s,t._width=f,t._height=p,t.isReady=!0,l(f,p);var _=n(u,!h,i);i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,_.mag),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,_.min),h||c||i.generateMipmap(i.TEXTURE_2D),d._bindTextureDirectly(i.TEXTURE_2D,null),d.resetTextureCache(),r._removePendingData(t),t.onLoadedCallbacks.forEach((function(e){e()})),t.onLoadedCallbacks=[]},s=function(t,i,r,n,o,s){void 0===s&&(s=null);var a,h=function(){r[i]=a,r._internalCount++,n._removePendingData(a),6===r._internalCount&&o(r)},c=function(){n._removePendingData(a),s&&s()};a=e.Tools.LoadImage(t,h,c,n.database),n._addPendingData(a)},a=function(e,t,i,r,n){void 0===n&&(n=null);var o=[];o._internalCount=0;for(var a=0;a<6;a++)s(r[a],a,o,t,i,n)},h=(function(){function e(){}return e})();e.InstancingAttributeInfo=h;var c=(function(){function e(){}return e})();e.EngineCapabilities=c;var l=(function(){function s(t,i,r,n){var o=this;void 0===n&&(n=!0),this.isFullscreen=!1,this.isPointerLock=!1,this.cullBackFaces=!0,this.renderEvenInBackground=!0,this.enableOfflineSupport=!0,this.scenes=new Array,this._windowIsBackground=!1,this._webGLVersion="1.0",this._badOS=!1,this._drawCalls=new e.PerfCounter,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.fpsRange=60,this.previousFramesDuration=[],this.fps=60,this.deltaTime=0,this._depthCullingState=new e.Internals._DepthCullingState,this._stencilState=new e.Internals._StencilState,this._alphaState=new e.Internals._AlphaState,this._alphaMode=s.ALPHA_DISABLE,this._loadedTexturesCache=new Array,this._maxTextureChannels=16,this._activeTexturesCache=new Array(this._maxTextureChannels),this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentBufferPointers=[],this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._texturesSupported=new Array,this._onVRFullScreenTriggered=function(){if(o._vrDisplayEnabled&&o._vrDisplayEnabled.isPresenting){o._oldSize=new e.Size(o.getRenderWidth(),o.getRenderHeight()),o._oldHardwareScaleFactor=o.getHardwareScalingLevel();var t=o._vrDisplayEnabled.getEyeParameters("left");o.setHardwareScalingLevel(1),o.setSize(2*t.renderWidth,t.renderHeight)}else o.setHardwareScalingLevel(o._oldHardwareScaleFactor),o.setSize(o._oldSize.width,o._oldSize.height),o._vrDisplayEnabled=void 0},this._renderingCanvas=t,this._externalData=new e.StringDictionary,r=r||{},null!=i&&(r.antialias=i),void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1);var a=this._canRenderToFloatTexture(),h=this._canRenderToHalfFloatTexture();if(!this._gl){if(!t)throw new Error("The provided canvas is null or undefined.");try{this._gl=t.getContext("webgl",r)||t.getContext("experimental-webgl",r)}catch(l){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported");this._onBlur=function(){o._windowIsBackground=!0},this._onFocus=function(){o._windowIsBackground=!1},window.addEventListener("blur",this._onBlur),window.addEventListener("focus",this._onFocus);var u=r.limitDeviceRatio||window.devicePixelRatio||1;this._hardwareScalingLevel=n?1/Math.min(u,window.devicePixelRatio||1):1,this.resize(),this._isStencilEnable=r.stencil,this._caps=new c,this._caps.maxTexturesImageUnits=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),this._caps.maxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),this._caps.maxCubemapTextureSize=this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),this._caps.maxRenderTextureSize=this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),this._caps.maxVertexAttribs=this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),this._glVersion=this._gl.getParameter(this._gl.VERSION);var d=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=d&&(this._glRenderer=this._gl.getParameter(d.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(d.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor="Unknown vendor"),this._glRenderer||(this._glRenderer="Unknown renderer"),this._caps.standardDerivatives=null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureFloat=null!==this._gl.getExtension("OES_texture_float"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.instancedArrays=this._gl.getExtension("ANGLE_instanced_arrays"),this._caps.uintIndices=null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!0,this._caps.drawBuffersExtension=this._gl.getExtension("WEBGL_draw_buffers"),this._caps.textureFloatLinearFiltering=this._gl.getExtension("OES_texture_float_linear"),this._caps.textureLOD=this._gl.getExtension("EXT_shader_texture_lod"),this._caps.textureFloatRender=a,this._caps.textureHalfFloat=null!==this._gl.getExtension("OES_texture_half_float"),this._caps.textureHalfFloatLinearFiltering=this._gl.getExtension("OES_texture_half_float_linear"),this._caps.textureHalfFloatRender=h,this._caps.astc&&this.texturesSupported.push(".astc"),this._caps.s3tc&&this.texturesSupported.push(".dds"),this._caps.pvrtc&&this.texturesSupported.push(".pvr"),this._caps.etc2&&this.texturesSupported.push(".etc2"),this._caps.etc1&&this.texturesSupported.push(".etc1"),this._gl.getShaderPrecisionFormat){var f=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);this._caps.highPrecisionShaderSupported=0!==f.precision}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._onFullscreenChange=function(){void 0!==document.fullscreen?o.isFullscreen=document.fullscreen:void 0!==document.mozFullScreen?o.isFullscreen=document.mozFullScreen:void 0!==document.webkitIsFullScreen?o.isFullscreen=document.webkitIsFullScreen:void 0!==document.msIsFullScreen&&(o.isFullscreen=document.msIsFullScreen),o.isFullscreen&&o._pointerLockRequested&&(t.requestPointerLock=t.requestPointerLock||t.msRequestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock&&t.requestPointerLock())},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("mozfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),document.addEventListener("msfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=function(){o.isPointerLock=document.mozPointerLockElement===t||document.webkitPointerLockElement===t||document.msPointerLockElement===t||document.pointerLockElement===t},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("mspointerlockchange",this._onPointerLockChange,!1),document.addEventListener("mozpointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1),e.AudioEngine&&!s.audioEngine&&(s.audioEngine=new e.AudioEngine),this._loadingScreen=new e.DefaultLoadingScreen(this._renderingCanvas),r.autoEnableWebVR&&this.initWebVR();var p=/AppleWebKit.*10.[\d] Mobile/;this._badOS=p.test(navigator.userAgent),e.Tools.Log("Babylon.js engine (v"+s.Version+") launched")}return Object.defineProperty(s,"NEVER",{get:function(){return s._NEVER},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALWAYS",{get:function(){return s._ALWAYS},enumerable:!0,configurable:!0}),Object.defineProperty(s,"LESS",{get:function(){return s._LESS},enumerable:!0,configurable:!0}),Object.defineProperty(s,"EQUAL",{get:function(){return s._EQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"LEQUAL",{get:function(){return s._LEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"GREATER",{get:function(){return s._GREATER},enumerable:!0,configurable:!0}),Object.defineProperty(s,"GEQUAL",{get:function(){return s._GEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"NOTEQUAL",{get:function(){return s._NOTEQUAL},enumerable:!0,configurable:!0}),Object.defineProperty(s,"KEEP",{get:function(){return s._KEEP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"REPLACE",{get:function(){return s._REPLACE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INCR",{get:function(){return s._INCR},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DECR",{get:function(){return s._DECR},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INVERT",{get:function(){return s._INVERT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"INCR_WRAP",{get:function(){return s._INCR_WRAP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DECR_WRAP",{get:function(){return s._DECR_WRAP},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_DISABLE",{get:function(){return s._ALPHA_DISABLE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_ONEONE",{get:function(){return s._ALPHA_ONEONE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_ADD",{get:function(){return s._ALPHA_ADD},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_COMBINE",{get:function(){return s._ALPHA_COMBINE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_SUBTRACT",{get:function(){return s._ALPHA_SUBTRACT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_MULTIPLY",{get:function(){return s._ALPHA_MULTIPLY},enumerable:!0,configurable:!0}),Object.defineProperty(s,"ALPHA_MAXIMIZED",{get:function(){return s._ALPHA_MAXIMIZED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_NONE",{get:function(){return s._DELAYLOADSTATE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_LOADED",{get:function(){return s._DELAYLOADSTATE_LOADED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_LOADING",{get:function(){return s._DELAYLOADSTATE_LOADING},enumerable:!0,configurable:!0}),Object.defineProperty(s,"DELAYLOADSTATE_NOTLOADED",{get:function(){return s._DELAYLOADSTATE_NOTLOADED},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_ALPHA",{get:function(){return s._TEXTUREFORMAT_ALPHA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_LUMINANCE",{get:function(){return s._TEXTUREFORMAT_LUMINANCE},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_LUMINANCE_ALPHA",{get:function(){return s._TEXTUREFORMAT_LUMINANCE_ALPHA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_RGB",{get:function(){return s._TEXTUREFORMAT_RGB},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTUREFORMAT_RGBA",{get:function(){return s._TEXTUREFORMAT_RGBA},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_UNSIGNED_INT",{get:function(){return s._TEXTURETYPE_UNSIGNED_INT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_FLOAT",{get:function(){return s._TEXTURETYPE_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"TEXTURETYPE_HALF_FLOAT",{get:function(){return s._TEXTURETYPE_HALF_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(s,"Version",{get:function(){return"2.5"},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"webGLVersion",{get:function(){return this._webGLVersion},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"isStencilEnable",{get:function(){return this._isStencilEnable},enumerable:!0,configurable:!0}),s.prototype._prepareWorkingCanvas=function(){this._workingCanvas||(this._workingCanvas=document.createElement("canvas"),this._workingContext=this._workingCanvas.getContext("2d"))},s.prototype.resetTextureCache=function(){for(var e=0;e<this._maxTextureChannels;e++)this._activeTexturesCache[e]=null},s.prototype.getGlInfo=function(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}},s.prototype.getAspectRatio=function(e,t){void 0===t&&(t=!1);var i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},s.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget._width:this._renderingCanvas.width},s.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget._height:this._renderingCanvas.height},s.prototype.getRenderingCanvas=function(){return this._renderingCanvas},s.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas.getBoundingClientRect()},s.prototype.setHardwareScalingLevel=function(e){this._hardwareScalingLevel=e,this.resize()},s.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel},s.prototype.getLoadedTexturesCache=function(){return this._loadedTexturesCache},s.prototype.getCaps=function(){return this._caps},Object.defineProperty(s.prototype,"drawCalls",{get:function(){return this._drawCalls.current},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"drawCallsPerfCounter",{get:function(){return this._drawCalls},enumerable:!0,configurable:!0}),s.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},s.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},s.prototype.setDepthFunctionToGreater=function(){this._depthCullingState.depthFunc=this._gl.GREATER},s.prototype.setDepthFunctionToGreaterOrEqual=function(){this._depthCullingState.depthFunc=this._gl.GEQUAL},s.prototype.setDepthFunctionToLess=function(){this._depthCullingState.depthFunc=this._gl.LESS},s.prototype.setDepthFunctionToLessOrEqual=function(){this._depthCullingState.depthFunc=this._gl.LEQUAL},s.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},s.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},s.prototype.getStencilMask=function(){return this._stencilState.stencilMask},s.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},s.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},s.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},s.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},s.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},s.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},s.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},s.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},s.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},s.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},s.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},s.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},s.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},s.prototype.stopRenderLoop=function(e){if(!e)return void(this._activeRenderLoops=[]);var t=this._activeRenderLoops.indexOf(e);t>=0&&this._activeRenderLoops.splice(t,1)},s.prototype._renderLoop=function(){var t=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(t=!1),t){this.beginFrame();for(var i=0;i<this._activeRenderLoops.length;i++){var r=this._activeRenderLoops[i];r()}this.endFrame()}this._activeRenderLoops.length>0?e.Tools.QueueNewFrame(this._bindedRenderFunction,this._vrDisplayEnabled):this._renderingQueueLaunched=!1},s.prototype.runRenderLoop=function(t){this._activeRenderLoops.indexOf(t)===-1&&(this._activeRenderLoops.push(t),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),e.Tools.QueueNewFrame(this._bindedRenderFunction)))},s.prototype.switchFullscreen=function(t){this.isFullscreen?e.Tools.ExitFullscreen():(this._pointerLockRequested=t,e.Tools.RequestFullscreen(this._renderingCanvas))},s.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),this.applyStates();var n=0;t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)},s.prototype.scissorClear=function(e,t,i,r,n){var o=this._gl,s=o.getParameter(o.SCISSOR_TEST),a=o.getParameter(o.SCISSOR_BOX);o.enable(o.SCISSOR_TEST),o.scissor(e,t,i,r),this.clear(n,!0,!0,!0),o.scissor(a[0],a[1],a[2],a[3]),s===!0?o.enable(o.SCISSOR_TEST):o.disable(o.SCISSOR_TEST)},s.prototype.setViewport=function(e,t,i){var r=t||(navigator.isCocoonJS?window.innerWidth:this._renderingCanvas.width),n=i||(navigator.isCocoonJS?window.innerHeight:this._renderingCanvas.height),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._gl.viewport(o*r,s*n,r*e.width,n*e.height)},s.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._gl.viewport(e,t,i,r),n},s.prototype.beginFrame=function(){this._measureFps()},s.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._vrDisplayEnabled&&this._vrDisplayEnabled.isPresenting&&this._vrDisplayEnabled.submitFrame()},s.prototype.resize=function(){var t=navigator.isCocoonJS?window.innerWidth:this._renderingCanvas.clientWidth,i=navigator.isCocoonJS?window.innerHeight:this._renderingCanvas.clientHeight;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel);for(var r=0;r<this.scenes.length;r++){var n=this.scenes[r];e.DebugLayer&&n.debugLayer.isVisible()&&n.debugLayer._syncPositions()}},s.prototype.setSize=function(e,t){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i<this.scenes.length;i++)for(var r=this.scenes[i],n=0;n<r.cameras.length;n++){var o=r.cameras[n];o._currentRenderId=0}},s.prototype.initWebVR=function(){this.vrDisplaysPromise||this._getVRDisplays()},s.prototype.enableVR=function(e){this._vrDisplayEnabled=e,this._vrDisplayEnabled.requestPresent([{source:this.getRenderingCanvas()}]).then(this._onVRFullScreenTriggered)},s.prototype.disableVR=function(){this._vrDisplayEnabled&&this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered)},s.prototype._getVRDisplays=function(){var e=this,t=function(t){var i=(t.length,0);return e._vrDisplays=t.filter((function(e){return t[i]instanceof VRDisplay})),e._vrDisplays};navigator.getVRDisplays&&(this.vrDisplaysPromise=navigator.getVRDisplays().then(t))},s.prototype.bindFramebuffer=function(e,t,i,r){this._currentRenderTarget=e,this.bindUnboundFramebuffer(e._framebuffer);var n=this._gl;e.isCube&&n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+t,e,0),n.viewport(0,0,i||e._width,r||e._height),this.wipeCaches()},s.prototype.bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)},s.prototype.unBindFramebuffer=function(e,t){if(void 0===t&&(t=!1),this._currentRenderTarget=null,e.generateMipMaps&&!t){var i=this._gl;this._bindTextureDirectly(i.TEXTURE_2D,e),i.generateMipmap(i.TEXTURE_2D),this._bindTextureDirectly(i.TEXTURE_2D,null)}this.bindUnboundFramebuffer(null)},s.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){var t=this._gl;this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,e),t.generateMipmap(t.TEXTURE_CUBE_MAP),this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)}},s.prototype.flushFramebuffer=function(){this._gl.flush()},s.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget=null,this.bindUnboundFramebuffer(null),this.setViewport(this._cachedViewport),this.wipeCaches()},s.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},s.prototype.createVertexBuffer=function(e){var t=this._gl.createBuffer();return this.bindArrayBuffer(t),e instanceof Float32Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this._resetVertexBufferBinding(),t.references=1,t},s.prototype.createDynamicVertexBuffer=function(e){var t=this._gl.createBuffer();return this.bindArrayBuffer(t),e instanceof Float32Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this._resetVertexBufferBinding(),t.references=1,t},s.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this._resetVertexBufferBinding()},s.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},s.prototype.createIndexBuffer=function(e){var t=this._gl.createBuffer();this.bindIndexBuffer(t);var i,r=!1;if(this._caps.uintIndices){for(var n=0;n<e.length;n++)if(e[n]>65535){r=!0;break}i=r?new Uint32Array(e):new Uint16Array(e)}else i=new Uint16Array(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),t.references=1,t.is32Bits=r,t},s.prototype.bindArrayBuffer=function(e){this.bindBuffer(e,this._gl.ARRAY_BUFFER)},s.prototype.bindIndexBuffer=function(e){this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},s.prototype.bindBuffer=function(e,t){this._currentBoundBuffer[t]!==e&&(this._gl.bindBuffer(t,e),this._currentBoundBuffer[t]=e)},s.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},s.prototype.vertexAttribPointer=function(e,t,i,r,n,o,s){var a=this._currentBufferPointers[t],h=!1;a?(a.buffer!==e&&(a.buffer=e,h=!0),a.size!==i&&(a.size=i,h=!0),a.type!==r&&(a.type=r,h=!0),a.normalized!==n&&(a.normalized=n,h=!0),a.stride!==o&&(a.stride=o,h=!0),a.offset!==s&&(a.offset=s,h=!0)):(h=!0,this._currentBufferPointers[t]={indx:t,size:i,type:r,normalized:n,stride:o,offset:s,buffer:e}),h&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,r,n,o,s))},s.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;for(var o=n.getAttributesCount(),s=0,a=0;a<o;a++)if(a<i.length){var h=n.getAttributeLocation(a);h>=0&&(this._vertexAttribArraysEnabled[h]||(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0),this.vertexAttribPointer(e,h,i[a],this._gl.FLOAT,!1,r,s)),s+=4*i[a]}else{var h=n.getAttributeLocation(a);this._vertexAttribArraysEnabled[h]&&(this._gl.disableVertexAttribArray(h),
this._vertexAttribArraysEnabled[h]=!1)}}this._cachedIndexBuffer!==t&&(this._cachedIndexBuffer=t,this.bindIndexBuffer(t),this._uintIndicesCurrentlySet=t.is32Bits)},s.prototype.bindBuffers=function(e,t,i){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i;for(var r=i.getAttributesNames(),n=0;n<r.length;n++){var o=i.getAttributeLocation(n);if(o>=0){var s=e[r[n]];if(!s){this._vertexAttribArraysEnabled[o]&&(this._gl.disableVertexAttribArray(o),this._vertexAttribArraysEnabled[o]=!1);continue}this._vertexAttribArraysEnabled[o]||(this._gl.enableVertexAttribArray(o),this._vertexAttribArraysEnabled[o]=!0);var a=s.getBuffer();this.vertexAttribPointer(a,o,s.getSize(),this._gl.FLOAT,!1,4*s.getStrideSize(),4*s.getOffset()),s.getIsInstanced()&&(this._caps.instancedArrays.vertexAttribDivisorANGLE(o,1),this._currentInstanceLocations.push(o),this._currentInstanceBuffers.push(a))}}}null!=t&&this._cachedIndexBuffer!==t&&(this._cachedIndexBuffer=t,this.bindIndexBuffer(t),this._uintIndicesCurrentlySet=t.is32Bits)},s.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t<i;t++){var r=this._currentInstanceBuffers[t];e!=r&&(e=r,this.bindArrayBuffer(r));var n=this._currentInstanceLocations[t];this._caps.instancedArrays.vertexAttribDivisorANGLE(n,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0},s.prototype._releaseBuffer=function(e){return e.references--,0===e.references&&(this._gl.deleteBuffer(e),!0)},s.prototype.createInstancesBuffer=function(e){var t=this._gl.createBuffer();return t.capacity=e,this.bindArrayBuffer(t),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),t},s.prototype.deleteInstancesBuffer=function(e){this._gl.deleteBuffer(e)},s.prototype.updateAndBindInstancesBuffer=function(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index){for(var r=0,n=0;n<i.length;n++){var o=i[n];r+=4*o.attributeSize}for(var n=0;n<i.length;n++){var o=i[n];this._vertexAttribArraysEnabled[o.index]||(this._gl.enableVertexAttribArray(o.index),this._vertexAttribArraysEnabled[o.index]=!0),this.vertexAttribPointer(e,o.index,o.attributeSize,o.attribyteType||this._gl.FLOAT,o.normalized||!1,r,o.offset),this._caps.instancedArrays.vertexAttribDivisorANGLE(o.index,1),this._currentInstanceLocations.push(o.index),this._currentInstanceBuffers.push(e)}}else for(var s=0;s<4;s++){var a=i[s];this._vertexAttribArraysEnabled[a]||(this._gl.enableVertexAttribArray(a),this._vertexAttribArraysEnabled[a]=!0),this.vertexAttribPointer(e,a,4,this._gl.FLOAT,!1,64,16*s),this._caps.instancedArrays.vertexAttribDivisorANGLE(a,1),this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(e)}},s.prototype.applyStates=function(){this._depthCullingState.apply(this._gl),this._stencilState.apply(this._gl),this._alphaState.apply(this._gl)},s.prototype.draw=function(e,t,i,r){this.applyStates(),this._drawCalls.addCount(1,!1);var n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,o=this._uintIndicesCurrentlySet?4:2;return r?void this._caps.instancedArrays.drawElementsInstancedANGLE(e?this._gl.TRIANGLES:this._gl.LINES,i,n,t*o,r):void this._gl.drawElements(e?this._gl.TRIANGLES:this._gl.LINES,i,n,t*o)},s.prototype.drawPointClouds=function(e,t,i){return this.applyStates(),this._drawCalls.addCount(1,!1),i?void this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS,e,t,i):void this._gl.drawArrays(this._gl.POINTS,e,t)},s.prototype.drawUnIndexed=function(e,t,i,r){return this.applyStates(),this._drawCalls.addCount(1,!1),r?void this._caps.instancedArrays.drawArraysInstancedANGLE(e?this._gl.TRIANGLES:this._gl.LINES,t,i,r):void this._gl.drawArrays(e?this._gl.TRIANGLES:this._gl.LINES,t,i)},s.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],e.getProgram()&&this._gl.deleteProgram(e.getProgram()))},s.prototype.createEffect=function(t,i,r,n,o,s,a,h,c){var l=t.vertexElement||t.vertex||t,u=t.fragmentElement||t.fragment||t,d=l+"+"+u+"@"+o;if(this._compiledEffects[d])return this._compiledEffects[d];var f=new e.Effect(t,i,r,n,this,o,s,a,h,c);return f._key=d,this._compiledEffects[d]=f,f},s.prototype.createEffectForParticles=function(e,t,i,r,n,o,s){return void 0===t&&(t=[]),void 0===i&&(i=[]),void 0===r&&(r=""),this.createEffect({vertex:"particles",fragmentElement:e},["position","color","options"],["view","projection"].concat(t),["diffuseSampler"].concat(i),r,n,o,s)},s.prototype.createShaderProgram=function(e,i,r,n){n=n||this._gl;var o=t(n,e,"vertex",r),s=t(n,i,"fragment",r),a=n.createProgram();n.attachShader(a,o),n.attachShader(a,s),n.linkProgram(a);var h=n.getProgramParameter(a,n.LINK_STATUS);if(!h){var c=n.getProgramInfoLog(a);if(c)throw new Error(c)}return n.deleteShader(o),n.deleteShader(s),a},s.prototype.getUniforms=function(e,t){for(var i=[],r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(e,t[r]));return i},s.prototype.getAttributes=function(e,t){for(var i=[],r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(e,t[r]))}catch(n){i.push(-1)}return i},s.prototype.enableEffect=function(e){this.setProgram(e.getProgram()),this._currentEffect=e,e.onBind&&e.onBind(e)},s.prototype.setIntArray=function(e,t){e&&this._gl.uniform1iv(e,t)},s.prototype.setIntArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2iv(e,t)},s.prototype.setIntArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3iv(e,t)},s.prototype.setIntArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4iv(e,t)},s.prototype.setFloatArray=function(e,t){e&&this._gl.uniform1fv(e,t)},s.prototype.setFloatArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2fv(e,t)},s.prototype.setFloatArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3fv(e,t)},s.prototype.setFloatArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4fv(e,t)},s.prototype.setArray=function(e,t){e&&this._gl.uniform1fv(e,t)},s.prototype.setArray2=function(e,t){e&&t.length%2===0&&this._gl.uniform2fv(e,t)},s.prototype.setArray3=function(e,t){e&&t.length%3===0&&this._gl.uniform3fv(e,t)},s.prototype.setArray4=function(e,t){e&&t.length%4===0&&this._gl.uniform4fv(e,t)},s.prototype.setMatrices=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t)},s.prototype.setMatrix=function(e,t){e&&this._gl.uniformMatrix4fv(e,!1,t.toArray())},s.prototype.setMatrix3x3=function(e,t){e&&this._gl.uniformMatrix3fv(e,!1,t)},s.prototype.setMatrix2x2=function(e,t){e&&this._gl.uniformMatrix2fv(e,!1,t)},s.prototype.setFloat=function(e,t){e&&this._gl.uniform1f(e,t)},s.prototype.setFloat2=function(e,t,i){e&&this._gl.uniform2f(e,t,i)},s.prototype.setFloat3=function(e,t,i,r){e&&this._gl.uniform3f(e,t,i,r)},s.prototype.setBool=function(e,t){e&&this._gl.uniform1i(e,t)},s.prototype.setFloat4=function(e,t,i,r,n){e&&this._gl.uniform4f(e,t,i,r,n)},s.prototype.setColor3=function(e,t){e&&this._gl.uniform3f(e,t.r,t.g,t.b)},s.prototype.setColor4=function(e,t,i){e&&this._gl.uniform4f(e,t.r,t.g,t.b,i)},s.prototype.setState=function(e,t,i,r){void 0===t&&(t=0),void 0===r&&(r=!1);var n=r?this._gl.FRONT:this._gl.BACK,o=r?this._gl.BACK:this._gl.FRONT,s=this.cullBackFaces?n:o;(this._depthCullingState.cull!==e||i||this._depthCullingState.cullFace!==s)&&(e?(this._depthCullingState.cullFace=s,this._depthCullingState.cull=!0):this._depthCullingState.cull=!1),this._depthCullingState.zOffset=t},s.prototype.setDepthBuffer=function(e){this._depthCullingState.depthTest=e},s.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},s.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},s.prototype.setColorWrite=function(e){this._gl.colorMask(e,e,e,e)},s.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode!==e){switch(e){case s.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case s.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case s.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0}t||this.setDepthWrite(e===s.ALPHA_DISABLE),this._alphaMode=e}},s.prototype.getAlphaMode=function(){return this._alphaMode},s.prototype.setAlphaTesting=function(e){this._alphaTest=e},s.prototype.getAlphaTesting=function(){return this._alphaTest},s.prototype.wipeCaches=function(){this.resetTextureCache(),this._currentEffect=null,this._stencilState.reset(),this._depthCullingState.reset(),this.setDepthFunctionToLessOrEqual(),this._alphaState.reset(),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null},s.prototype.setSamplingMode=function(t,i){var r=this._gl;this._bindTextureDirectly(r.TEXTURE_2D,t);var n=r.NEAREST,o=r.NEAREST;i===e.Texture.BILINEAR_SAMPLINGMODE?(n=r.LINEAR,o=r.LINEAR):i===e.Texture.TRILINEAR_SAMPLINGMODE&&(n=r.LINEAR,o=r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,n),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,o),this._bindTextureDirectly(r.TEXTURE_2D,null),t.samplingMode=i},s.prototype.setTextureFormatToUse=function(e){for(var t=0,i=this.texturesSupported.length;t<i;t++)if(".astc"!==this._texturesSupported[t]&&".pvr"!==this._texturesSupported[t]&&".etc1"!==this._texturesSupported[t]&&".etc2"!==this._texturesSupported[t])for(var r=0,n=e.length;r<n;r++)if(this._texturesSupported[t]===e[r].toLowerCase())return this._textureFormatInUse=this._texturesSupported[t];return this._textureFormatInUse=null},s.prototype.createTexture=function(t,i,r,n,s,a,h,c){var l=this;void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===h&&(h=null),void 0===c&&(c=null);var u,d=this._gl.createTexture(),f=!1;if("data:"===t.substr(0,5)&&(f=!0),f){var p=t;f=p.split(":"),t=p,u=f[1].substr(f[1].length-4,4).toLowerCase()}else{var _=t.lastIndexOf(".");u=t.substring(_).toLowerCase(),!this._textureFormatInUse||f||n.database||(u=this._textureFormatInUse,t=t.substring(0,_)+this._textureFormatInUse)}var m=".dds"===u,g=".tga"===u;n._addPendingData(d),d.url=t,d.noMipmap=i,d.references=1,d.samplingMode=s,d.onLoadedCallbacks=[a],this._loadedTexturesCache.push(d);var v,y=function(){n._removePendingData(d),h&&h()};if(g)v=function(t){var a=new Uint8Array(t),h=e.Internals.TGATools.GetTGAHeader(a);o(d,l._gl,n,h.width,h.height,r,i,!1,(function(){e.Internals.TGATools.UploadContent(l._gl,a)}),s)},f instanceof Array?v(c):e.Tools.LoadFile(t,(function(e){v(e)}),null,n.database,!0,y);else if(m)v=function(t){var a=e.Internals.DDSTools.GetDDSInfo(t),h=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&!i&&a.width>>a.mipmapCount-1===1;o(d,l._gl,n,a.width,a.height,r,!h,a.isFourCC,(function(){e.Internals.DDSTools.UploadDDSLevels(l._gl,l.getCaps().s3tc,t,a,h,1)}),s)},f instanceof Array?v(c):e.Tools.LoadFile(t,(function(e){v(e)}),null,n.database,!0,y);else{var x=function(t){o(d,l._gl,n,t.width,t.height,r,i,!1,(function(i,r){var n=t.width===i&&t.height===r;n||(l._prepareWorkingCanvas(),l._workingCanvas.width=i,l._workingCanvas.height=r,s===e.Texture.NEAREST_SAMPLINGMODE&&(l._workingContext.imageSmoothingEnabled=!1,l._workingContext.mozImageSmoothingEnabled=!1,l._workingContext.oImageSmoothingEnabled=!1,l._workingContext.webkitImageSmoothingEnabled=!1,l._workingContext.msImageSmoothingEnabled=!1),l._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,r),s===e.Texture.NEAREST_SAMPLINGMODE&&(l._workingContext.imageSmoothingEnabled=!0,l._workingContext.mozImageSmoothingEnabled=!0,l._workingContext.oImageSmoothingEnabled=!0,l._workingContext.webkitImageSmoothingEnabled=!0,l._workingContext.msImageSmoothingEnabled=!0)),l._gl.texImage2D(l._gl.TEXTURE_2D,0,l._gl.RGBA,l._gl.RGBA,l._gl.UNSIGNED_BYTE,n?t:l._workingCanvas)}),s)};f instanceof Array?e.Tools.LoadImage(c,x,y,n.database):e.Tools.LoadImage(t,x,y,n.database)}return d},s.prototype._getInternalFormat=function(e){var t=this._gl.RGBA;switch(e){case s.TEXTUREFORMAT_ALPHA:t=this._gl.ALPHA;break;case s.TEXTUREFORMAT_LUMINANCE:t=this._gl.LUMINANCE;break;case s.TEXTUREFORMAT_LUMINANCE_ALPHA:t=this._gl.LUMINANCE_ALPHA;break;case s.TEXTUREFORMAT_RGB:t=this._gl.RGB;break;case s.TEXTUREFORMAT_RGBA:t=this._gl.RGBA}return t},s.prototype.updateRawTexture=function(e,t,i,r,n){void 0===n&&(n=null);var o=this._getInternalFormat(i);this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,void 0===r?1:r?1:0),e._width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[n],e._width,e._height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e._width,e._height,0,o,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this.resetTextureCache(),e.isReady=!0},s.prototype.createRawTexture=function(e,t,i,r,o,s,a,h){void 0===h&&(h=null);var c=this._gl.createTexture();c._baseWidth=t,c._baseHeight=i,c._width=t,c._height=i,c.references=1,this.updateRawTexture(c,e,r,s,h),this._bindTextureDirectly(this._gl.TEXTURE_2D,c);var l=n(a,o,this._gl);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,l.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,l.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),c.samplingMode=a,this._loadedTexturesCache.push(c),c},s.prototype.createDynamicTexture=function(t,i,r,n){var o=this._gl.createTexture();return o._baseWidth=t,o._baseHeight=i,r&&(t=e.Tools.GetExponentOfTwo(t,this._caps.maxTextureSize),i=e.Tools.GetExponentOfTwo(i,this._caps.maxTextureSize)),this.resetTextureCache(),o._width=t,o._height=i,o.isReady=!1,o.generateMipMaps=r,o.references=1,o.samplingMode=n,this.updateTextureSamplingMode(n,o),this._loadedTexturesCache.push(o),o},s.prototype.updateTextureSamplingMode=function(e,t){var i=n(e,t.generateMipMaps,this._gl);t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null))},s.prototype.updateDynamicTexture=function(e,t,i,r){void 0===r&&(r=!1),this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?1:0),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this.resetTextureCache(),e.isReady=!0},s.prototype.updateVideoTexture=function(e,t,i){if(!e._isDisabled){this._bindTextureDirectly(this._gl.TEXTURE_2D,e),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,i?0:1);try{void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported?this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t):(e._workingCanvas||(e._workingCanvas=document.createElement("canvas"),e._workingContext=e._workingCanvas.getContext("2d"),e._workingCanvas.width=e._width,e._workingCanvas.height=e._height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e._width,e._height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this.resetTextureCache(),e.isReady=!0}catch(r){e._isDisabled=!0}}},s.prototype.createRenderTargetTexture=function(t,i){var o=!1,a=!0,h=!1,c=s.TEXTURETYPE_UNSIGNED_INT,l=e.Texture.TRILINEAR_SAMPLINGMODE;void 0!==i&&(o=void 0===i.generateMipMaps?i:i.generateMipMaps,a=void 0===i.generateDepthBuffer||i.generateDepthBuffer,h=a&&i.generateStencilBuffer,c=void 0===i.type?c:i.type,void 0!==i.samplingMode&&(l=i.samplingMode),c!==s.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?c!==s.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering||(l=e.Texture.NEAREST_SAMPLINGMODE):l=e.Texture.NEAREST_SAMPLINGMODE);var u=this._gl,d=u.createTexture();this._bindTextureDirectly(u.TEXTURE_2D,d);var f=t.width||t,p=t.height||t,_=n(l,o,u);c!==s.TEXTURETYPE_FLOAT||this._caps.textureFloat||(c=s.TEXTURETYPE_UNSIGNED_INT,e.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,_.mag),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,_.min),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,f,p,0,u.RGBA,r(u,c),null);var m;h?(m=u.createRenderbuffer(),u.bindRenderbuffer(u.RENDERBUFFER,m),u.renderbufferStorage(u.RENDERBUFFER,u.DEPTH_STENCIL,f,p)):a&&(m=u.createRenderbuffer(),u.bindRenderbuffer(u.RENDERBUFFER,m),u.renderbufferStorage(u.RENDERBUFFER,u.DEPTH_COMPONENT16,f,p));var g=u.createFramebuffer();return this.bindUnboundFramebuffer(g),h?u.framebufferRenderbuffer(u.FRAMEBUFFER,u.DEPTH_STENCIL_ATTACHMENT,u.RENDERBUFFER,m):a&&u.framebufferRenderbuffer(u.FRAMEBUFFER,u.DEPTH_ATTACHMENT,u.RENDERBUFFER,m),u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,d,0),o&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(u.TEXTURE_2D,null),u.bindRenderbuffer(u.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),d._framebuffer=g,a&&(d._depthBuffer=m),d._baseWidth=f,d._baseHeight=p,d._width=f,d._height=p,d.isReady=!0,d.generateMipMaps=o,d.references=1,d.samplingMode=l,d.type=c,this.resetTextureCache(),this._loadedTexturesCache.push(d),d},s.prototype.createRenderTargetCubeTexture=function(t,i){var r=this._gl,o=r.createTexture(),s=!0,a=!0,h=!1,c=e.Texture.TRILINEAR_SAMPLINGMODE;void 0!==i&&(s=void 0===i.generateMipMaps?i:i.generateMipMaps,a=void 0===i.generateDepthBuffer||i.generateDepthBuffer,h=a&&i.generateStencilBuffer,void 0!==i.samplingMode&&(c=i.samplingMode)),o.isCube=!0,o.references=1,o.generateMipMaps=s,o.references=1,o.samplingMode=c;var l=n(c,s,r);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,o);for(var u=0;u<6;u++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+u,0,r.RGBA,t,t,0,r.RGBA,r.UNSIGNED_BYTE,null);r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,l.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,l.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);var d;h?(d=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,d),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,t)):a&&(d=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,d),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT16,t,t));var f=r.createFramebuffer();return this.bindUnboundFramebuffer(f),h?r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,d):a&&r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,d),o.generateMipMaps&&(this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,o),r.generateMipmap(r.TEXTURE_CUBE_MAP)),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),r.bindRenderbuffer(r.RENDERBUFFER,null),this.bindUnboundFramebuffer(null),o._framebuffer=f,a&&(o._depthBuffer=d),o._width=t,o._height=t,o.isReady=!0,this.resetTextureCache(),this._loadedTexturesCache.push(o),o},s.prototype.createCubeTexture=function(t,i,r,n,o,s){var h=this;void 0===o&&(o=null),void 0===s&&(s=null);var c=this._gl,l=c.createTexture();l.isCube=!0,l.url=t,l.references=1,l.onLoadedCallbacks=[];var u=t.substr(t.length-4,4).toLowerCase(),d=this.getCaps().s3tc&&".dds"===u;return d?e.Tools.LoadFile(t,(function(t){var i=e.Internals.DDSTools.GetDDSInfo(t),r=(i.isRGB||i.isLuminance||i.mipmapCount>1)&&!n;h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l),c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,1),e.Internals.DDSTools.UploadDDSLevels(h._gl,h.getCaps().s3tc,t,i,r,6),n||i.isFourCC||1!==i.mipmapCount||c.generateMipmap(c.TEXTURE_CUBE_MAP),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,r?c.LINEAR_MIPMAP_LINEAR:c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),h.resetTextureCache(),l._width=i.width,l._height=i.height,l.isReady=!0}),null,null,!0,s):a(t,i,(function(t){var i=e.Tools.GetExponentOfTwo(t[0].width,h._caps.maxCubemapTextureSize),r=i;h._prepareWorkingCanvas(),h._workingCanvas.width=i,h._workingCanvas.height=r;var s=[c.TEXTURE_CUBE_MAP_POSITIVE_X,c.TEXTURE_CUBE_MAP_POSITIVE_Y,c.TEXTURE_CUBE_MAP_POSITIVE_Z,c.TEXTURE_CUBE_MAP_NEGATIVE_X,c.TEXTURE_CUBE_MAP_NEGATIVE_Y,c.TEXTURE_CUBE_MAP_NEGATIVE_Z];h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,l),c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,0);for(var a=0;a<s.length;a++)h._workingContext.drawImage(t[a],0,0,t[a].width,t[a].height,0,0,i,r),c.texImage2D(s[a],0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,h._workingCanvas);n||c.generateMipmap(c.TEXTURE_CUBE_MAP),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,n?c.LINEAR:c.LINEAR_MIPMAP_LINEAR),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),h._bindTextureDirectly(c.TEXTURE_CUBE_MAP,null),h.resetTextureCache(),l._width=i,l._height=r,l.isReady=!0,l.onLoadedCallbacks.forEach((function(e){e()})),o&&o()}),r,s),this._loadedTexturesCache.push(l),l},s.prototype.updateTextureSize=function(e,t,i){e._width=t,e._height=i,e._size=t*i,e._baseWidth=t,e._baseHeight=i},s.prototype.createRawCubeTexture=function(t,r,n,o,a,h,c,l){var u=this,d=this._gl,f=d.createTexture();r._addPendingData(f),f.isCube=!0,f.references=1,f.url=t;var p=this._getInternalFormat(o),_=d.UNSIGNED_BYTE;a===s.TEXTURETYPE_FLOAT&&(_=d.FLOAT);var m=n,g=m,v=e.Tools.IsExponentOfTwo(m)&&e.Tools.IsExponentOfTwo(g);f._width=m,f._height=g;var y=function(){r._removePendingData(f)},x=function(t){var n=c(t),o=[d.TEXTURE_CUBE_MAP_POSITIVE_X,d.TEXTURE_CUBE_MAP_POSITIVE_Y,d.TEXTURE_CUBE_MAP_POSITIVE_Z,d.TEXTURE_CUBE_MAP_NEGATIVE_X,d.TEXTURE_CUBE_MAP_NEGATIVE_Y,d.TEXTURE_CUBE_MAP_NEGATIVE_Z];if(m=f._width,g=f._height,v=e.Tools.IsExponentOfTwo(m)&&e.Tools.IsExponentOfTwo(g),u._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f),d.pixelStorei(d.UNPACK_FLIP_Y_WEBGL,0),!h&&v)if(l){var s=[];s.push(n[0]),s.push(n[3]),s.push(n[1]),s.push(n[4]),s.push(n[2]),s.push(n[5]);for(var a=l(s),y=0;y<a.length;y++){var x=m>>y;d.texImage2D(o[0],y,p,x,x,0,p,_,a[y][0]),d.texImage2D(o[1],y,p,x,x,0,p,_,a[y][2]),d.texImage2D(o[2],y,p,x,x,0,p,_,a[y][4]),d.texImage2D(o[3],y,p,x,x,0,p,_,a[y][1]),d.texImage2D(o[4],y,p,x,x,0,p,_,a[y][3]),d.texImage2D(o[5],y,p,x,x,0,p,_,a[y][5])}}else{for(var b=0;b<o.length;b++){var A=n[b];d.texImage2D(o[b],0,p,m,g,0,p,_,A)}if(d.generateMipmap(d.TEXTURE_CUBE_MAP),_===d.FLOAT&&p===d.RGB&&1282===d.getError()){e.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");for(var b=0;b<o.length;b++){for(var A=n[b],T=new Float32Array(m*g*4),E=0;E<m;E++)for(var P=0;P<g;P++){var S=3*(P*m+E),M=4*(P*m+E);T[M+0]=A[S+0],T[M+1]=A[S+1],T[M+2]=A[S+2],T[M+3]=1}d.texImage2D(o[b],0,d.RGBA,m,g,0,d.RGBA,_,T)}d.generateMipmap(d.TEXTURE_CUBE_MAP)}}else h=!0;(_!==d.FLOAT||u._caps.textureFloatLinearFiltering)&&(_!==i||u._caps.textureHalfFloatLinearFiltering)?(d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MAG_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MIN_FILTER,h?d.LINEAR:d.LINEAR_MIPMAP_LINEAR)):(d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_MIN_FILTER,d.NEAREST)),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_CUBE_MAP,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),u._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null),f.isReady=!0,u.resetTextureCache(),r._removePendingData(f)};return e.Tools.LoadFile(t,(function(e){x(e)}),y,r.database,!0),f},s.prototype._releaseTexture=function(e){var t=this._gl;e._framebuffer&&t.deleteFramebuffer(e._framebuffer),e._depthBuffer&&t.deleteRenderbuffer(e._depthBuffer),t.deleteTexture(e),this.unbindAllTextures();var i=this._loadedTexturesCache.indexOf(e);i!==-1&&this._loadedTexturesCache.splice(i,1)},s.prototype.setProgram=function(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)},s.prototype.bindSamplers=function(e){this.setProgram(e.getProgram());for(var t=e.getSamplers(),i=0;i<t.length;i++){var r=e.getUniform(t[i]);this._gl.uniform1i(r,i)}this._currentEffect=null},s.prototype.activateTexture=function(e){this._activeTexture!==e&&(this._gl.activeTexture(e),this._activeTexture=e)},s.prototype._bindTextureDirectly=function(e,t){this._activeTexturesCache[this._activeTexture]!==t&&(this._gl.bindTexture(e,t),this._activeTexturesCache[this._activeTexture]=t)},s.prototype._bindTexture=function(e,t){e<0||(this.activateTexture(this._gl["TEXTURE"+e]),this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},s.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t._textures.data[t._currentRenderTextureInd])},s.prototype.unbindAllTextures=function(){for(var e=0;e<this._caps.maxTexturesImageUnits;e++)this.activateTexture(this._gl["TEXTURE"+e]),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)},s.prototype.setTexture=function(e,t,i){e<0||(this._gl.uniform1i(t,e),this._setTexture(e,i))},s.prototype._setTexture=function(t,i){if(!i||!i.isReady())return void(null!=this._activeTexturesCache[t]&&(this.activateTexture(this._gl["TEXTURE"+t]),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)));var r=!1;if(i instanceof e.VideoTexture)this.activateTexture(this._gl["TEXTURE"+t]),r=!0,i.update();else if(i.delayLoadState===s.DELAYLOADSTATE_NOTLOADED)return void i.delayLoad();var n=i.getInternalTexture();if(this._activeTexturesCache[t]!==n)if(r||this.activateTexture(this._gl["TEXTURE"+t]),n.isCube){if(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,n),n._cachedCoordinatesMode!==i.coordinatesMode){n._cachedCoordinatesMode=i.coordinatesMode;var o=i.coordinatesMode!==e.Texture.CUBIC_MODE&&i.coordinatesMode!==e.Texture.SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,o),this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,o)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,i)}else{if(this._bindTextureDirectly(this._gl.TEXTURE_2D,n),n._cachedWrapU!==i.wrapU)switch(n._cachedWrapU=i.wrapU,i.wrapU){case e.Texture.WRAP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.REPEAT);break;case e.Texture.CLAMP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE);break;case e.Texture.MIRROR_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.MIRRORED_REPEAT)}if(n._cachedWrapV!==i.wrapV)switch(n._cachedWrapV=i.wrapV,i.wrapV){case e.Texture.WRAP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.REPEAT);break;case e.Texture.CLAMP_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);break;case e.Texture.MIRROR_ADDRESSMODE:this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.MIRRORED_REPEAT)}this._setAnisotropicLevel(this._gl.TEXTURE_2D,i)}},s.prototype.setTextureArray=function(e,t,i){if(!(e<0)){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var r=0;r<i.length;r++)this._textureUnits[r]=e+r;this._gl.uniform1iv(t,this._textureUnits);for(var n=0;n<i.length;n++)this._setTexture(e+n,i[n])}},s.prototype._setAnisotropicLevel=function(t,i){var r=this._caps.textureAnisotropicFilterExtension,n=i.anisotropicFilteringLevel;i.getInternalTexture().samplingMode===e.Texture.NEAREST_SAMPLINGMODE&&(n=1),r&&i._cachedAnisotropicFilteringLevel!==n&&(this._gl.texParameterf(t,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(n,this._caps.maxAnisotropy)),i._cachedAnisotropicFilteringLevel=n)},s.prototype.readPixels=function(e,t,i,r){var n=new Uint8Array(r*i*4);return this._gl.readPixels(e,t,i,r,this._gl.RGBA,this._gl.UNSIGNED_BYTE,n),n},s.prototype.addExternalData=function(e,t){return this._externalData.add(e,t)},s.prototype.getExternalData=function(e){return this._externalData.get(e)},s.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData.getOrAddWithFactory(e,t)},s.prototype.removeExternalData=function(e){return this._externalData.remove(e)},s.prototype.releaseInternalTexture=function(e){if(e&&(e.references--,0===e.references)){var t=this.getLoadedTexturesCache(),i=t.indexOf(e);i>-1&&t.splice(i,1),this._releaseTexture(e)}},s.prototype.unbindAllAttributes=function(){for(var e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1)},s.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop();this.scenes.length;)this.scenes[0].dispose();s.audioEngine.dispose();for(var e in this._compiledEffects)this._gl.deleteProgram(this._compiledEffects[e]._program);this.unbindAllAttributes(),this._gl=null,this.disableVR(),window.removeEventListener("blur",this._onBlur),window.removeEventListener("focus",this._onFocus),document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)},s.prototype.displayLoadingUI=function(){this._loadingScreen.displayLoadingUI()},s.prototype.hideLoadingUI=function(){this._loadingScreen.hideLoadingUI()},Object.defineProperty(s.prototype,"loadingScreen",{get:function(){return this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"loadingUIText",{set:function(e){this._loadingScreen.loadingUIText=e;
},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"loadingUIBackgroundColor",{set:function(e){this._loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),s.prototype.attachContextLostEvent=function(e){this._renderingCanvas.addEventListener("webglcontextlost",e,!1)},s.prototype.attachContextRestoredEvent=function(e){this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)},s.prototype.getVertexShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return this._gl.getShaderSource(t[0])},s.prototype.getFragmentShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return this._gl.getShaderSource(t[1])},s.prototype.getFps=function(){return this.fps},s.prototype.getDeltaTime=function(){return this.deltaTime},s.prototype._measureFps=function(){this.previousFramesDuration.push(e.Tools.Now);var t=this.previousFramesDuration.length;if(t>=2&&(this.deltaTime=this.previousFramesDuration[t-1]-this.previousFramesDuration[t-2]),t>=this.fpsRange){t>this.fpsRange&&(this.previousFramesDuration.splice(0,1),t=this.previousFramesDuration.length);for(var i=0,r=0;r<t-1;r++)i+=this.previousFramesDuration[r+1]-this.previousFramesDuration[r];this.fps=1e3/(i/(t-1))}},s.prototype._canRenderToFloatTexture=function(){return this._canRenderToTextureOfType(e.Engine.TEXTURETYPE_FLOAT,"OES_texture_float")},s.prototype._canRenderToHalfFloatTexture=function(){return this._canRenderToTextureOfType(e.Engine.TEXTURETYPE_HALF_FLOAT,"OES_texture_half_float")},s.prototype._canRenderToTextureOfType=function(t,i){var n=document.createElement("canvas");n.height=16,n.width=16;var o=n.getContext("webgl")||n.getContext("experimental-webgl"),s=o.getExtension(i);if(!s)return!1;var a="attribute vec4 a_position;\n                void main() {\n                    gl_Position = a_position;\n                }",h="precision mediump float;\n                uniform vec4 u_color;\n                uniform sampler2D u_texture;\n\n                void main() {\n                    gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n                }",c=this.createShaderProgram(a,h,null,o);o.useProgram(c);var l=o.getAttribLocation(c,"a_position"),u=o.getUniformLocation(c,"u_color"),d=o.createBuffer();o.bindBuffer(o.ARRAY_BUFFER,d),o.bufferData(o.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),o.STATIC_DRAW),o.enableVertexAttribArray(l),o.vertexAttribPointer(l,2,o.FLOAT,!1,0,0);var f=o.createTexture();o.bindTexture(o.TEXTURE_2D,f),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));var p=o.createTexture();o.bindTexture(o.TEXTURE_2D,p),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,r(o,t),null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST);var _=o.createFramebuffer();o.bindFramebuffer(o.FRAMEBUFFER,_),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,p,0);var m=function(){o.deleteProgram(c),o.disableVertexAttribArray(l),o.deleteBuffer(d),o.deleteFramebuffer(_),o.deleteTexture(f),o.deleteTexture(p)},g=o.checkFramebufferStatus(o.FRAMEBUFFER);if(g!==o.FRAMEBUFFER_COMPLETE)return e.Tools.Log("GL Support: can **NOT** render to "+t+" texture"),m(),!1;o.bindTexture(o.TEXTURE_2D,f),o.uniform4fv(u,[0,10,20,1]),o.drawArrays(o.TRIANGLES,0,6),o.bindTexture(o.TEXTURE_2D,p),o.bindFramebuffer(o.FRAMEBUFFER,null),o.clearColor(1,0,0,1),o.clear(o.COLOR_BUFFER_BIT),o.uniform4fv(u,[0,.1,.05,1]),o.drawArrays(o.TRIANGLES,0,6);var v=new Uint8Array(4);return o.readPixels(0,0,1,1,o.RGBA,o.UNSIGNED_BYTE,v),0!==v[0]||v[1]<248||v[2]<248||v[3]<254?(e.Tools.Log("GL Support: Was not able to actually render to "+t+" texture"),m(),!1):(m(),!0)},s.isSupported=function(){try{if(navigator.isCocoonJS)return!0;var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");return null!=t&&!!window.WebGLRenderingContext}catch(i){return!1}},s._ALPHA_DISABLE=0,s._ALPHA_ADD=1,s._ALPHA_COMBINE=2,s._ALPHA_SUBTRACT=3,s._ALPHA_MULTIPLY=4,s._ALPHA_MAXIMIZED=5,s._ALPHA_ONEONE=6,s._DELAYLOADSTATE_NONE=0,s._DELAYLOADSTATE_LOADED=1,s._DELAYLOADSTATE_LOADING=2,s._DELAYLOADSTATE_NOTLOADED=4,s._TEXTUREFORMAT_ALPHA=0,s._TEXTUREFORMAT_LUMINANCE=1,s._TEXTUREFORMAT_LUMINANCE_ALPHA=2,s._TEXTUREFORMAT_RGB=4,s._TEXTUREFORMAT_RGBA=5,s._TEXTURETYPE_UNSIGNED_INT=0,s._TEXTURETYPE_FLOAT=1,s._TEXTURETYPE_HALF_FLOAT=2,s._NEVER=512,s._ALWAYS=519,s._LESS=513,s._EQUAL=514,s._LEQUAL=515,s._GREATER=516,s._GEQUAL=518,s._NOTEQUAL=517,s._KEEP=7680,s._REPLACE=7681,s._INCR=7682,s._DECR=7683,s._INVERT=5386,s._INCR_WRAP=34055,s._DECR_WRAP=34056,s.CollisionsEpsilon=.001,s.CodeRepository="src/",s.ShadersRepository="src/Shaders/",s})();e.Engine=l})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.state="",this.metadata=null,this.doNotSerialize=!1,this.animations=new Array,this._ranges={},this._childrenFlag=-1,this._isEnabled=!0,this._isReady=!0,this._currentRenderId=-1,this._parentRenderId=-1,this.onDisposeObservable=new e.Observable,this.name=t,this.id=t,this._scene=i,this._initCache()}return Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){if(this._parentNode){var t=this._parentNode._children.indexOf(this);t!==-1&&this._parentNode._children.splice(t,1)}this._parentNode=e,this._parentNode&&(this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this))}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._scene.getEngine()},t.prototype.getWorldMatrix=function(){return e.Matrix.Identity()},t.prototype._initCache=function(){this._cache={},this._cache.parent=void 0},t.prototype.updateCache=function(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,this._updateCache())},t.prototype._updateCache=function(e){},t.prototype._isSynchronized=function(){return!0},t.prototype._markSyncedWithParent=function(){this._parentRenderId=this.parent._currentRenderId},t.prototype.isSynchronizedWithParent=function(){return!this.parent||this._parentRenderId===this.parent._currentRenderId&&this.parent.isSynchronized()},t.prototype.isSynchronized=function(e){var t=this.hasNewParent();return t=t||!this.isSynchronizedWithParent(),t=t||!this._isSynchronized(),e&&this.updateCache(!0),!t},t.prototype.hasNewParent=function(e){return this._cache.parent!==this.parent&&(e&&(this._cache.parent=this.parent),!0)},t.prototype.isReady=function(){return this._isReady},t.prototype.isEnabled=function(){return!!this._isEnabled&&(!this.parent||this.parent.isEnabled())},t.prototype.setEnabled=function(e){this._isEnabled=e},t.prototype.isDescendantOf=function(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))},t.prototype._getDescendants=function(e,t,i){if(void 0===t&&(t=!1),this._children)for(var r=0;r<this._children.length;r++){var n=this._children[r];i&&!i(n)||e.push(n),t||n._getDescendants(e,!1,i)}},t.prototype.getDescendants=function(e,t){var i=[];return this._getDescendants(i,e,t),i},t.prototype.getChildren=function(e){return this.getDescendants(!0,e)},t.prototype.getChildMeshes=function(t,i){var r=[];return this._getDescendants(r,t,(function(t){return(!i||i(t))&&t instanceof e.AbstractMesh})),r},t.prototype._setReady=function(e){if(e!==this._isReady){if(!e)return void(this._isReady=!1);this._isReady=!0,this.onReady&&this.onReady(this)}},t.prototype.getAnimationByName=function(e){for(var t=0;t<this.animations.length;t++){var i=this.animations[t];if(i.name===e)return i}return null},t.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=new e.AnimationRange(t,i,r);for(var n=0,o=this.animations.length;n<o;n++)this.animations[n]&&this.animations[n].createRange(t,i,r)}},t.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=void 0},t.prototype.getAnimationRange=function(e){return this._ranges[e]},t.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?void this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},t.prototype.serializeAnimationRanges=function(){var e=[];for(var t in this._ranges){var i={};i.name=t,i.from=this._ranges[t].from,i.to=this._ranges[t].to,e.push(i)}return e},t.prototype.dispose=function(){this.parent=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.ParseAnimationRanges=function(e,t,i){if(t.ranges)for(var r=0;r<t.ranges.length;r++){var n=t.ranges[r];e.createAnimationRange(n.name,n.from,n.to)}},__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"id",void 0),__decorate([e.serialize()],t.prototype,"uniqueId",void 0),__decorate([e.serialize()],t.prototype,"state",void 0),__decorate([e.serialize()],t.prototype,"metadata",void 0),t})();e.Node=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o,s,a){this._engine=e,this._canvas=i,this._currentScene=t,this._sceneLoadedCallback=r,this._progressCallback=n,this._additionnalRenderLoopLogicCallback=o,this._textureLoadingCallback=s,this._startingProcessingFilesCallback=a}return t.prototype.monitorElementForDragNDrop=function(e){var t=this;e&&(this._elementToMonitor=e,this._elementToMonitor.addEventListener("dragenter",(function(e){t.drag(e)}),!1),this._elementToMonitor.addEventListener("dragover",(function(e){t.drag(e)}),!1),this._elementToMonitor.addEventListener("drop",(function(e){t.drop(e)}),!1))},t.prototype.renderFunction=function(){if(this._additionnalRenderLoopLogicCallback&&this._additionnalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){var e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}},t.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},t.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},t.prototype.loadFiles=function(e){if(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(),e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&this._filesToLoad.length>0){for(var i=0;i<this._filesToLoad.length;i++)switch(this._filesToLoad[i].type){case"image/jpeg":case"image/png":case"image/bmp":t.FilesTextures[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i];break;case"image/targa":case"image/vnd.ms-dds":case"audio/wav":case"audio/x-wav":case"audio/mp3":case"audio/mpeg":case"audio/mpeg3":case"audio/x-mpeg-3":case"audio/ogg":t.FilesToLoad[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i];break;default:this._filesToLoad[i].name.indexOf(".mtl")!==-1?t.FilesToLoad[this._filesToLoad[i].name.toLowerCase()]=this._filesToLoad[i]:this._filesToLoad[i].name.indexOf(".babylon")===-1&&this._filesToLoad[i].name.indexOf(".stl")===-1&&this._filesToLoad[i].name.indexOf(".obj")===-1||this._filesToLoad[i].name.indexOf(".manifest")!==-1||this._filesToLoad[i].name.indexOf(".incremental")!==-1||this._filesToLoad[i].name.indexOf(".babylonmeshdata")!==-1||this._filesToLoad[i].name.indexOf(".babylongeometrydata")!==-1||this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata")!==-1||this._filesToLoad[i].name.indexOf(".binary.babylon")!==-1||(this._sceneFileToLoad=this._filesToLoad[i])}this.reload()}},t.prototype.reload=function(){var t=this,i=this;this._sceneFileToLoad?(this._currentScene&&(e.Tools.errorsCount>0&&(e.Tools.ClearLogCache(),e.Tools.Log("Babylon.js engine (v"+e.Engine.Version+") launched")),this._engine.stopRenderLoop(),this._currentScene.dispose()),e.SceneLoader.Load("file:",this._sceneFileToLoad,this._engine,(function(e){i._currentScene=e,i._currentScene.executeWhenReady((function(){i._currentScene.activeCamera&&0!==i._currentScene.lights.length||i._currentScene.createDefaultCameraOrLight(),i._currentScene.activeCamera.attachControl(i._canvas),i._sceneLoadedCallback&&i._sceneLoadedCallback(t._sceneFileToLoad,i._currentScene),i._engine.runRenderLoop((function(){i.renderFunction()}))}))}),(function(e){t._progressCallback&&t._progressCallback(e)}))):e.Tools.Error("Please provide a valid .babylon file.")},t.FilesTextures=new Array,t.FilesToLoad=new Array,t})();e.FilesInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}return e})();e.IntersectionInfo=t;var i=(function(){function t(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshId=0,this.pickedSprite=null}return t.prototype.getNormal=function(t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!0),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e.VertexBuffer.NormalKind))return null;var r,n=this.pickedMesh.getIndices();if(i){var o=this.pickedMesh.getVerticesData(e.VertexBuffer.NormalKind),s=e.Vector3.FromArray(o,3*n[3*this.faceId]),a=e.Vector3.FromArray(o,3*n[3*this.faceId+1]),h=e.Vector3.FromArray(o,3*n[3*this.faceId+2]);s=s.scale(this.bu),a=a.scale(this.bv),h=h.scale(1-this.bu-this.bv),r=new e.Vector3(s.x+a.x+h.x,s.y+a.y+h.y,s.z+a.z+h.z)}else{var c=this.pickedMesh.getVerticesData(e.VertexBuffer.PositionKind),l=e.Vector3.FromArray(c,3*n[3*this.faceId]),u=e.Vector3.FromArray(c,3*n[3*this.faceId+1]),d=e.Vector3.FromArray(c,3*n[3*this.faceId+2]),f=l.subtract(u),p=d.subtract(u);r=e.Vector3.Cross(f,p)}return t&&(r=e.Vector3.TransformNormal(r,this.pickedMesh.getWorldMatrix())),e.Vector3.Normalize(r)},t.prototype.getTextureCoordinates=function(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e.VertexBuffer.UVKind))return null;var t=this.pickedMesh.getIndices(),i=this.pickedMesh.getVerticesData(e.VertexBuffer.UVKind),r=e.Vector2.FromArray(i,2*t[3*this.faceId]),n=e.Vector2.FromArray(i,2*t[3*this.faceId+1]),o=e.Vector2.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(1-this.bu-this.bv),n=n.scale(this.bu),o=o.scale(this.bv),new e.Vector2(r.x+n.x+o.x,r.y+n.y+o.y)},t})();e.PickingInfo=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._tempRadiusVector=e.Vector3.Zero();var r=e.Vector3.Distance(t,i);this.center=e.Vector3.Lerp(t,i,.5),this.radius=.5*r,this.centerWorld=e.Vector3.Zero(),this._update(e.Matrix.Identity())}return t.prototype._update=function(t){e.Vector3.TransformCoordinatesToRef(this.center,t,this.centerWorld),e.Vector3.TransformNormalFromFloatsToRef(1,1,1,t,this._tempRadiusVector),this.radiusWorld=Math.max(Math.abs(this._tempRadiusVector.x),Math.abs(this._tempRadiusVector.y),Math.abs(this._tempRadiusVector.z))*this.radius},t.prototype.isInFrustum=function(e){for(var t=0;t<6;t++)if(e[t].dotCoordinate(this.centerWorld)<=-this.radiusWorld)return!1;return!0},t.prototype.intersectsPoint=function(t){var i=this.centerWorld.x-t.x,r=this.centerWorld.y-t.y,n=this.centerWorld.z-t.z,o=Math.sqrt(i*i+r*r+n*n);return!(Math.abs(this.radiusWorld-o)<e.Epsilon)},t.Intersects=function(e,t){var i=e.centerWorld.x-t.centerWorld.x,r=e.centerWorld.y-t.centerWorld.y,n=e.centerWorld.z-t.centerWorld.z,o=Math.sqrt(i*i+r*r+n*n);return!(e.radiusWorld+t.radiusWorld<o)},t})();e.BoundingSphere=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.minimum=t,this.maximum=i,this.vectors=new Array,this.vectorsWorld=new Array,this.vectors.push(this.minimum.clone()),this.vectors.push(this.maximum.clone()),this.vectors.push(this.minimum.clone()),this.vectors[2].x=this.maximum.x,this.vectors.push(this.minimum.clone()),this.vectors[3].y=this.maximum.y,this.vectors.push(this.minimum.clone()),this.vectors[4].z=this.maximum.z,this.vectors.push(this.maximum.clone()),this.vectors[5].z=this.minimum.z,this.vectors.push(this.maximum.clone()),this.vectors[6].x=this.minimum.x,this.vectors.push(this.maximum.clone()),this.vectors[7].y=this.minimum.y,this.center=this.maximum.add(this.minimum).scale(.5),this.extendSize=this.maximum.subtract(this.minimum).scale(.5),this.directions=[e.Vector3.Zero(),e.Vector3.Zero(),e.Vector3.Zero()];for(var r=0;r<this.vectors.length;r++)this.vectorsWorld[r]=e.Vector3.Zero();this.minimumWorld=e.Vector3.Zero(),this.maximumWorld=e.Vector3.Zero(),this._update(e.Matrix.Identity())}return t.prototype.getWorldMatrix=function(){return this._worldMatrix},t.prototype.setWorldMatrix=function(e){return this._worldMatrix.copyFrom(e),this},t.prototype._update=function(t){e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this.minimumWorld),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this.maximumWorld);for(var i=0;i<this.vectors.length;i++){var r=this.vectorsWorld[i];e.Vector3.TransformCoordinatesToRef(this.vectors[i],t,r),r.x<this.minimumWorld.x&&(this.minimumWorld.x=r.x),r.y<this.minimumWorld.y&&(this.minimumWorld.y=r.y),r.z<this.minimumWorld.z&&(this.minimumWorld.z=r.z),r.x>this.maximumWorld.x&&(this.maximumWorld.x=r.x),r.y>this.maximumWorld.y&&(this.maximumWorld.y=r.y),r.z>this.maximumWorld.z&&(this.maximumWorld.z=r.z)}this.maximumWorld.addToRef(this.minimumWorld,this.center),this.center.scaleInPlace(.5),e.Vector3.FromFloatArrayToRef(t.m,0,this.directions[0]),e.Vector3.FromFloatArrayToRef(t.m,4,this.directions[1]),e.Vector3.FromFloatArrayToRef(t.m,8,this.directions[2]),this._worldMatrix=t},t.prototype.isInFrustum=function(e){return t.IsInFrustum(this.vectorsWorld,e)},t.prototype.isCompletelyInFrustum=function(e){return t.IsCompletelyInFrustum(this.vectorsWorld,e)},t.prototype.intersectsPoint=function(t){var i=-e.Epsilon;return!(this.maximumWorld.x-t.x<i||i>t.x-this.minimumWorld.x)&&(!(this.maximumWorld.y-t.y<i||i>t.y-this.minimumWorld.y)&&!(this.maximumWorld.z-t.z<i||i>t.z-this.minimumWorld.z))},t.prototype.intersectsSphere=function(e){return t.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)},t.prototype.intersectsMinMax=function(e,t){return!(this.maximumWorld.x<e.x||this.minimumWorld.x>t.x)&&(!(this.maximumWorld.y<e.y||this.minimumWorld.y>t.y)&&!(this.maximumWorld.z<e.z||this.minimumWorld.z>t.z))},t.Intersects=function(e,t){return!(e.maximumWorld.x<t.minimumWorld.x||e.minimumWorld.x>t.maximumWorld.x)&&(!(e.maximumWorld.y<t.minimumWorld.y||e.minimumWorld.y>t.maximumWorld.y)&&!(e.maximumWorld.z<t.minimumWorld.z||e.minimumWorld.z>t.maximumWorld.z))},t.IntersectsSphere=function(t,i,r,n){var o=e.Vector3.Clamp(r,t,i),s=e.Vector3.DistanceSquared(r,o);return s<=n*n},t.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;i++)for(var r=0;r<8;r++)if(t[i].dotCoordinate(e[r])<0)return!1;return!0},t.IsInFrustum=function(e,t){for(var i=0;i<6;i++){for(var r=8,n=0;n<8&&t[i].dotCoordinate(e[n])<0;n++)--r;if(0===r)return!1}return!0},t})();e.BoundingBox=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(t,i){var r=e.Vector3.Dot(i.center,t),n=Math.abs(e.Vector3.Dot(i.directions[0],t))*i.extendSize.x,o=Math.abs(e.Vector3.Dot(i.directions[1],t))*i.extendSize.y,s=Math.abs(e.Vector3.Dot(i.directions[2],t))*i.extendSize.z,a=n+o+s;return{min:r-a,max:r+a}},i=function(e,t,i,r){return!(e>r||i>t)},r=function(e,r,n){var o=t(e,r),s=t(e,n);return i(o.min,o.max,s.min,s.max)},n=(function(){function t(t,i){this.minimum=t,this.maximum=i,this._isLocked=!1,this.boundingBox=new e.BoundingBox(t,i),this.boundingSphere=new e.BoundingSphere(t,i)}return Object.defineProperty(t.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),t.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},t.prototype.isInFrustum=function(e){return!!this.boundingSphere.isInFrustum(e)&&this.boundingBox.isInFrustum(e)},t.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},t.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},t.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},t.prototype.intersects=function(t,i){if(!this.boundingSphere.centerWorld||!t.boundingSphere.centerWorld)return!1;if(!e.BoundingSphere.Intersects(this.boundingSphere,t.boundingSphere))return!1;if(!e.BoundingBox.Intersects(this.boundingBox,t.boundingBox))return!1;if(!i)return!0;var n=this.boundingBox,o=t.boundingBox;return!!r(n.directions[0],n,o)&&(!!r(n.directions[1],n,o)&&(!!r(n.directions[2],n,o)&&(!!r(o.directions[0],n,o)&&(!!r(o.directions[1],n,o)&&(!!r(o.directions[2],n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[0],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[1]),n,o)&&(!!r(e.Vector3.Cross(n.directions[1],o.directions[2]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[0]),n,o)&&(!!r(e.Vector3.Cross(n.directions[2],o.directions[1]),n,o)&&!!r(e.Vector3.Cross(n.directions[2],o.directions[2]),n,o))))))))))))))},t})();e.BoundingInfo=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i){void 0===i&&(i=Number.MAX_VALUE),this.origin=e,this.direction=t,this.length=i,this._show=!1}return t.prototype.intersectsBoxMinMax=function(e,t){var i,r,n,o,s=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<e.x||this.origin.x>t.x)return!1}else if(i=1/this.direction.x,r=(e.x-this.origin.x)*i,n=(t.x-this.origin.x)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<e.y||this.origin.y>t.y)return!1}else if(i=1/this.direction.y,r=(e.y-this.origin.y)*i,n=(t.y-this.origin.y)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<e.z||this.origin.z>t.z)return!1}else if(i=1/this.direction.z,r=(e.z-this.origin.z)*i,n=(t.z-this.origin.z)*i,n===-(1/0)&&(n=1/0),r>n&&(o=r,r=n,n=o),s=Math.max(r,s),a=Math.min(n,a),s>a)return!1;return!0},t.prototype.intersectsBox=function(e){return this.intersectsBoxMinMax(e.minimum,e.maximum)},t.prototype.intersectsSphere=function(e){var t=e.center.x-this.origin.x,i=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=t*t+i*i+r*r,o=e.radius*e.radius;if(n<=o)return!0;var s=t*this.direction.x+i*this.direction.y+r*this.direction.z;if(s<0)return!1;var a=n-s*s;return a<=o},t.prototype.intersectsTriangle=function(t,i,r){this._edge1||(this._edge1=e.Vector3.Zero(),this._edge2=e.Vector3.Zero(),this._pvec=e.Vector3.Zero(),this._tvec=e.Vector3.Zero(),this._qvec=e.Vector3.Zero()),i.subtractToRef(t,this._edge1),r.subtractToRef(t,this._edge2),e.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var n=e.Vector3.Dot(this._edge1,this._pvec);if(0===n)return null;var o=1/n;this.origin.subtractToRef(t,this._tvec);var s=e.Vector3.Dot(this._tvec,this._pvec)*o;if(s<0||s>1)return null;e.Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Vector3.Dot(this.direction,this._qvec)*o;if(a<0||s+a>1)return null;var h=e.Vector3.Dot(this._edge2,this._qvec)*o;return h>this.length?null:new e.IntersectionInfo(s,a,h)},t.prototype.intersectsPlane=function(t){var i,r=e.Vector3.Dot(t.normal,this.direction);if(Math.abs(r)<9.99999997475243e-7)return null;var n=e.Vector3.Dot(t.normal,this.origin);return i=(-t.d-n)/r,i<0?i<-9.99999997475243e-7?null:0:i},t.prototype.intersectsMesh=function(i,r){var n=e.Tmp.Matrix[0];return i.getWorldMatrix().invertToRef(n),this._tmpRay?t.TransformToRef(this,n,this._tmpRay):this._tmpRay=t.Transform(this,n),i.intersects(this._tmpRay,r)},t.prototype.show=function(t,i){this._show||(this._renderFunction=this._render.bind(this),this._show=!0,this._scene=t,this._renderPoints=[this.origin,this.origin.add(this.direction.scale(this.length))],this._renderLine=e.Mesh.CreateLines("ray",this._renderPoints,t,!0),this._scene.registerBeforeRender(this._renderFunction)),i&&this._renderLine.color.copyFrom(i)},t.prototype.hide=function(){this._show&&(this._show=!1,this._scene.unregisterBeforeRender(this._renderFunction)),this._renderLine&&(this._renderLine.dispose(),this._renderLine=null,this._renderPoints=null)},t.prototype._render=function(){var t=this._renderPoints[1];t.copyFrom(this.direction),t.scaleInPlace(this.length),t.addInPlace(this.origin),e.Mesh.CreateLines("ray",this._renderPoints,this._scene,!0,this._renderLine)},t.prototype.intersectionSegment=function(i,r,n){var o,s,a,h,c=this.origin.add(this.direction.multiplyByFloats(t.rayl,t.rayl,t.rayl)),l=r.subtract(i),u=c.subtract(this.origin),d=i.subtract(this.origin),f=e.Vector3.Dot(l,l),p=e.Vector3.Dot(l,u),_=e.Vector3.Dot(u,u),m=e.Vector3.Dot(l,d),g=e.Vector3.Dot(u,d),v=f*_-p*p,y=v,x=v;v<t.smallnum?(s=0,y=1,h=g,x=_):(s=p*g-_*m,h=f*g-p*m,s<0?(s=0,h=g,x=_):s>y&&(s=y,h=g+p,x=_)),h<0?(h=0,-m<0?s=0:-m>f?s=y:(s=-m,y=f)):h>x&&(h=x,-m+p<0?s=0:-m+p>f?s=y:(s=-m+p,y=f)),o=Math.abs(s)<t.smallnum?0:s/y,a=Math.abs(h)<t.smallnum?0:h/x;var b=u.multiplyByFloats(a,a,a),A=d.add(l.multiplyByFloats(o,o,o)).subtract(b),T=a>0&&a<=this.length&&A.lengthSquared()<n*n;return T?b.length():-1},t.CreateNew=function(i,r,n,o,s,a,h){var c=e.Vector3.Unproject(new e.Vector3(i,r,0),n,o,s,a,h),l=e.Vector3.Unproject(new e.Vector3(i,r,1),n,o,s,a,h),u=l.subtract(c);return u.normalize(),new t(c,u)},t.CreateNewFromTo=function(i,r,n){void 0===n&&(n=e.Matrix.Identity());var o=r.subtract(i),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),t.Transform(new t(i,o,s),n)},t.Transform=function(i,r){var n=e.Vector3.TransformCoordinates(i.origin,r),o=e.Vector3.TransformNormal(i.direction,r);return o.normalize(),new t(n,o,i.length)},t.TransformToRef=function(t,i,r){e.Vector3.TransformCoordinatesToRef(t.origin,i,r.origin),e.Vector3.TransformNormalToRef(t.direction,i,r.direction),t.direction.normalize()},t.smallnum=1e-8,t.rayl=1e9,t})();e.Ray=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n){var o=this;t.call(this,r,n),this.onCollideObservable=new e.Observable,this.onCollisionPositionChangeObservable=new e.Observable,this.onAfterWorldMatrixUpdateObservable=new e.Observable,this.definedFacingForward=!0,this.position=new e.Vector3(0,0,0),this._rotation=new e.Vector3(0,0,0),this._scaling=new e.Vector3(1,1,1),this.billboardMode=i.BILLBOARDMODE_NONE,this.visibility=1,this.alphaIndex=Number.MAX_VALUE,this.infiniteDistance=!1,this.isVisible=!0,this.isPickable=!0,this.showBoundingBox=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.renderingGroupId=0,this.receiveShadows=!1,this.renderOutline=!1,this.outlineColor=e.Color3.Red(),this.outlineWidth=.02,this.renderOverlay=!1,this.overlayColor=e.Color3.Red(),this.overlayAlpha=.5,this.hasVertexAlpha=!1,this.useVertexColors=!0,this.applyFog=!0,this.computeBonesUsingShaders=!0,this.scalingDeterminant=1,this.numBoneInfluencers=4,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.layerMask=268435455,this.alwaysSelectAsActiveMesh=!1,this._checkCollisions=!1,this.ellipsoid=new e.Vector3(.5,1,.5),this.ellipsoidOffset=new e.Vector3(0,0,0),this._collider=new e.Collider,this._oldPositionForCollisions=new e.Vector3(0,0,0),this._diffPositionForCollisions=new e.Vector3(0,0,0),this._newPositionForCollisions=new e.Vector3(0,0,0),this.edgesWidth=1,this.edgesColor=new e.Color4(1,0,0,1),this._localWorld=e.Matrix.Zero(),this._worldMatrix=e.Matrix.Zero(),this._rotateYByPI=e.Matrix.RotationY(Math.PI),this._absolutePosition=e.Vector3.Zero(),this._collisionsTransformMatrix=e.Matrix.Zero(),this._collisionsScalingMatrix=e.Matrix.Zero(),this._isDirty=!1,this._pivotMatrix=e.Matrix.Identity(),this._isDisposed=!1,this._renderId=0,this._intersectionsInProgress=new Array,this._isWorldMatrixFrozen=!1,this._unIndexed=!1,this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),o.getScene().workerCollisions&&i.multiplyInPlace(o._collider.radius),i.subtractToRef(o._oldPositionForCollisions,o._diffPositionForCollisions),o._diffPositionForCollisions.length()>e.Engine.CollisionsEpsilon&&o.position.addInPlace(o._diffPositionForCollisions),r&&o.onCollideObservable.notifyObservers(r),o.onCollisionPositionChangeObservable.notifyObservers(o.position)},n.addMesh(this)}return __extends(i,t),Object.defineProperty(i,"BILLBOARDMODE_NONE",{get:function(){return i._BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_X",{get:function(){return i._BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Y",{get:function(){return i._BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_Z",{get:function(){return i._BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(i,"BILLBOARDMODE_ALL",{get:function(){return i._BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollide",{set:function(e){this._onCollideObserver&&this.onCollideObservable.remove(this._onCollideObserver),this._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onCollisionPositionChange",{set:function(e){this._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver),this._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._skeleton},set:function(e){this._skeleton&&this._skeleton.needInitialSkinMatrix&&this._skeleton._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._skeleton=e,this._skeleton||(this._bonesTransformMatrices=null)},enumerable:!0,configurable:!0}),i.prototype.toString=function(t){var i="Name: "+this.name+", isInstance: "+(this instanceof e.InstancedMesh?"YES":"NO");return i+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0),this._skeleton&&(i+=", skeleton: "+this._skeleton.name),t&&(i+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],i+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingFreezeWorldMatrix?"YES":"NO")),i},Object.defineProperty(i.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this.physicsImpostor&&this.physicsImpostor.forceUpdate()},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this.rotation.length()&&this.rotation.copyFromFloats(0,0,0)},enumerable:!0,configurable:!0}),i.prototype.updatePoseMatrix=function(e){this._poseMatrix.copyFrom(e)},i.prototype.getPoseMatrix=function(){return this._poseMatrix},i.prototype.disableEdgesRendering=function(){void 0!==this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=void 0)},i.prototype.enableEdgesRendering=function(t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.disableEdgesRendering(),this._edgesRenderer=new e.EdgesRenderer(this,t,i)},Object.defineProperty(i.prototype,"isBlocked",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.getLOD=function(e){
return this},i.prototype.getTotalVertices=function(){return 0},i.prototype.getIndices=function(){return null},i.prototype.getVerticesData=function(e){return null},i.prototype.isVerticesDataPresent=function(e){return!1},i.prototype.getBoundingInfo=function(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfo||this._updateBoundingInfo(),this._boundingInfo)},i.prototype.setBoundingInfo=function(e){this._boundingInfo=e},Object.defineProperty(i.prototype,"useBones",{get:function(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)},enumerable:!0,configurable:!0}),i.prototype._preActivate=function(){},i.prototype._preActivateForIntermediateRendering=function(e){},i.prototype._activate=function(e){this._renderId=e},i.prototype.getWorldMatrix=function(){return this._masterMesh?this._masterMesh.getWorldMatrix():(this._currentRenderId!==this.getScene().getRenderId()&&this.computeWorldMatrix(),this._worldMatrix)},Object.defineProperty(i.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),i.prototype.freezeWorldMatrix=function(){this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0},i.prototype.unfreezeWorldMatrix=function(){this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)},Object.defineProperty(i.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),i.prototype.rotate=function(t,r,n){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation=e.Vector3.Zero());var o;if(n&&n!==e.Space.LOCAL){if(this.parent){var s=this.parent.getWorldMatrix().clone();s.invert(),t=e.Vector3.TransformNormal(t,s)}o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else o=e.Quaternion.RotationAxisToRef(t,r,i._rotationAxisCache),this.rotationQuaternion.multiplyToRef(o,this.rotationQuaternion)},i.prototype.translate=function(t,i,r){var n=t.scale(i);if(r&&r!==e.Space.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var o=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(o)}},i.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},i.prototype.setAbsolutePosition=function(t){if(t){var i,r,n;if(void 0===t.x){if(arguments.length<3)return;i=arguments[0],r=arguments[1],n=arguments[2]}else i=t.x,r=t.y,n=t.z;if(this.parent){var o=this.parent.getWorldMatrix().clone();o.invert();var s=new e.Vector3(i,r,n);this.position=e.Vector3.TransformCoordinates(s,o)}else this.position.x=i,this.position.y=r,this.position.z=n}},i.prototype.movePOV=function(e,t,i){this.position.addInPlace(this.calcMovePOV(e,t,i))},i.prototype.calcMovePOV=function(t,i,r){var n=new e.Matrix,o=this.rotationQuaternion?this.rotationQuaternion:e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);o.toRotationMatrix(n);var s=e.Vector3.Zero(),a=this.definedFacingForward?-1:1;return e.Vector3.TransformCoordinatesFromFloatsToRef(t*a,i,r*a,n,s),s},i.prototype.rotatePOV=function(e,t,i){this.rotation.addInPlace(this.calcRotatePOV(e,t,i))},i.prototype.calcRotatePOV=function(t,i,r){var n=this.definedFacingForward?1:-1;return new e.Vector3(t*n,i,r*n)},i.prototype.setPivotMatrix=function(e){this._pivotMatrix=e,this._cache.pivotMatrixUpdated=!0},i.prototype.getPivotMatrix=function(){return this._pivotMatrix},i.prototype._isSynchronized=function(){return!this._isDirty&&(this.billboardMode===this._cache.billboardMode&&this.billboardMode===i.BILLBOARDMODE_NONE&&(!this._cache.pivotMatrixUpdated&&(!this.infiniteDistance&&(!!this._cache.position.equals(this.position)&&(!(this.rotationQuaternion&&!this._cache.rotationQuaternion.equals(this.rotationQuaternion))&&(!!this._cache.rotation.equals(this.rotation)&&!!this._cache.scaling.equals(this.scaling)))))))},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.localMatrixUpdated=!1,this._cache.position=e.Vector3.Zero(),this._cache.scaling=e.Vector3.Zero(),this._cache.rotation=e.Vector3.Zero(),this._cache.rotationQuaternion=new e.Quaternion(0,0,0,0),this._cache.billboardMode=-1},i.prototype.markAsDirty=function(e){"rotation"===e&&(this.rotationQuaternion=null),this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0},i.prototype._updateBoundingInfo=function(){this._boundingInfo=this._boundingInfo||new e.BoundingInfo(this.absolutePosition,this.absolutePosition),this._boundingInfo.update(this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)},i.prototype._updateSubMeshesBoundingInfo=function(e){if(this.subMeshes)for(var t=0;t<this.subMeshes.length;t++){var i=this.subMeshes[t];i.IsGlobal||i.updateBoundingInfo(e)}},i.prototype.computeWorldMatrix=function(t){if(this._isWorldMatrixFrozen)return this._worldMatrix;if(!t&&(this._currentRenderId===this.getScene().getRenderId()||this.isSynchronized(!0)))return this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix;if(this._cache.position.copyFrom(this.position),this._cache.scaling.copyFrom(this.scaling),this._cache.pivotMatrixUpdated=!1,this._cache.billboardMode=this.billboardMode,this._currentRenderId=this.getScene().getRenderId(),this._isDirty=!1,e.Matrix.ScalingToRef(this.scaling.x*this.scalingDeterminant,this.scaling.y*this.scalingDeterminant,this.scaling.z*this.scalingDeterminant,e.Tmp.Matrix[1]),this.rotationQuaternion){var r=this.rotation.length();r&&(this.rotationQuaternion.multiplyInPlace(e.Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)),this.rotation.copyFromFloats(0,0,0))}if(this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(e.Tmp.Matrix[0]),this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,e.Tmp.Matrix[0]),this._cache.rotation.copyFrom(this.rotation)),this.infiniteDistance&&!this.parent){var n=this.getScene().activeCamera;if(n){var o=n.getWorldMatrix(),s=new e.Vector3(o.m[12],o.m[13],o.m[14]);e.Matrix.TranslationToRef(this.position.x+s.x,this.position.y+s.y,this.position.z+s.z,e.Tmp.Matrix[2])}}else e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,e.Tmp.Matrix[2]);if(this._pivotMatrix.multiplyToRef(e.Tmp.Matrix[1],e.Tmp.Matrix[4]),e.Tmp.Matrix[4].multiplyToRef(e.Tmp.Matrix[0],e.Tmp.Matrix[5]),this.billboardMode!==i.BILLBOARDMODE_NONE&&this.getScene().activeCamera){e.Tmp.Vector3[0].copyFrom(this.position);var a=e.Tmp.Vector3[0];if(this.parent&&this.parent.getWorldMatrix){this._markSyncedWithParent();var h;this._meshToBoneReferal?(this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(),e.Tmp.Matrix[6]),h=e.Tmp.Matrix[6]):h=this.parent.getWorldMatrix(),e.Vector3.TransformNormalToRef(a,h,e.Tmp.Vector3[1]),a=e.Tmp.Vector3[1]}var c=this.getScene().activeCamera.globalPosition.clone();this.parent&&this.parent.position&&(a.addInPlace(this.parent.position),e.Matrix.TranslationToRef(a.x,a.y,a.z,e.Tmp.Matrix[2])),(this.billboardMode&i.BILLBOARDMODE_ALL)!==i.BILLBOARDMODE_ALL&&(this.billboardMode&i.BILLBOARDMODE_X&&(c.x=a.x+e.Epsilon),this.billboardMode&i.BILLBOARDMODE_Y&&(c.y=a.y+e.Epsilon),this.billboardMode&i.BILLBOARDMODE_Z&&(c.z=a.z+e.Epsilon)),e.Matrix.LookAtLHToRef(a,c,e.Vector3.Up(),e.Tmp.Matrix[3]),e.Tmp.Matrix[3].m[12]=e.Tmp.Matrix[3].m[13]=e.Tmp.Matrix[3].m[14]=0,e.Tmp.Matrix[3].invert(),e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[3],this._localWorld),this._rotateYByPI.multiplyToRef(this._localWorld,e.Tmp.Matrix[5])}return e.Tmp.Matrix[5].multiplyToRef(e.Tmp.Matrix[2],this._localWorld),this.parent&&this.parent.getWorldMatrix&&this.billboardMode===i.BILLBOARDMODE_NONE?(this._markSyncedWithParent(),this._meshToBoneReferal?(this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),e.Tmp.Matrix[6]),e.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localWorld.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix)):this._worldMatrix.copyFrom(this._localWorld),this._updateBoundingInfo(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=e.Matrix.Invert(this._worldMatrix)),this._worldMatrix},i.prototype.registerAfterWorldMatrixUpdate=function(e){this.onAfterWorldMatrixUpdateObservable.add(e)},i.prototype.unregisterAfterWorldMatrixUpdate=function(e){this.onAfterWorldMatrixUpdateObservable.removeCallback(e)},i.prototype.setPositionWithLocalVector=function(t){this.computeWorldMatrix(),this.position=e.Vector3.TransformNormal(t,this._localWorld)},i.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var t=this._localWorld.clone();return t.invert(),e.Vector3.TransformNormal(this.position,t)},i.prototype.locallyTranslate=function(t){this.computeWorldMatrix(!0),this.position=e.Vector3.TransformCoordinates(t,this._localWorld)},i.prototype.lookAt=function(t,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=e.Space.LOCAL);var a=i._lookAtVectorCache,h=s===e.Space.LOCAL?this.position:this.getAbsolutePosition();t.subtractToRef(h,a);var c=-Math.atan2(a.z,a.x)-Math.PI/2,l=Math.sqrt(a.x*a.x+a.z*a.z),u=Math.atan2(a.y,l);this.rotationQuaternion=this.rotationQuaternion||new e.Quaternion,e.Quaternion.RotationYawPitchRollToRef(c+r,u+n,o,this.rotationQuaternion)},i.prototype.attachToBone=function(e,t){this._meshToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1)},i.prototype.detachFromBone=function(){this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._meshToBoneReferal=null,this.parent=null},i.prototype.isInFrustum=function(e){return this._boundingInfo.isInFrustum(e)},i.prototype.isCompletelyInFrustum=function(e){return this._boundingInfo.isCompletelyInFrustum(e)},i.prototype.intersectsMesh=function(e,t){return!(!this._boundingInfo||!e._boundingInfo)&&this._boundingInfo.intersects(e._boundingInfo,t)},i.prototype.intersectsPoint=function(e){return!!this._boundingInfo&&this._boundingInfo.intersectsPoint(e)},i.prototype.setPhysicsState=function(t,i){return t.impostor&&(i=t,t=t.impostor),this.physicsImpostor=new e.PhysicsImpostor(this,t,i,this.getScene()),this.physicsImpostor.physicsBody},i.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},i.prototype.getPhysicsMass=function(){return this.physicsImpostor.getParam("mass")},i.prototype.getPhysicsFriction=function(){return this.physicsImpostor.getParam("friction")},i.prototype.getPhysicsRestitution=function(){return this.physicsImpostor.getParam("restitution")},i.prototype.getPositionInCameraSpace=function(t){return t||(t=this.getScene().activeCamera),e.Vector3.TransformCoordinates(this.absolutePosition,t.getViewMatrix())},i.prototype.getDistanceToCamera=function(e){return e||(e=this.getScene().activeCamera),this.absolutePosition.subtract(e.position).length()},i.prototype.applyImpulse=function(e,t){this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t)},i.prototype.setPhysicsLinkWith=function(t,i,r,n){this.physicsImpostor&&t.physicsImpostor&&this.physicsImpostor.createJoint(t.physicsImpostor,e.PhysicsJoint.HingeJoint,{mainPivot:i,connectedPivot:r,nativeParams:n})},i.prototype.updatePhysicsBodyPosition=function(){e.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()"),this.updatePhysicsBody()},i.prototype.updatePhysicsBody=function(){},Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return this._checkCollisions},set:function(e){this._checkCollisions=e,this.getScene().workerCollisions&&this.getScene().collisionCoordinator.onMeshUpdated(this)},enumerable:!0,configurable:!0}),i.prototype.moveWithCollisions=function(e){var t=this.getAbsolutePosition();t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPositionForCollisions),this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset),this._collider.radius=this.ellipsoid,this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions,e,this._collider,3,this,this._onCollisionPositionChange,this.uniqueId)},i.prototype.createOrUpdateSubmeshesOctree=function(t,i){void 0===t&&(t=64),void 0===i&&(i=2),this._submeshesOctree||(this._submeshesOctree=new e.Octree(e.Octree.CreationFuncForSubMeshes,t,i)),this.computeWorldMatrix(!0);var r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree},i.prototype._collideForSubMesh=function(t,i,r){if(this._generatePointsArray(),!t._lastColliderWorldVertices||!t._lastColliderTransformMatrix.equals(i)){t._lastColliderTransformMatrix=i.clone(),t._lastColliderWorldVertices=[],t._trianglePlanes=[];for(var n=t.verticesStart,o=t.verticesStart+t.verticesCount,s=n;s<o;s++)t._lastColliderWorldVertices.push(e.Vector3.TransformCoordinates(this._positions[s],i))}r._collide(t._trianglePlanes,t._lastColliderWorldVertices,this.getIndices(),t.indexStart,t.indexStart+t.indexCount,t.verticesStart,!!t.getMaterial()),r.collisionFound&&(r.collidedMesh=this)},i.prototype._processCollisionsForSubMeshes=function(e,t){var i,r;if(this._submeshesOctree&&this.useOctreeForCollisions){var n=e.velocityWorldLength+Math.max(e.radius.x,e.radius.y,e.radius.z),o=this._submeshesOctree.intersects(e.basePointWorld,n);r=o.length,i=o.data}else i=this.subMeshes,r=i.length;for(var s=0;s<r;s++){var a=i[s];r>1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}},i.prototype._checkCollision=function(t){this._boundingInfo._checkCollision(t)&&(e.Matrix.ScalingToRef(1/t.radius.x,1/t.radius.y,1/t.radius.z,this._collisionsScalingMatrix),this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix),this._processCollisionsForSubMeshes(t,this._collisionsTransformMatrix))},i.prototype._generatePointsArray=function(){return!1},i.prototype.intersects=function(t,i){var r=new e.PickingInfo;if(!(this.subMeshes&&this._boundingInfo&&t.intersectsSphere(this._boundingInfo.boundingSphere)&&t.intersectsBox(this._boundingInfo.boundingBox)))return r;if(!this._generatePointsArray())return r;var n,o,s=null;if(this._submeshesOctree&&this.useOctreeForPicking){var a=e.Ray.Transform(t,this.getWorldMatrix()),h=this._submeshesOctree.intersectsRay(a);o=h.length,n=h.data}else n=this.subMeshes,o=n.length;for(var c=0;c<o;c++){var l=n[c];if(!(o>1)||l.canIntersects(t)){var u=l.intersects(t,this._positions,this.getIndices(),i);if(u&&(i||!s||u.distance<s.distance)&&(s=u,s.subMeshId=c,i))break}}if(s){var d=this.getWorldMatrix(),f=e.Vector3.TransformCoordinates(t.origin,d),p=t.direction.clone();p=p.scale(s.distance);var _=e.Vector3.TransformNormal(p,d),m=f.add(_);return r.hit=!0,r.distance=e.Vector3.Distance(f,m),r.pickedPoint=m,r.pickedMesh=this,r.bu=s.bu,r.bv=s.bv,r.faceId=s.faceId,r.subMeshId=s.subMeshId,r}return r},i.prototype.clone=function(e,t,i){return null},i.prototype.releaseSubMeshes=function(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=new Array},i.prototype.dispose=function(e){var i,r=this;for(this.actionManager&&(this.actionManager.dispose(),this.actionManager=null),this.skeleton=null,this.getScene().stopAnimation(this),this.physicsImpostor&&this.physicsImpostor.dispose(),i=0;i<this._intersectionsInProgress.length;i++){var n=this._intersectionsInProgress[i],o=n._intersectionsInProgress.indexOf(this);n._intersectionsInProgress.splice(o,1)}this._intersectionsInProgress=[];var s=this.getScene().lights;if(s.forEach((function(e){var t=e.includedOnlyMeshes.indexOf(r);t!==-1&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(r),t!==-1&&e.excludedMeshes.splice(t,1);var i=e.getShadowGenerator();i&&(t=i.getShadowMap().renderList.indexOf(r),t!==-1&&i.getShadowMap().renderList.splice(t,1))})),this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this.releaseSubMeshes(),this.getScene().getEngine().unbindAllAttributes(),this.getScene().removeMesh(this),e){var a=this.getChildMeshes(!0);for(i=0;i<a.length;i++){var h=a[i];h.parent=null,h.computeWorldMatrix(!0)}}else{for(i=0;i<this.getScene().particleSystems.length;i++)this.getScene().particleSystems[i].emitter===this&&(this.getScene().particleSystems[i].dispose(),i--);var c=this.getDescendants(!0);for(i=0;i<c.length;i++)c[i].dispose()}this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this._isDisposed=!0,t.prototype.dispose.call(this)},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i)},i.prototype.setPivotPoint=function(t,i){void 0===i&&(i=e.Space.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var r=this.getWorldMatrix();if(i==e.Space.WORLD){var n=e.Tmp.Matrix[0];r.invertToRef(n),t=e.Vector3.TransformCoordinates(t,n)}e.Vector3.TransformCoordinatesToRef(t,r,this.position),this._pivotMatrix.m[12]=-t.x,this._pivotMatrix.m[13]=-t.y,this._pivotMatrix.m[14]=-t.z,this._cache.pivotMatrixUpdated=!0},i.prototype.getPivotPoint=function(){var t=e.Vector3.Zero();return this.getPivotPointToRef(t),t},i.prototype.getPivotPointToRef=function(e){e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14]},i.prototype.getAbsolutePivotPoint=function(){var t=e.Vector3.Zero();return this.getAbsolutePivotPointToRef(t),t},i.prototype.getAbsolutePivotPointToRef=function(t){t.x=this._pivotMatrix.m[12],t.y=this._pivotMatrix.m[13],t.z=this._pivotMatrix.m[14],this.getPivotPointToRef(t),e.Vector3.TransformCoordinatesToRef(t,this.getWorldMatrix(),t)},i._BILLBOARDMODE_NONE=0,i._BILLBOARDMODE_X=1,i._BILLBOARDMODE_Y=2,i._BILLBOARDMODE_Z=4,i._BILLBOARDMODE_ALL=7,i._rotationAxisCache=new e.Quaternion,i._lookAtVectorCache=new e.Vector3(0,0,0),i})(e.Node);e.AbstractMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,i,r),this.diffuse=new e.Color3(1,1,1),this.specular=new e.Color3(1,1,1),this.intensity=1,this.range=Number.MAX_VALUE,this.includeOnlyWithLayerMask=0,this.includedOnlyMeshes=new Array,this.excludedMeshes=new Array,this.excludeWithLayerMask=0,this.lightmapMode=0,this.radius=1e-5,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,r.addLight(this)}return __extends(i,t),Object.defineProperty(i,"LIGHTMAP_DEFAULT",{get:function(){return i._LIGHTMAP_DEFAULT},enumerable:!0,configurable:!0}),Object.defineProperty(i,"LIGHTMAP_SPECULAR",{get:function(){return i._LIGHTMAP_SPECULAR},enumerable:!0,configurable:!0}),Object.defineProperty(i,"LIGHTMAP_SHADOWSONLY",{get:function(){return i._LIGHTMAP_SHADOWSONLY},enumerable:!0,configurable:!0}),i.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},i.prototype.getShadowGenerator=function(){return this._shadowGenerator},i.prototype.getAbsolutePosition=function(){return e.Vector3.Zero()},i.prototype.transferToEffect=function(e,t,i){},i.prototype._getWorldMatrix=function(){return e.Matrix.Identity()},i.prototype.canAffectMesh=function(e){return!e||!(this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(e)===-1)&&(!(this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1)&&((0===this.includeOnlyWithLayerMask||0!==(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},i.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId();var t=this._getWorldMatrix();return this.parent&&this.parent.getWorldMatrix?(this._parentedWorldMatrix||(this._parentedWorldMatrix=e.Matrix.Identity()),t.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix),this._markSyncedWithParent(),this._parentedWorldMatrix):t},i.prototype.dispose=function(){this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this),this.getScene().removeLight(this),t.prototype.dispose.call(this)},i.prototype.getTypeID=function(){return 0},i.prototype.clone=function(t){return e.SerializationHelper.Clone(i.GetConstructorFromName(this.getTypeID(),t,this.getScene()),this)},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.type=this.getTypeID(),this.parent&&(t.parentId=this.parent.id),this.excludedMeshes.length>0&&(t.excludedMeshesIds=[],this.excludedMeshes.forEach((function(e){t.excludedMeshesIds.push(e.id)}))),this.includedOnlyMeshes.length>0&&(t.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(e){t.includedOnlyMeshesIds.push(e.id)}))),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.GetConstructorFromName=function(t,i,r){switch(t){case 0:return function(){return new e.PointLight(i,e.Vector3.Zero(),r)};case 1:return function(){return new e.DirectionalLight(i,e.Vector3.Zero(),r)};case 2:return function(){return new e.SpotLight(i,e.Vector3.Zero(),e.Vector3.Zero(),0,0,r)};case 3:return function(){return new e.HemisphericLight(i,e.Vector3.Zero(),r)}}},i.Parse=function(t,r){var n=e.SerializationHelper.Parse(i.GetConstructorFromName(t.type,t.name,r),t,r);if(t.excludedMeshesIds&&(n._excludedMeshesIds=t.excludedMeshesIds),t.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=t.includedOnlyMeshesIds),t.parentId&&(n._waitingParentId=t.parentId),t.animations){for(var o=0;o<t.animations.length;o++){var s=t.animations[o];n.animations.push(e.Animation.Parse(s))}e.Node.ParseAnimationRanges(n,t,r)}return t.autoAnimate&&r.beginAnimation(n,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),n},i._LIGHTMAP_DEFAULT=0,i._LIGHTMAP_SPECULAR=1,i._LIGHTMAP_SHADOWSONLY=2,__decorate([e.serializeAsColor3()],i.prototype,"diffuse",void 0),__decorate([e.serializeAsColor3()],i.prototype,"specular",void 0),__decorate([e.serialize()],i.prototype,"intensity",void 0),__decorate([e.serialize()],i.prototype,"range",void 0),__decorate([e.serialize()],i.prototype,"includeOnlyWithLayerMask",void 0),__decorate([e.serialize()],i.prototype,"excludeWithLayerMask",void 0),__decorate([e.serialize()],i.prototype,"lightmapMode",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),i})(e.Node);e.Light=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r){t.call(this,e,r),this.position=i}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(e,t){return this.parent&&this.parent.getWorldMatrix?(this.computeTransformedPosition(),void e.setFloat4(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0)):void e.setFloat4(t,this.position.x,this.position.y,this.position.z,0)},i.prototype.needCube=function(){return!0},i.prototype.supportsVSM=function(){return!1},i.prototype.needRefreshPerFrame=function(){return!1},i.prototype.getShadowDirection=function(t){switch(t){case 0:return new e.Vector3(1,0,0);case 1:return new e.Vector3((-1),0,0);case 2:return new e.Vector3(0,(-1),0);case 3:return new e.Vector3(0,1,0);case 4:return new e.Vector3(0,0,1);case 5:return new e.Vector3(0,0,(-1))}return e.Vector3.Zero()},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;e.Matrix.PerspectiveFovLHToRef(Math.PI/2,1,n.minZ,n.maxZ,t)},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 0},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),i})(e.Light);e.PointLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){t.call(this,e,s),this.position=i,this.direction=r,this.angle=n,this.exponent=o}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;e.Matrix.PerspectiveFovLHToRef(this.angle,1,n.minZ,n.maxZ,t)},i.prototype.needCube=function(){return!1},i.prototype.supportsVSM=function(){return!0},i.prototype.needRefreshPerFrame=function(){return!1},i.prototype.getShadowDirection=function(e){return this.direction},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(t,i,r){var n;this.parent&&this.parent.getWorldMatrix?(this._transformedDirection||(this._transformedDirection=e.Vector3.Zero()),this.computeTransformedPosition(),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection),t.setFloat4(i,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent),n=e.Vector3.Normalize(this._transformedDirection)):(t.setFloat4(i,this.position.x,this.position.y,this.position.z,this.exponent),n=e.Vector3.Normalize(this.direction)),t.setFloat4(r,n.x,n.y,n.z,Math.cos(.5*this.angle))},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 2},i.prototype.getRotation=function(){this.direction.normalize();var t=e.Vector3.Cross(this.direction,e.Axis.Y),i=e.Vector3.Cross(t,this.direction);return e.Vector3.RotationFromAxis(t,i,this.direction)},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),__decorate([e.serialize()],i.prototype,"angle",void 0),__decorate([e.serialize()],i.prototype,"exponent",void 0),i})(e.Light);e.SpotLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,n),this.groundColor=new e.Color3(0,0,0),this.direction=r}return __extends(i,t),i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(e.Vector3.Zero())),this.direction},i.prototype.getShadowGenerator=function(){return null},i.prototype.transferToEffect=function(t,i,r){var n=e.Vector3.Normalize(this.direction);t.setFloat4(i,n.x,n.y,n.z,0),t.setColor3(r,this.groundColor.scale(this.intensity))},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._worldMatrix},i.prototype.getTypeID=function(){return 3},__decorate([e.serializeAsColor3()],i.prototype,"groundColor",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),i})(e.Light);e.HemisphericLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r){t.call(this,e,r),this.shadowOrthoScale=.5,this.autoUpdateExtends=!0,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=i.scale(-1),this.direction=i}return __extends(i,t),i.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},i.prototype.setDirectionToTarget=function(t){return this.direction=e.Vector3.Normalize(t.subtract(this.position)),this.direction},i.prototype.setShadowProjectionMatrix=function(t,i,r){var n=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var o=e.Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;s<r.length;s++){var a=r[s];if(a){var h=a.getBoundingInfo();if(h)for(var c=h.boundingBox,l=0;l<c.vectorsWorld.length;l++)e.Vector3.TransformCoordinatesToRef(c.vectorsWorld[l],i,o),o.x<this._orthoLeft&&(this._orthoLeft=o.x),o.y<this._orthoBottom&&(this._orthoBottom=o.y),o.x>this._orthoRight&&(this._orthoRight=o.x),o.y>this._orthoTop&&(this._orthoTop=o.y)}}}var u=this._orthoRight-this._orthoLeft,d=this._orthoTop-this._orthoBottom;e.Matrix.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-d*this.shadowOrthoScale,this._orthoTop+d*this.shadowOrthoScale,-n.maxZ,n.maxZ,t)},i.prototype.supportsVSM=function(){return!0},i.prototype.needRefreshPerFrame=function(){return!0},i.prototype.needCube=function(){return!1},i.prototype.getShadowDirection=function(e){return this.direction},i.prototype.computeTransformedPosition=function(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=e.Vector3.Zero()),e.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),!0)},i.prototype.transferToEffect=function(t,i){return this.parent&&this.parent.getWorldMatrix?(this._transformedDirection||(this._transformedDirection=e.Vector3.Zero()),e.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection),void t.setFloat4(i,this._transformedDirection.x,this._transformedDirection.y,this._transformedDirection.z,1)):void t.setFloat4(i,this.direction.x,this.direction.y,this.direction.z,1)},i.prototype._getWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),e.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this._worldMatrix},i.prototype.getTypeID=function(){return 1},__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"direction",void 0),__decorate([e.serialize()],i.prototype,"shadowOrthoScale",void 0),__decorate([e.serialize()],i.prototype,"autoUpdateExtends",void 0),i})(e.Light);e.DirectionalLight=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(i,r){var n=this;this._filter=t.FILTER_NONE,this.blurScale=2,this._blurBoxOffset=0,this._bias=5e-5,this._lightDirection=e.Vector3.Zero(),this.forceBackFacesOnly=!1,this._darkness=0,this._transparencyShadow=!1,this._viewMatrix=e.Matrix.Zero(),this._projectionMatrix=e.Matrix.Zero(),this._transformMatrix=e.Matrix.Zero(),this._worldViewProjection=e.Matrix.Zero(),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._useFullFloat=!0,this._light=r,this._scene=r.getScene(),this._mapSize=i,r._shadowGenerator=this;var o,s=this._scene.getEngine().getCaps();s.textureFloat&&s.textureFloatLinearFiltering&&s.textureFloatRender?(this._useFullFloat=!0,o=e.Engine.TEXTURETYPE_FLOAT):(this._useFullFloat=!1,o=e.Engine.TEXTURETYPE_UNSIGNED_INT),this._shadowMap=new e.RenderTargetTexture(r.name+"_shadowMap",i,this._scene,(!1),(!0),o,r.needCube()),
this._shadowMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.NEAREST_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.onBeforeRenderObservable.add((function(e){n._currentFaceIndex=e})),this._shadowMap.onAfterUnbindObservable.add((function(){n.useBlurVarianceShadowMap&&(n._shadowMap2||(n._shadowMap2=new e.RenderTargetTexture(r.name+"_shadowMap",i,n._scene,(!1),(!0),o),n._shadowMap2.wrapU=e.Texture.CLAMP_ADDRESSMODE,n._shadowMap2.wrapV=e.Texture.CLAMP_ADDRESSMODE,n._shadowMap2.updateSamplingMode(e.Texture.TRILINEAR_SAMPLINGMODE),n._downSamplePostprocess=new e.PassPostProcess("downScale",1/n.blurScale,null,e.Texture.BILINEAR_SAMPLINGMODE,n._scene.getEngine()),n._downSamplePostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",n._shadowMap)})),n.blurBoxOffset=1),n._scene.postProcessManager.directRender([n._downSamplePostprocess,n._boxBlurPostprocess],n._shadowMap2.getInternalTexture()))}));var a=function(t){var i=t.getRenderingMesh(),r=n._scene,o=r.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id]&&void 0!==s.visibleInstances[t._id];if(n.isReady(t,a)){o.enableEffect(n._effect),i._bind(t,n._effect,e.Material.TriangleFillMode);var h=t.getMaterial();if(n._effect.setMatrix("viewProjection",n.getTransformMatrix()),n._effect.setVector3("lightPosition",n.getLight().position),n.getLight().needCube()&&n._effect.setFloat2("depthValues",r.activeCamera.minZ,r.activeCamera.maxZ),h&&h.needAlphaTesting()){var c=h.getAlphaTestTexture();n._effect.setTexture("diffuseSampler",c),n._effect.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&n._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),n.forceBackFacesOnly&&o.setState(!0,0,!1,!0),i._processRendering(t,n._effect,e.Material.TriangleFillMode,s,a,(function(e,t){return n._effect.setMatrix("world",t)})),n.forceBackFacesOnly&&o.setState(!0,0,!1,!1)}else n._shadowMap.resetRefreshCounter()}};this._shadowMap.customRenderFunction=function(e,t,i){var r;for(r=0;r<e.length;r++)a(e.data[r]);for(r=0;r<t.length;r++)a(t.data[r]);if(n._transparencyShadow)for(r=0;r<i.length;r++)a(i.data[r])},this._shadowMap.onClearObservable.add((function(t){n.useBlurVarianceShadowMap||n.useVarianceShadowMap?t.clear(new e.Color4(0,0,0,0),!0,!0,!0):t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}))}return Object.defineProperty(t,"FILTER_NONE",{get:function(){return t._FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_VARIANCESHADOWMAP",{get:function(){return t._FILTER_VARIANCESHADOWMAP},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_POISSONSAMPLING",{get:function(){return t._FILTER_POISSONSAMPLING},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FILTER_BLURVARIANCESHADOWMAP",{get:function(){return t._FILTER_BLURVARIANCESHADOWMAP},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bias",{get:function(){return this._bias},set:function(e){this._bias=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(t){var i=this;this._blurBoxOffset!==t&&(this._blurBoxOffset=t,this._boxBlurPostprocess&&this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=new e.PostProcess("DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1/this.blurScale,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define OFFSET "+t),this._boxBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",i._mapSize/i.blurScale,i._mapSize/i.blurScale)})))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"filter",{get:function(){return this._filter},set:function(t){this._filter!==t&&(this._filter=t,this.useVarianceShadowMap||this.useBlurVarianceShadowMap||this.usePoissonSampling?(this._shadowMap.anisotropicFilteringLevel=16,this._shadowMap.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE)):(this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(e.Texture.NEAREST_SAMPLINGMODE)))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useVarianceShadowMap",{get:function(){return this.filter===t.FILTER_VARIANCESHADOWMAP&&this._light.supportsVSM()},set:function(e){this.filter=e?t.FILTER_VARIANCESHADOWMAP:t.FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"usePoissonSampling",{get:function(){return this.filter===t.FILTER_POISSONSAMPLING||!this._light.supportsVSM()&&(this.filter===t.FILTER_VARIANCESHADOWMAP||this.filter===t.FILTER_BLURVARIANCESHADOWMAP)},set:function(e){this.filter=e?t.FILTER_POISSONSAMPLING:t.FILTER_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBlurVarianceShadowMap",{get:function(){return this.filter===t.FILTER_BLURVARIANCESHADOWMAP&&this._light.supportsVSM()},set:function(e){this.filter=e?t.FILTER_BLURVARIANCESHADOWMAP:t.FILTER_NONE},enumerable:!0,configurable:!0}),t.prototype.isReady=function(t,i){var r=[];this._useFullFloat&&r.push("#define FULLFLOAT"),(this.useVarianceShadowMap||this.useBlurVarianceShadowMap)&&r.push("#define VSM"),this.getLight().needCube()&&r.push("#define CUBEMAP");var n=[e.VertexBuffer.PositionKind],o=t.getMesh(),s=t.getMaterial();if(s&&s.needAlphaTesting()&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind))){var a=s.getAlphaTestTexture();1===a.coordinatesIndex&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2"))}o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var h=r.join("\n");return this._cachedDefines!==h&&(this._cachedDefines=h,this._effect=this._scene.getEngine().createEffect("shadowMap",n,["world","mBones","viewProjection","diffuseMatrix","lightPosition","depthValues"],["diffuseSampler"],h)),this._effect.isReady()},t.prototype.getShadowMap=function(){return this._shadowMap},t.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},t.prototype.getLight=function(){return this._light},t.prototype.getTransformMatrix=function(){var t=this._scene;if(this._currentRenderID===t.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderID=t.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var i=this._light.position;return e.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(e.Vector3.Dot(this._lightDirection,e.Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.computeTransformedPosition()&&(i=this._light.transformedPosition),!this._light.needRefreshPerFrame()&&this._cachedPosition&&this._cachedDirection&&i.equals(this._cachedPosition)&&this._lightDirection.equals(this._cachedDirection)||(this._cachedPosition=i.clone(),this._cachedDirection=this._lightDirection.clone(),e.Matrix.LookAtLHToRef(i,i.add(this._lightDirection),e.Vector3.Up(),this._viewMatrix),this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,this.getShadowMap().renderList),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)),this._transformMatrix},t.prototype.getDarkness=function(){return this._darkness},t.prototype.setDarkness=function(e){e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e},t.prototype.setTransparencyShadow=function(e){this._transparencyShadow=e},t.prototype._packHalf=function(t){var i=255*t,r=i-Math.floor(i);return new e.Vector2(t-r/255,r)},t.prototype.dispose=function(){this._shadowMap.dispose(),this._shadowMap2&&this._shadowMap2.dispose(),this._downSamplePostprocess&&this._downSamplePostprocess.dispose(),this._boxBlurPostprocess&&this._boxBlurPostprocess.dispose()},t.prototype.serialize=function(){var e={};e.lightId=this._light.id,e.mapSize=this.getShadowMap().getRenderSize(),e.useVarianceShadowMap=this.useVarianceShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.forceBackFacesOnly=this.forceBackFacesOnly,e.renderList=[];for(var t=0;t<this.getShadowMap().renderList.length;t++){var i=this.getShadowMap().renderList[t];e.renderList.push(i.id)}return e},t.Parse=function(e,i){for(var r=i.getLightByID(e.lightId),n=new t(e.mapSize,r),o=0;o<e.renderList.length;o++){var s=i.getMeshesByID(e.renderList[o]);s.forEach((function(e){n.getShadowMap().renderList.push(e)}))}return e.usePoissonSampling?n.usePoissonSampling=!0:e.useVarianceShadowMap?n.useVarianceShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurVarianceShadowMap=!0,e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset)),void 0!==e.bias&&(n.bias=e.bias),n.forceBackFacesOnly=e.forceBackFacesOnly,n},t._FILTER_NONE=0,t._FILTER_VARIANCESHADOWMAP=1,t._FILTER_POISSONSAMPLING=2,t._FILTER_BLURVARIANCESHADOWMAP=3,t})();e.ShadowGenerator=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t,i,r){return!(e.x>i.x+r)&&(!(i.x-r>t.x)&&(!(e.y>i.y+r)&&(!(i.y-r>t.y)&&(!(e.z>i.z+r)&&!(i.z-r>t.z)))))},i=(function(){var e={root:0,found:!1};return function(t,i,r,n){e.root=0,e.found=!1;var o=i*i-4*t*r;if(o<0)return e;var s=Math.sqrt(o),a=(-i-s)/(2*t),h=(-i+s)/(2*t);if(a>h){var c=h;h=a,a=c}return a>0&&a<n?(e.root=a,e.found=!0,e):h>0&&h<n?(e.root=h,e.found=!0,e):e}})(),r=(function(){function r(){this.radius=new e.Vector3(1,1,1),this.retry=0,this.basePointWorld=e.Vector3.Zero(),this.velocityWorld=e.Vector3.Zero(),this.normalizedVelocity=e.Vector3.Zero(),this._collisionPoint=e.Vector3.Zero(),this._planeIntersectionPoint=e.Vector3.Zero(),this._tempVector=e.Vector3.Zero(),this._tempVector2=e.Vector3.Zero(),this._tempVector3=e.Vector3.Zero(),this._tempVector4=e.Vector3.Zero(),this._edge=e.Vector3.Zero(),this._baseToVertex=e.Vector3.Zero(),this._destinationPoint=e.Vector3.Zero(),this._slidePlaneNormal=e.Vector3.Zero(),this._displacementVector=e.Vector3.Zero()}return r.prototype._initialize=function(t,i,r){this.velocity=i,e.Vector3.NormalizeToRef(i,this.normalizedVelocity),this.basePoint=t,t.multiplyToRef(this.radius,this.basePointWorld),i.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=r,this.collisionFound=!1},r.prototype._checkPointInTriangle=function(t,i,r,n,o){i.subtractToRef(t,this._tempVector),r.subtractToRef(t,this._tempVector2),e.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var s=e.Vector3.Dot(this._tempVector4,o);return!(s<0)&&(n.subtractToRef(t,this._tempVector3),e.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),s=e.Vector3.Dot(this._tempVector4,o),!(s<0)&&(e.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),s=e.Vector3.Dot(this._tempVector4,o),s>=0))},r.prototype._canDoCollision=function(i,r,n,o){var s=e.Vector3.Distance(this.basePointWorld,i),a=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(s>this.velocityWorldLength+a+r)&&!!t(n,o,this.basePointWorld,this.velocityWorldLength+a)},r.prototype._testTriangle=function(t,r,n,o,s,a){var h,c=!1;r||(r=[]),r[t]||(r[t]=new e.Plane(0,0,0,0),r[t].copyFromPoints(n,o,s));var l=r[t];if(a||l.isFrontFacingTo(this.normalizedVelocity,0)){var u=l.signedDistanceTo(this.basePoint),d=e.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(u)>=1)return;c=!0,h=0}else{h=(-1-u)/d;var f=(1-u)/d;if(h>f){var p=f;f=h,h=p}if(h>1||f<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var _=!1,m=1;if(c||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,n,o,s,l.normal)&&(_=!0,m=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!_){var g=this.velocity.lengthSquared(),v=g;this.basePoint.subtractToRef(n,this._tempVector);var y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,m);b.found&&(m=b.root,_=!0,this._collisionPoint.copyFrom(n)),this.basePoint.subtractToRef(o,this._tempVector),y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,m),b.found&&(m=b.root,_=!0,this._collisionPoint.copyFrom(o)),this.basePoint.subtractToRef(s,this._tempVector),y=2*e.Vector3.Dot(this.velocity,this._tempVector),x=this._tempVector.lengthSquared()-1,b=i(v,y,x,m),b.found&&(m=b.root,_=!0,this._collisionPoint.copyFrom(s)),o.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex);var A=this._edge.lengthSquared(),T=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex);if(v=A*-g+T*T,y=A*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*T*E,x=A*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,m),b.found){var P=(T*b.root-E)/A;P>=0&&P<=1&&(m=b.root,_=!0,this._edge.scaleInPlace(P),n.addToRef(this._edge,this._collisionPoint))}s.subtractToRef(o,this._edge),o.subtractToRef(this.basePoint,this._baseToVertex),A=this._edge.lengthSquared(),T=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex),v=A*-g+T*T,y=A*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*T*E,x=A*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,m),b.found&&(P=(T*b.root-E)/A,P>=0&&P<=1&&(m=b.root,_=!0,this._edge.scaleInPlace(P),o.addToRef(this._edge,this._collisionPoint))),n.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex),A=this._edge.lengthSquared(),T=e.Vector3.Dot(this._edge,this.velocity),E=e.Vector3.Dot(this._edge,this._baseToVertex),v=A*-g+T*T,y=A*(2*e.Vector3.Dot(this.velocity,this._baseToVertex))-2*T*E,x=A*(1-this._baseToVertex.lengthSquared())+E*E,b=i(v,y,x,m),b.found&&(P=(T*b.root-E)/A,P>=0&&P<=1&&(m=b.root,_=!0,this._edge.scaleInPlace(P),s.addToRef(this._edge,this._collisionPoint)))}if(_){var S=m*this.velocity.length();(!this.collisionFound||S<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=S,this.collisionFound=!0)}}},r.prototype._collide=function(e,t,i,r,n,o,s){for(var a=r;a<n;a+=3){var h=t[i[a]-o],c=t[i[a+1]-o],l=t[i[a+2]-o];this._testTriangle(a,e,l,c,h,s)}},r.prototype._getResponse=function(t,i){t.addToRef(i,this._destinationPoint),i.scaleInPlace(this.nearestDistance/i.length()),this.basePoint.addToRef(i,t),t.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),t.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(e.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,i)},r})();e.Collider=r})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){e.CollisionWorker="",(function(e){e[e.INIT=0]="INIT",e[e.UPDATE=1]="UPDATE",e[e.COLLIDE=2]="COLLIDE"})(e.WorkerTaskType||(e.WorkerTaskType={}));var t=e.WorkerTaskType;!(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.UNKNOWN_ERROR=1]="UNKNOWN_ERROR"})(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,r=(function(){function r(){var n=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){n._addUpdateMeshesList[e.uniqueId]=r.SerializeMesh(e)},this.onGeometryUpdated=function(e){n._addUpdateGeometriesList[e.id]=r.SerializeGeometry(e)},this._afterRender=function(){if(n._init&&!(0==n._toRemoveGeometryArray.length&&0==n._toRemoveMeshesArray.length&&0==Object.keys(n._addUpdateGeometriesList).length&&0==Object.keys(n._addUpdateMeshesList).length||n._runningUpdated>4)){++n._runningUpdated;var e={updatedMeshes:n._addUpdateMeshesList,updatedGeometries:n._addUpdateGeometriesList,removedGeometries:n._toRemoveGeometryArray,removedMeshes:n._toRemoveMeshesArray},i={payload:e,taskType:t.UPDATE},r=[];for(var o in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(o)&&(r.push(i.payload.updatedGeometries[o].indices.buffer),r.push(i.payload.updatedGeometries[o].normals.buffer),r.push(i.payload.updatedGeometries[o].positions.buffer));n._worker.postMessage(i,r),n._addUpdateMeshesList={},n._addUpdateGeometriesList={},n._toRemoveGeometryArray=[],n._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(r){var o=r.data;if(o.error!=i.SUCCESS)return void e.Tools.Warn("error returned from worker!");switch(o.taskType){case t.INIT:n._init=!0,n._scene.meshes.forEach((function(e){n.onMeshAdded(e)})),n._scene.getGeometries().forEach((function(e){n.onGeometryAdded(e)}));break;case t.UPDATE:n._runningUpdated--;break;case t.COLLIDE:n._runningCollisionTask=!1;var s=o.payload;if(!n._collisionsCallbackArray[s.collisionId])return;n._collisionsCallbackArray[s.collisionId](s.collisionId,e.Vector3.FromArray(s.newPosition),n._scene.getMeshByUniqueID(s.collidedMeshUniqueId)),n._collisionsCallbackArray[s.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return r.prototype.getNewPosition=function(e,i,r,n,o,s,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(r.radius,this._scaledPosition),i.divideToRef(r.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=s;var h={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:r.radius.asArray()},collisionId:a,excludedMeshUniqueId:o?o.uniqueId:null,maximumRetry:n},c={payload:h,taskType:t.COLLIDE};this._worker.postMessage(c)}},r.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var r=e.WorkerIncluded?e.Engine.CodeRepository+"Collisions/babylon.collisionWorker.js":URL.createObjectURL(new Blob([e.CollisionWorker],{type:"application/javascript"}));this._worker=new Worker(r),this._worker.onmessage=this._onMessageFromWorker;var n={payload:{},taskType:t.INIT};this._worker.postMessage(n)},r.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},r.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},r.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},r.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},r.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},r.SerializeMesh=function(t){var i=[];t.subMeshes&&(i=t.subMeshes.map((function(e,t){return{position:t,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}})));var r=null;return t instanceof e.Mesh?r=t.geometry?t.geometry.id:null:t instanceof e.InstancedMesh&&(r=t.sourceMesh&&t.sourceMesh.geometry?t.sourceMesh.geometry.id:null),{uniqueId:t.uniqueId,id:t.id,name:t.name,geometryId:r,sphereCenter:t.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:t.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:t.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:t.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:t.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:t.checkCollisions}},r.SerializeGeometry=function(t){return{id:t.id,positions:new Float32Array(t.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(t.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(t.getIndices()||[])}},r})();e.CollisionCoordinatorWorker=r;var n=(function(){function t(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return t.prototype.getNewPosition=function(e,t,i,r,n,o,s){e.divideToRef(i.radius,this._scaledPosition),t.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i.radius),o(s,this._finalPosition,i.collidedMesh)},t.prototype.init=function(e){this._scene=e},t.prototype.destroy=function(){},t.prototype.onMeshAdded=function(e){},t.prototype.onMeshUpdated=function(e){},t.prototype.onMeshRemoved=function(e){},t.prototype.onGeometryAdded=function(e){},t.prototype.onGeometryUpdated=function(e){},t.prototype.onGeometryDeleted=function(e){},t.prototype._collideWithWorld=function(t,i,r,n,o,s){void 0===s&&(s=null);var a=10*e.Engine.CollisionsEpsilon;if(r.retry>=n)return void o.copyFrom(t);r._initialize(t,i,a);for(var h=0;h<this._scene.meshes.length;h++){var c=this._scene.meshes[h];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==s&&c._checkCollision(r)}return r.collisionFound?(0===i.x&&0===i.y&&0===i.z||r._getResponse(t,i),i.length()<=a?void o.copyFrom(t):(r.retry++,void this._collideWithWorld(t,i,r,n,o,s))):void t.addToRef(i,o)},t})();e.CollisionCoordinatorLegacy=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o){t.call(this,r,o),this.upVector=e.Vector3.Up(),this.orthoLeft=null,this.orthoRight=null,this.orthoBottom=null,this.orthoTop=null,this.fov=.8,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this.mode=i.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new e.Viewport(0,0,1,1),this.layerMask=268435455,this.fovMode=i.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=i.RIG_MODE_NONE,this._rigCameras=new Array,this._computedViewMatrix=e.Matrix.Identity(),this._projectionMatrix=new e.Matrix,this._doNotComputeProjectionMatrix=!1,this._postProcesses=new Array,this._transformMatrix=e.Matrix.Zero(),this._webvrViewMatrix=e.Matrix.Identity(),this._activeMeshes=new e.SmartArray(256),this._globalPosition=e.Vector3.Zero(),this._refreshFrustumPlanes=!0,o.addCamera(this),o.activeCamera||(o.activeCamera=this),this.position=n}return __extends(i,t),Object.defineProperty(i,"PERSPECTIVE_CAMERA",{get:function(){return i._PERSPECTIVE_CAMERA},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ORTHOGRAPHIC_CAMERA",{get:function(){return i._ORTHOGRAPHIC_CAMERA},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOVMODE_VERTICAL_FIXED",{get:function(){return i._FOVMODE_VERTICAL_FIXED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOVMODE_HORIZONTAL_FIXED",{get:function(){return i._FOVMODE_HORIZONTAL_FIXED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_NONE",{get:function(){return i._RIG_MODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_ANAGLYPH",{get:function(){return i._RIG_MODE_STEREOSCOPIC_ANAGLYPH},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL",{get:function(){return i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED",{get:function(){return i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_STEREOSCOPIC_OVERUNDER",{get:function(){return i._RIG_MODE_STEREOSCOPIC_OVERUNDER},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_VR",{get:function(){return i._RIG_MODE_VR},enumerable:!0,configurable:!0}),Object.defineProperty(i,"RIG_MODE_WEBVR",{get:function(){return i._RIG_MODE_WEBVR},enumerable:!0,configurable:!0}),i.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+this.getTypeName(),this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},Object.defineProperty(i.prototype,"globalPosition",{get:function(){return this._globalPosition},enumerable:!0,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.position=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this.getEngine();this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector),this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()},i.prototype._updateFromScene=function(){this.updateCache(),this.update()},i.prototype._isSynchronized=function(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronized.call(this)&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())},i.prototype._isSynchronizedProjectionMatrix=function(){var e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;var t=this.getEngine();return e=this.mode===i.PERSPECTIVE_CAMERA?this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this):this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight()},i.prototype.attachControl=function(e,t){},i.prototype.detachControl=function(e){},i.prototype.update=function(){this.cameraRigMode!==i.RIG_MODE_NONE&&this._updateRigCameras(),this._checkInputs()},i.prototype._checkInputs=function(){},i.prototype._cascadePostProcessesToRigCams=function(){this._postProcesses.length>0&&this._postProcesses[0].markTextureDirty();for(var t=0,i=this._rigCameras.length;t<i;t++){var r=this._rigCameras[t],n=r._rigPostProcess;if(n){var o=n instanceof e.PassPostProcess;o&&(r.isIntermediate=0===this._postProcesses.length),r._postProcesses=this._postProcesses.slice(0).concat(n),n.markTextureDirty()}else r._postProcesses=this._postProcesses.slice(0)}},i.prototype.attachPostProcess=function(t,i){return void 0===i&&(i=null),!t.isReusable()&&this._postProcesses.indexOf(t)>-1?(e.Tools.Error("You're trying to reuse a post process not defined as reusable."),0):(null==i||i<0?this._postProcesses.push(t):this._postProcesses.splice(i,0,t),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(t))},i.prototype.detachPostProcess=function(e,t){void 0===t&&(t=null);var i,r,n=[];if(t)for(t=t instanceof Array?t:[t],i=t.length-1;i>=0;i--)this._postProcesses[t[i]]===e?this._postProcesses.splice(r,1):n.push(i);else{var o=this._postProcesses.indexOf(e);o!==-1&&this._postProcesses.splice(o,1)}return this._cascadePostProcessesToRigCams(),n},i.prototype.getWorldMatrix=function(){this._worldMatrix||(this._worldMatrix=e.Matrix.Identity());var t=this.getViewMatrix();return t.invertToRef(this._worldMatrix),this._worldMatrix},i.prototype._getViewMatrix=function(){return e.Matrix.Identity()},i.prototype.getViewMatrix=function(t){return this._computedViewMatrix=this._computeViewMatrix(t),!t&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._refreshFrustumPlanes=!0,this.parent&&this.parent.getWorldMatrix?(this._worldMatrix||(this._worldMatrix=e.Matrix.Identity()),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._computedViewMatrix),this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12],this._computedViewMatrix.m[13],this._computedViewMatrix.m[14]),this._computedViewMatrix.invert(),this._markSyncedWithParent()):this._globalPosition.copyFrom(this.position),this._currentRenderId=this.getScene().getRenderId(),this._computedViewMatrix)},i.prototype._computeViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._computedViewMatrix)},i.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},i.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},i.prototype.getProjectionMatrix=function(t){if(this._doNotComputeProjectionMatrix||!t&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._refreshFrustumPlanes=!0;var r=this.getEngine(),n=this.getScene();if(this.mode===i.PERSPECTIVE_CAMERA)return this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?e.Matrix.PerspectiveFovRHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED):e.Matrix.PerspectiveFovLHToRef(this.fov,r.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===i.FOVMODE_VERTICAL_FIXED),this._projectionMatrix;var o=r.getRenderWidth()/2,s=r.getRenderHeight()/2;return n.useRightHandedSystem?e.Matrix.OrthoOffCenterRHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix):e.Matrix.OrthoOffCenterLHToRef(this.orthoLeft||-o,this.orthoRight||o,this.orthoBottom||-s,this.orthoTop||s,this.minZ,this.maxZ,this._projectionMatrix),this._projectionMatrix},i.prototype.getTranformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},i.prototype.updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTranformationMatrix(),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},i.prototype.isInFrustum=function(e){return this.updateFrustumPlanes(),e.isInFrustum(this._frustumPlanes)},i.prototype.isCompletelyInFrustum=function(e){return this.updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},i.prototype.dispose=function(){for(this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;)this._rigCameras.pop().dispose();
for(var e=0;e<this._postProcesses.length;++e)this._postProcesses[e].dispose(this);t.prototype.dispose.call(this)},i.prototype.setCameraRigMode=function(t,r){for(;this._rigCameras.length>0;)this._rigCameras.pop().dispose();switch(this.cameraRigMode=t,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=r.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==i.RIG_MODE_NONE&&(this._rigCameras.push(this.createRigCamera(this.name+"_L",0)),this._rigCameras.push(this.createRigCamera(this.name+"_R",1))),this.cameraRigMode){case i.RIG_MODE_STEREOSCOPIC_ANAGLYPH:this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.AnaglyphPostProcess(this.name+"_anaglyph",1,this._rigCameras);break;case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case i.RIG_MODE_STEREOSCOPIC_OVERUNDER:var n=this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;this._rigCameras[0]._rigPostProcess=new e.PassPostProcess(this.name+"_passthru",1,this._rigCameras[0]),this._rigCameras[1]._rigPostProcess=new e.StereoscopicInterlacePostProcess(this.name+"_stereoInterlace",this._rigCameras,n);break;case i.RIG_MODE_VR:var o=r.vrCameraMetrics||e.VRCameraMetrics.GetDefault();this._rigCameras[0]._cameraRigParams.vrMetrics=o,this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0]._cameraRigParams.vrHMatrix=o.leftHMatrix,this._rigCameras[0]._cameraRigParams.vrPreViewMatrix=o.leftPreViewMatrix,this._rigCameras[0].getProjectionMatrix=this._rigCameras[0]._getVRProjectionMatrix,this._rigCameras[1]._cameraRigParams.vrMetrics=o,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1]._cameraRigParams.vrHMatrix=o.rightHMatrix,this._rigCameras[1]._cameraRigParams.vrPreViewMatrix=o.rightPreViewMatrix,this._rigCameras[1].getProjectionMatrix=this._rigCameras[1]._getVRProjectionMatrix,o.compensateDistortion&&(this._rigCameras[0]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",this._rigCameras[0],(!1),o),this._rigCameras[1]._rigPostProcess=new e.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",this._rigCameras[1],(!0),o));break;case i.RIG_MODE_WEBVR:r.vrDisplay&&(this._rigCameras[0].viewport=new e.Viewport(0,0,.5,1),this._rigCameras[0].setCameraRigParameter("left",!0),this._rigCameras[0].setCameraRigParameter("frameData",r.frameData),this._rigCameras[0]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[0].getProjectionMatrix=this._getWebVRProjectionMatrix,this._rigCameras[1].viewport=new e.Viewport(.5,0,.5,1),this._rigCameras[1].setCameraRigParameter("frameData",r.frameData),this._rigCameras[1]._cameraRigParams.vrWorkMatrix=new e.Matrix,this._rigCameras[1].getProjectionMatrix=this._getWebVRProjectionMatrix)}this._cascadePostProcessesToRigCams(),this.update()},i.prototype._getVRProjectionMatrix=function(){return e.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},i.prototype._getWebVRProjectionMatrix=function(){var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return[8,9,10,11].forEach((function(e){t[e]*=-1})),e.Matrix.FromArrayToRef(t,0,this._projectionMatrix),this._projectionMatrix},i.prototype._getWebVRViewMatrix=function(){var t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return[8,9,10,11].forEach((function(e){t[e]*=-1})),e.Matrix.FromArrayToRef(t,0,this._webvrViewMatrix),this._webvrViewMatrix},i.prototype.setCameraRigParameter=function(t,i){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[t]=i,"interaxialDistance"===t&&(this._cameraRigParams.stereoHalfAngle=e.Tools.ToRadians(i/.0637))},i.prototype.createRigCamera=function(e,t){return null},i.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov;this.cameraRigMode===i.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)},i.prototype._setupInputs=function(){},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.type=this.getTypeName(),this.parent&&(t.parentId=this.parent.id),this.inputs&&this.inputs.serialize(t),e.Animation.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},i.prototype.getTypeName=function(){return"Camera"},i.prototype.clone=function(t){return e.SerializationHelper.Clone(i.GetConstructorFromName(this.getTypeName(),t,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this)},i.prototype.getDirection=function(t){var i=e.Vector3.Zero();return this.getDirectionToRef(t,i),i},i.prototype.getDirectionToRef=function(t,i){e.Vector3.TransformNormalToRef(t,this.getWorldMatrix(),i)},i.GetConstructorFromName=function(t,i,r,n,o){switch(void 0===n&&(n=0),void 0===o&&(o=!0),t){case"ArcRotateCamera":return function(){return new e.ArcRotateCamera(i,0,0,1,e.Vector3.Zero(),r)};case"DeviceOrientationCamera":return function(){return new e.DeviceOrientationCamera(i,e.Vector3.Zero(),r)};case"FollowCamera":return function(){return new e.FollowCamera(i,e.Vector3.Zero(),r)};case"ArcFollowCamera":return function(){return new e.ArcFollowCamera(i,0,0,1,null,r)};case"GamepadCamera":return function(){return new e.GamepadCamera(i,e.Vector3.Zero(),r)};case"TouchCamera":return function(){return new e.TouchCamera(i,e.Vector3.Zero(),r)};case"VirtualJoysticksCamera":return function(){return new e.VirtualJoysticksCamera(i,e.Vector3.Zero(),r)};case"WebVRFreeCamera":return function(){return new e.WebVRFreeCamera(i,e.Vector3.Zero(),r)};case"VRDeviceOrientationFreeCamera":return function(){return new e.VRDeviceOrientationFreeCamera(i,e.Vector3.Zero(),r)};case"AnaglyphArcRotateCamera":return function(){return new e.AnaglyphArcRotateCamera(i,0,0,1,e.Vector3.Zero(),n,r)};case"AnaglyphFreeCamera":return function(){return new e.AnaglyphFreeCamera(i,e.Vector3.Zero(),n,r)};case"AnaglyphGamepadCamera":return function(){return new e.AnaglyphGamepadCamera(i,e.Vector3.Zero(),n,r)};case"AnaglyphUniversalCamera":return function(){return new e.AnaglyphUniversalCamera(i,e.Vector3.Zero(),n,r)};case"StereoscopicArcRotateCamera":return function(){return new e.StereoscopicArcRotateCamera(i,0,0,1,e.Vector3.Zero(),n,o,r)};case"StereoscopicFreeCamera":return function(){return new e.StereoscopicFreeCamera(i,e.Vector3.Zero(),n,o,r)};case"StereoscopicGamepadCamera":return function(){return new e.StereoscopicGamepadCamera(i,e.Vector3.Zero(),n,o,r)};case"StereoscopicUniversalCamera":return function(){return new e.StereoscopicUniversalCamera(i,e.Vector3.Zero(),n,o,r)};case"FreeCamera":return function(){return new e.UniversalCamera(i,e.Vector3.Zero(),r)};default:return function(){return new e.UniversalCamera(i,e.Vector3.Zero(),r)}}},i.Parse=function(t,r){var n=t.type,o=i.GetConstructorFromName(n,t.name,r,t.interaxial_distance,t.isStereoscopicSideBySide),s=e.SerializationHelper.Parse(o,t,r);if(t.parentId&&(s._waitingParentId=t.parentId),s.inputs&&(s.inputs.parse(t),s._setupInputs()),t.target&&s.setTarget&&s.setTarget(e.Vector3.FromArray(t.target)),t.cameraRigMode){var a=t.interaxial_distance?{interaxialDistance:t.interaxial_distance}:{};s.setCameraRigMode(t.cameraRigMode,a)}if(t.animations){for(var h=0;h<t.animations.length;h++){var c=t.animations[h];s.animations.push(e.Animation.Parse(c))}e.Node.ParseAnimationRanges(s,t,r)}return t.autoAnimate&&r.beginAnimation(s,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),s},i._PERSPECTIVE_CAMERA=0,i._ORTHOGRAPHIC_CAMERA=1,i._FOVMODE_VERTICAL_FIXED=0,i._FOVMODE_HORIZONTAL_FIXED=1,i._RIG_MODE_NONE=0,i._RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,i._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,i._RIG_MODE_STEREOSCOPIC_OVERUNDER=13,i._RIG_MODE_VR=20,i._RIG_MODE_WEBVR=21,i.ForceAttachControlToAlwaysPreventDefault=!1,__decorate([e.serializeAsVector3()],i.prototype,"position",void 0),__decorate([e.serializeAsVector3()],i.prototype,"upVector",void 0),__decorate([e.serialize()],i.prototype,"orthoLeft",void 0),__decorate([e.serialize()],i.prototype,"orthoRight",void 0),__decorate([e.serialize()],i.prototype,"orthoBottom",void 0),__decorate([e.serialize()],i.prototype,"orthoTop",void 0),__decorate([e.serialize()],i.prototype,"fov",void 0),__decorate([e.serialize()],i.prototype,"minZ",void 0),__decorate([e.serialize()],i.prototype,"maxZ",void 0),__decorate([e.serialize()],i.prototype,"inertia",void 0),__decorate([e.serialize()],i.prototype,"mode",void 0),__decorate([e.serialize()],i.prototype,"layerMask",void 0),__decorate([e.serialize()],i.prototype,"fovMode",void 0),__decorate([e.serialize()],i.prototype,"cameraRigMode",void 0),__decorate([e.serialize()],i.prototype,"interaxialDistance",void 0),__decorate([e.serialize()],i.prototype,"isStereoscopicSideBySide",void 0),i})(e.Node);e.Camera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){e.CameraInputTypes={};var t=(function(){function t(e){this.attached={},this.camera=e,this.checkInputs=function(){}}return t.prototype.add=function(t){var i=t.getSimpleName();return this.attached[i]?void e.Tools.Warn("camera input of type "+i+" already exists on camera"):(this.attached[i]=t,t.camera=this.camera,t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t))),void(this.attachedElement&&t.attachControl(this.attachedElement)))},t.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];i===e&&(i.detachControl(this.attachedElement),delete this.attached[t],this.rebuildInputCheck())}},t.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getTypeName()===e&&(i.detachControl(this.attachedElement),delete this.attached[t],this.rebuildInputCheck())}},t.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},t.prototype.attachInput=function(e){e.attachControl(this.attachedElement,this.noPreventDefault)},t.prototype.attachElement=function(t,i){if(!this.attachedElement){i=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&i,this.attachedElement=t,this.noPreventDefault=i;for(var r in this.attached){this.attached[r];this.attached[r].attachControl(t,i)}}},t.prototype.detachElement=function(e){if(this.attachedElement===e){for(var t in this.attached){this.attached[t];this.attached[t].detachControl(e)}this.attachedElement=null}},t.prototype.rebuildInputCheck=function(){this.checkInputs=function(){};for(var e in this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},t.prototype.clear=function(){this.attachedElement&&this.detachElement(this.attachedElement),this.attached={},this.attachedElement=null,this.checkInputs=function(){}},t.prototype.serialize=function(t){var i={};for(var r in this.attached){var n=this.attached[r],o=e.SerializationHelper.Serialize(n);i[n.getTypeName()]=o}t.inputsmgr=i},t.prototype.parse=function(t){var i=t.inputsmgr;if(i){this.clear();for(var r in i){var n=e.CameraInputTypes[r];if(n){var o=i[r],s=e.SerializationHelper.Parse((function(){return new n}),o,null);this.add(s)}}}else for(var r in this.attached){var n=e.CameraInputTypes[this.attached[r].getTypeName()];if(n){var s=e.SerializationHelper.Parse((function(){return new n}),t,null);this.remove(this.attached[r]),this.add(s)}}},t})();e.CameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){void 0===e&&(e=!0),this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3}return t.prototype.attachControl=function(t,i){var r=this,n=this.camera.getEngine();this._pointerInput||(this._pointerInput=function(o,s){var a=o.event;if((r.touchEnabled||"touch"!==a.pointerType)&&(o.type===e.PointerEventTypes.POINTERMOVE||r.buttons.indexOf(a.button)!==-1))if(o.type===e.PointerEventTypes.POINTERDOWN){try{a.srcElement.setPointerCapture(a.pointerId)}catch(h){}r.previousPosition={x:a.clientX,y:a.clientY},i||(a.preventDefault(),t.focus())}else if(o.type===e.PointerEventTypes.POINTERUP){try{a.srcElement.releasePointerCapture(a.pointerId)}catch(h){}r.previousPosition=null,i||a.preventDefault()}else if(o.type===e.PointerEventTypes.POINTERMOVE){if(!r.previousPosition||n.isPointerLock)return;var c=a.clientX-r.previousPosition.x,l=a.clientY-r.previousPosition.y;r.camera.getScene().useRightHandedSystem?r.camera.cameraRotation.y-=c/r.angularSensibility:r.camera.cameraRotation.y+=c/r.angularSensibility,r.camera.cameraRotation.x+=l/r.angularSensibility,r.previousPosition={x:a.clientX,y:a.clientY},i||a.preventDefault()}}),this._onMouseMove=function(e){if(n.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,o=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;r.camera.getScene().useRightHandedSystem?r.camera.cameraRotation.y-=t/r.angularSensibility:r.camera.cameraRotation.y+=t/r.angularSensibility,r.camera.cameraRotation.x+=o/r.angularSensibility,r.previousPosition=null,i||e.preventDefault()}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),t.addEventListener("mousemove",this._onMouseMove,!1)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),e.removeEventListener("mousemove",this._onMouseMove),this._observer=null,this._onMouseMove=null,this.previousPosition=null)},t.prototype.getTypeName=function(){return"FreeCameraMouseInput"},t.prototype.getSimpleName=function(){return"mouse"},__decorate([e.serialize()],t.prototype,"buttons",void 0),__decorate([e.serialize()],t.prototype,"angularSensibility",void 0),t})();e.FreeCameraMouseInput=t,e.CameraInputTypes.FreeCameraMouseInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._keys=[],this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39]}return t.prototype.attachControl=function(t,i){var r=this;this._onKeyDown||(t.tabIndex=1,this._onKeyDown=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t===-1&&r._keys.push(e.keyCode),i||e.preventDefault()}},this._onKeyUp=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t>=0&&r._keys.splice(t,1),i||e.preventDefault()}},t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]))},t.prototype.detachControl=function(t){this._onKeyDown&&(t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),this._keys=[],this._onKeyDown=null,this._onKeyUp=null)},t.prototype.checkInputs=function(){if(this._onKeyDown)for(var t=this.camera,i=0;i<this._keys.length;i++){var r=this._keys[i],n=t._computeLocalCameraSpeed();this.keysLeft.indexOf(r)!==-1?t._localDirection.copyFromFloats(-n,0,0):this.keysUp.indexOf(r)!==-1?t._localDirection.copyFromFloats(0,0,n):this.keysRight.indexOf(r)!==-1?t._localDirection.copyFromFloats(n,0,0):this.keysDown.indexOf(r)!==-1&&t._localDirection.copyFromFloats(0,0,-n),t.getScene().useRightHandedSystem&&(t._localDirection.z*=-1),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),e.Vector3.TransformNormalToRef(t._localDirection,t._cameraTransformMatrix,t._transformedDirection),t.cameraDirection.addInPlace(t._transformedDirection)}},t.prototype.getTypeName=function(){return"FreeCameraKeyboardMoveInput"},t.prototype._onLostFocus=function(e){this._keys=[]},t.prototype.getSimpleName=function(){return"keyboard"},__decorate([e.serialize()],t.prototype,"keysUp",void 0),__decorate([e.serialize()],t.prototype,"keysDown",void 0),__decorate([e.serialize()],t.prototype,"keysLeft",void 0),__decorate([e.serialize()],t.prototype,"keysRight",void 0),t})();e.FreeCameraKeyboardMoveInput=t,e.CameraInputTypes.FreeCameraKeyboardMoveInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._offsetX=null,this._offsetY=null,this._pointerCount=0,this._pointerPressed=[],this.touchAngularSensibility=2e5,this.touchMoveSensibility=250}return t.prototype.attachControl=function(t,i){var r,n=this;void 0===this._pointerInput&&(this._onLostFocus=function(e){n._offsetX=null,n._offsetY=null},this._pointerInput=function(t,o){var s=t.event;if("mouse"!==s.pointerType)if(t.type===e.PointerEventTypes.POINTERDOWN){if(i||s.preventDefault(),n._pointerPressed.push(s.pointerId),1!==n._pointerPressed.length)return;r={x:s.clientX,y:s.clientY}}else if(t.type===e.PointerEventTypes.POINTERUP){i||s.preventDefault();var a=n._pointerPressed.indexOf(s.pointerId);if(a===-1)return;if(n._pointerPressed.splice(a,1),0!=a)return;r=null,n._offsetX=null,n._offsetY=null}else if(t.type===e.PointerEventTypes.POINTERMOVE){if(i||s.preventDefault(),!r)return;var a=n._pointerPressed.indexOf(s.pointerId);if(0!=a)return;n._offsetX=s.clientX-r.x,n._offsetY=-(s.clientY-r.y)}}),this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),t.addEventListener("blur",this._onLostFocus)},t.prototype.detachControl=function(e){this._pointerInput&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null,this._pointerPressed=[],this._offsetX=null,this._offsetY=null,this._pointerCount=0)},t.prototype.checkInputs=function(){if(this._offsetX){var t=this.camera;if(t.cameraRotation.y+=this._offsetX/this.touchAngularSensibility,this._pointerPressed.length>1)t.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var i=t._computeLocalCameraSpeed(),r=new e.Vector3(0,0,i*this._offsetY/this.touchMoveSensibility);e.Matrix.RotationYawPitchRollToRef(t.rotation.y,t.rotation.x,0,t._cameraRotationMatrix),t.cameraDirection.addInPlace(e.Vector3.TransformCoordinates(r,t._cameraRotationMatrix))}}},t.prototype.getTypeName=function(){return"FreeCameraTouchInput"},t.prototype.getSimpleName=function(){return"touch"},__decorate([e.serialize()],t.prototype,"touchAngularSensibility",void 0),__decorate([e.serialize()],t.prototype,"touchMoveSensibility",void 0),t})();e.FreeCameraTouchInput=t,e.CameraInputTypes.FreeCameraTouchInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){var t=this;this._screenOrientationAngle=0,this._screenQuaternion=new e.Quaternion,this._alpha=0,this._beta=0,this._gamma=0,this._orientationChanged=function(){t._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,t._screenOrientationAngle=-e.Tools.ToRadians(t._screenOrientationAngle/2),t._screenQuaternion.copyFromFloats(0,Math.sin(t._screenOrientationAngle),0,Math.cos(t._screenOrientationAngle))},this._deviceOrientation=function(e){t._alpha=e.alpha,t._beta=e.beta,t._gamma=e.gamma},this._constantTranform=new e.Quaternion((-Math.sqrt(.5)),0,0,Math.sqrt(.5)),this._orientationChanged()}return Object.defineProperty(t.prototype,"camera",{get:function(){return this._camera},set:function(t){this._camera=t,this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new e.Quaternion)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){window.addEventListener("orientationchange",this._orientationChanged),window.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()},t.prototype.detachControl=function(e){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation)},t.prototype.checkInputs=function(){this._alpha&&(e.Quaternion.RotationYawPitchRollToRef(e.Tools.ToRadians(this._alpha),e.Tools.ToRadians(this._beta),-e.Tools.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)},t.prototype.getTypeName=function(){return"FreeCameraDeviceOrientationInput"},t.prototype.getSimpleName=function(){return"deviceOrientation"},t})();e.FreeCameraDeviceOrientationInput=t,e.CameraInputTypes.FreeCameraDeviceOrientationInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this;this._gamepads=new e.Gamepads(function(e){r._onNewGameConnected(e)})},t.prototype.detachControl=function(e){this._gamepads&&this._gamepads.dispose(),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var t=this.camera,i=this.gamepad.leftStick,r=i.x/this.gamepadMoveSensibility,n=i.y/this.gamepadMoveSensibility;i.x=Math.abs(r)>.005?0+r:0,i.y=Math.abs(n)>.005?0+n:0;var o=this.gamepad.rightStick,s=o.x/this.gamepadAngularSensibility,a=o.y/this.gamepadAngularSensibility;o.x=Math.abs(s)>.001?0+s:0,o.y=Math.abs(a)>.001?0+a:0;var h=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),c=50*t._computeLocalCameraSpeed(),l=e.Vector3.TransformCoordinates(new e.Vector3(i.x*c,0,-i.y*c),h);t.cameraDirection=t.cameraDirection.add(l),t.cameraRotation=t.cameraRotation.add(new e.Vector2(o.y,o.x))}},t.prototype._onNewGameConnected=function(e){0===e.index&&(this.gamepad=e)},t.prototype.getTypeName=function(){return"FreeCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},__decorate([e.serialize()],t.prototype,"gamepadAngularSensibility",void 0),__decorate([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.FreeCameraGamepadInput=t,e.CameraInputTypes.FreeCameraGamepadInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._keys=[],this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39]}return t.prototype.attachControl=function(t,i){var r=this;t.tabIndex=1,this._onKeyDown=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t===-1&&r._keys.push(e.keyCode),e.preventDefault&&(i||e.preventDefault())}},this._onKeyUp=function(e){if(r.keysUp.indexOf(e.keyCode)!==-1||r.keysDown.indexOf(e.keyCode)!==-1||r.keysLeft.indexOf(e.keyCode)!==-1||r.keysRight.indexOf(e.keyCode)!==-1){var t=r._keys.indexOf(e.keyCode);t>=0&&r._keys.splice(t,1),e.preventDefault&&(i||e.preventDefault())}},this._onLostFocus=function(){r._keys=[]},t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){t&&(t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp)),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),this._keys=[],this._onKeyDown=null,this._onKeyUp=null,this._onLostFocus=null},t.prototype.checkInputs=function(){if(this._onKeyDown)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t];this.keysLeft.indexOf(i)!==-1?e.inertialAlphaOffset-=.01:this.keysUp.indexOf(i)!==-1?e.inertialBetaOffset-=.01:this.keysRight.indexOf(i)!==-1?e.inertialAlphaOffset+=.01:this.keysDown.indexOf(i)!==-1&&(e.inertialBetaOffset+=.01)}},t.prototype.getTypeName=function(){return"ArcRotateCameraKeyboardMoveInput"},t.prototype.getSimpleName=function(){return"keyboard"},__decorate([e.serialize()],t.prototype,"keysUp",void 0),__decorate([e.serialize()],t.prototype,"keysDown",void 0),__decorate([e.serialize()],t.prototype,"keysLeft",void 0),__decorate([e.serialize()],t.prototype,"keysRight",void 0),t})();e.ArcRotateCameraKeyboardMoveInput=t,e.CameraInputTypes.ArcRotateCameraKeyboardMoveInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.wheelPrecision=3}return t.prototype.attachControl=function(t,i){var r=this;this._wheel=function(t,n){if(t.type===e.PointerEventTypes.POINTERWHEEL){var o=t.event,s=0;o.wheelDelta?s=o.wheelDelta/(40*r.wheelPrecision):o.detail&&(s=-o.detail/r.wheelPrecision),s&&(r.camera.inertialRadiusOffset+=s),o.preventDefault&&(i||o.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,e.PointerEventTypes.POINTERWHEEL)},t.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},t.prototype.getTypeName=function(){return"ArcRotateCameraMouseWheelInput"},t.prototype.getSimpleName=function(){return"mousewheel"},__decorate([e.serialize()],t.prototype,"wheelPrecision",void 0),t})();e.ArcRotateCameraMouseWheelInput=t,e.CameraInputTypes.ArcRotateCameraMouseWheelInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(e.Tools.GetPointerPrefix(),(function(){function t(){this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=6,this.panningSensibility=50,this._isPanClick=!1,this.pinchInwards=!0}return t.prototype.attachControl=function(t,i){var r,n,o,s=this,a=this.camera.getEngine(),h=0;this._pointerInput=function(a,c){var l=a.event;if(a.type===e.PointerEventTypes.POINTERMOVE||s.buttons.indexOf(l.button)!==-1)if(a.type===e.PointerEventTypes.POINTERDOWN){try{l.srcElement.setPointerCapture(l.pointerId)}catch(u){}s._isPanClick=l.button===s.camera._panningMouseButton,r={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType},void 0===n?n=r:void 0===o&&(o=r),i||(l.preventDefault(),t.focus())}else if(a.type===e.PointerEventTypes.POINTERUP){try{l.srcElement.releasePointerCapture(l.pointerId)}catch(u){}r=null,h=0,n=o=void 0,i||l.preventDefault()}else if(a.type===e.PointerEventTypes.POINTERMOVE)if(i||l.preventDefault(),n&&void 0===o){if(0!==s.panningSensibility&&(l.ctrlKey&&s.camera._useCtrlForPanning||!s.camera._useCtrlForPanning&&s._isPanClick))s.camera.inertialPanningX+=-(l.clientX-r.x)/s.panningSensibility,s.camera.inertialPanningY+=(l.clientY-r.y)/s.panningSensibility;else{var d=l.clientX-r.x,f=l.clientY-r.y;s.camera.inertialAlphaOffset-=d/s.angularSensibilityX,s.camera.inertialBetaOffset-=f/s.angularSensibilityY}r.x=l.clientX,r.y=l.clientY}else if(n&&o){var p=n.pointerId===l.pointerId?n:o;p.x=l.clientX,p.y=l.clientY;var _=s.pinchInwards?1:-1,m=n.x-o.x,g=n.y-o.y,v=m*m+g*g;if(0===h)return void(h=v);v!==h&&(s.camera.inertialRadiusOffset+=(v-h)/(s.pinchPrecision*((s.angularSensibilityX+s.angularSensibilityY)/2)*_),h=v)}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,e.PointerEventTypes.POINTERDOWN|e.PointerEventTypes.POINTERUP|e.PointerEventTypes.POINTERMOVE),this._onContextMenu=function(e){e.preventDefault()},this.camera._useCtrlForPanning||t.addEventListener("contextmenu",this._onContextMenu,!1),this._onLostFocus=function(){n=o=void 0,h=0,r=null},this._onMouseMove=function(e){if(a.isPointerLock){var t=e.movementX||e.mozMovementX||e.webkitMovementX||e.msMovementX||0,r=e.movementY||e.mozMovementY||e.webkitMovementY||e.msMovementY||0;s.camera.inertialAlphaOffset-=t/s.angularSensibilityX,s.camera.inertialBetaOffset-=r/s.angularSensibilityY,i||e.preventDefault()}},this._onGestureStart=function(e){void 0!==window.MSGesture&&(s._MSGestureHandler||(s._MSGestureHandler=new MSGesture,s._MSGestureHandler.target=t),s._MSGestureHandler.addPointer(e.pointerId))},this._onGesture=function(e){s.camera.radius*=e.scale,e.preventDefault&&(i||(e.stopPropagation(),e.preventDefault()))},t.addEventListener("mousemove",this._onMouseMove,!1),t.addEventListener("MSPointerDown",this._onGestureStart,!1),t.addEventListener("MSGestureChange",this._onGesture,!1),t.addEventListener("keydown",this._onKeyDown,!1),t.addEventListener("keyup",this._onKeyUp,!1),e.Tools.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.detachControl=function(t){t&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,t.removeEventListener("contextmenu",this._onContextMenu),t.removeEventListener("mousemove",this._onMouseMove),t.removeEventListener("MSPointerDown",this._onGestureStart),t.removeEventListener("MSGestureChange",this._onGesture),t.removeEventListener("keydown",this._onKeyDown),t.removeEventListener("keyup",this._onKeyUp),this._isPanClick=!1,this.pinchInwards=!0,this._onKeyDown=null,this._onKeyUp=null,this._onMouseMove=null,this._onGestureStart=null,this._onGesture=null,this._MSGestureHandler=null,this._onLostFocus=null,this._onContextMenu=null),e.Tools.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},t.prototype.getTypeName=function(){return"ArcRotateCameraPointersInput"},t.prototype.getSimpleName=function(){return"pointers"},__decorate([e.serialize()],t.prototype,"buttons",void 0),__decorate([e.serialize()],t.prototype,"angularSensibilityX",void 0),__decorate([e.serialize()],t.prototype,"angularSensibilityY",void 0),__decorate([e.serialize()],t.prototype,"pinchPrecision",void 0),__decorate([e.serialize()],t.prototype,"panningSensibility",void 0),t})());e.ArcRotateCameraPointersInput=t,e.CameraInputTypes.ArcRotateCameraPointersInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40}return t.prototype.attachControl=function(t,i){var r=this;this._gamepads=new e.Gamepads(function(e){r._onNewGameConnected(e)})},t.prototype.detachControl=function(e){this._gamepads&&this._gamepads.dispose(),this.gamepad=null},t.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}var n=this.gamepad.leftStick;if(0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},t.prototype._onNewGameConnected=function(e){0===e.index&&(this.gamepad=e)},t.prototype.getTypeName=function(){return"ArcRotateCameraGamepadInput"},t.prototype.getSimpleName=function(){return"gamepad"},__decorate([e.serialize()],t.prototype,"gamepadRotationSensibility",void 0),__decorate([e.serialize()],t.prototype,"gamepadMoveSensibility",void 0),t})();e.ArcRotateCameraGamepadInput=t,e.CameraInputTypes.ArcRotateCameraGamepadInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.alphaCorrection=1,this.betaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._beta=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}return e.prototype.attachControl=function(e,t){this.camera.attachControl(e,t),window.addEventListener("deviceorientation",this._deviceOrientationHandler);
},e.prototype._onOrientationEvent=function(e){this.camera;this._alpha=0|+e.alpha,this._beta=0|+e.beta,this._gamma=0|+e.gamma,this._dirty=!0},e.prototype.checkInputs=function(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)},e.prototype.detachControl=function(e){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype.getTypeName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"VRDeviceOrientation"},e})();e.ArcRotateCameraVRDeviceOrientationInput=t,e.CameraInputTypes.ArcRotateCameraVRDeviceOrientationInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,r,n),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0),this.rotation=new e.Vector3(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.lockedTarget=null,this._currentTarget=e.Vector3.Zero(),this._viewMatrix=e.Matrix.Zero(),this._camMatrix=e.Matrix.Zero(),this._cameraTransformMatrix=e.Matrix.Zero(),this._cameraRotationMatrix=e.Matrix.Zero(),this._referencePoint=new e.Vector3(0,0,1),this._defaultUpVector=new e.Vector3(0,1,0),this._transformedReferencePoint=e.Vector3.Zero(),this._lookAtTemp=e.Matrix.Zero(),this._tempMatrix=e.Matrix.Zero()}return __extends(i,t),i.prototype.getFrontPosition=function(e){var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},i.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.lockedTarget=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new e.Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},i.prototype._isSynchronizedViewMatrix=function(){if(!t.prototype._isSynchronizedViewMatrix.call(this))return!1;var e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},i.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},i.prototype.setTarget=function(t){this.upVector.normalize(),e.Matrix.LookAtLHToRef(this.position,t,this._defaultUpVector,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var i=t.subtract(this.position);i.x>=0?this.rotation.y=-Math.atan(i.z/i.x)+Math.PI/2:this.rotation.y=-Math.atan(i.z/i.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&e.Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},i.prototype.getTarget=function(){return this._currentTarget},i.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.position.addInPlace(this.cameraDirection)},i.prototype._checkInputs=function(){var i=this._decideIfNeedsToMove(),r=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(i&&this._updatePosition(),r&&(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,!this.noRotationConstraint)){var n=Math.PI/2*.95;this.rotation.x>n&&(this.rotation.x=n),this.rotation.x<-n&&(this.rotation.x=-n)}i&&(Math.abs(this.cameraDirection.x)<e.Epsilon&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<e.Epsilon&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<e.Epsilon&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),r&&(Math.abs(this.cameraRotation.x)<e.Epsilon&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<e.Epsilon&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),t.prototype._checkInputs.call(this)},i.prototype._updateCameraRotationMatrix=function(){this.rotationQuaternion?(this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix),e.Vector3.TransformNormalToRef(this._defaultUpVector,this._cameraRotationMatrix,this.upVector)):e.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)},i.prototype._getViewMatrix=function(){return this.lockedTarget?this._currentTarget.copyFrom(this._getLockedTargetPosition()):(this._updateCameraRotationMatrix(),e.Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget)),this.getScene().useRightHandedSystem?e.Matrix.LookAtRHToRef(this.position,this._currentTarget,this.upVector,this._viewMatrix):e.Matrix.LookAtLHToRef(this.position,this._currentTarget,this.upVector,this._viewMatrix),this._viewMatrix},i.prototype.createRigCamera=function(t,r){if(this.cameraRigMode!==e.Camera.RIG_MODE_NONE){var n=new i(t,this.position.clone(),this.getScene());return this.cameraRigMode!==e.Camera.RIG_MODE_VR&&this.cameraRigMode!==e.Camera.RIG_MODE_WEBVR||(this.rotationQuaternion||(this.rotationQuaternion=new e.Quaternion),n._cameraRigParams={},n.rotationQuaternion=new e.Quaternion),n}return null},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:var n=this.cameraRigMode===e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,o=this.cameraRigMode===e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle*n,i.position),this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle*o,r.position),i.setTarget(this.getTarget()),r.setTarget(this.getTarget());break;case e.Camera.RIG_MODE_VR:case e.Camera.RIG_MODE_WEBVR:i.rotationQuaternion?(i.rotationQuaternion.copyFrom(this.rotationQuaternion),r.rotationQuaternion.copyFrom(this.rotationQuaternion)):(i.rotation.copyFrom(this.rotation),r.rotation.copyFrom(this.rotation)),i.position.copyFrom(this.position),r.position.copyFrom(this.position)}t.prototype._updateRigCameras.call(this)},i.prototype._getRigCamPosition=function(t,i){this._rigCamTransformMatrix||(this._rigCamTransformMatrix=new e.Matrix);var r=this.getTarget();e.Matrix.Translation(-r.x,-r.y,-r.z).multiplyToRef(e.Matrix.RotationY(t),this._rigCamTransformMatrix),this._rigCamTransformMatrix=this._rigCamTransformMatrix.multiply(e.Matrix.Translation(r.x,r.y,r.z)),e.Vector3.TransformCoordinatesToRef(this.position,this._rigCamTransformMatrix,i)},i.prototype.getTypeName=function(){return"TargetCamera"},__decorate([e.serializeAsVector3()],i.prototype,"rotation",void 0),__decorate([e.serialize()],i.prototype,"speed",void 0),__decorate([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.Camera);e.TargetCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){var o=this;t.call(this,i,r,n),this.ellipsoid=new e.Vector3(.5,1,.5),this.checkCollisions=!1,this.applyGravity=!1,this._collider=new e.Collider,this._needMoveForGravity=!1,this._oldPosition=e.Vector3.Zero(),this._diffPosition=e.Vector3.Zero(),this._newPosition=e.Vector3.Zero(),this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),o.getScene().workerCollisions&&i.multiplyInPlace(o._collider.radius);var n=function(t){o._newPosition.copyFrom(t),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition);o.position.clone();o._diffPosition.length()>e.Engine.CollisionsEpsilon&&(o.position.addInPlace(o._diffPosition),o.onCollide&&r&&o.onCollide(r))};n(i)},this.inputs=new e.FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}return __extends(i,t),Object.defineProperty(i.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;if(e)return e.angularSensibility},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysUp},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysDown},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysLeft},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysRight},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),i.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},i.prototype.detachControl=function(t){this.inputs.detachElement(t),this.cameraDirection=new e.Vector3(0,0,0),this.cameraRotation=new e.Vector2(0,0)},i.prototype._collideWithWorld=function(t){var i;i=this.parent?e.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,i.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._collider.radius=this.ellipsoid;var r=t;this.applyGravity&&(r=t.add(this.getScene().gravity)),this.getScene().collisionCoordinator.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},i.prototype._checkInputs=function(){this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inputs.checkInputs(),t.prototype._checkInputs.call(this)},i.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},i.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):this.position.addInPlace(this.cameraDirection)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getTypeName=function(){return"FreeCamera"},__decorate([e.serializeAsVector3()],i.prototype,"ellipsoid",void 0),__decorate([e.serialize()],i.prototype,"checkCollisions",void 0),__decorate([e.serialize()],i.prototype,"applyGravity",void 0),i})(e.TargetCamera);e.FreeCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e){t.call(this,e)}return __extends(i,t),i.prototype.addKeyboard=function(){return this.add(new e.FreeCameraKeyboardMoveInput),this},i.prototype.addMouse=function(t){return void 0===t&&(t=!0),this.add(new e.FreeCameraMouseInput(t)),this},i.prototype.addGamepad=function(){return this.add(new e.FreeCameraGamepadInput),this},i.prototype.addDeviceOrientation=function(){return this.add(new e.FreeCameraDeviceOrientationInput),this},i.prototype.addTouch=function(){return this.add(new e.FreeCameraTouchInput),this},i.prototype.addVirtualJoystick=function(){return this.add(new e.FreeCameraVirtualJoystickInput),this},i})(e.CameraInputsManager);e.FreeCameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n){t.call(this,e,i,r),this.radius=12,this.rotationOffset=0,this.heightOffset=4,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=n}return __extends(i,t),i.prototype.getRadians=function(e){return e*Math.PI/180},i.prototype.follow=function(t){if(t){var i;if(t.rotationQuaternion){var r=new e.Matrix;t.rotationQuaternion.toRotationMatrix(r),i=Math.atan2(r.m[8],r.m[10])}else i=t.rotation.y;var n=this.getRadians(this.rotationOffset)+i,o=t.position.x+Math.sin(n)*this.radius,s=t.position.z+Math.cos(n)*this.radius,a=o-this.position.x,h=t.position.y+this.heightOffset-this.position.y,c=s-this.position.z,l=a*this.cameraAcceleration*2,u=h*this.cameraAcceleration,d=c*this.cameraAcceleration*2;(l>this.maxCameraSpeed||l<-this.maxCameraSpeed)&&(l=l<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new e.Vector3(this.position.x+l,this.position.y+u,this.position.z+d),this.setTarget(t.position)}},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow(this.lockedTarget)},i.prototype.getTypeName=function(){return"FollowCamera"},__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serialize()],i.prototype,"rotationOffset",void 0),__decorate([e.serialize()],i.prototype,"heightOffset",void 0),__decorate([e.serialize()],i.prototype,"cameraAcceleration",void 0),__decorate([e.serialize()],i.prototype,"maxCameraSpeed",void 0),__decorate([e.serializeAsMeshReference("lockedTargetId")],i.prototype,"lockedTarget",void 0),i})(e.TargetCamera);e.FollowCamera=t;var i=(function(t){function i(i,r,n,o,s,a){t.call(this,i,e.Vector3.Zero(),a),this.alpha=r,this.beta=n,this.radius=o,this.target=s,this._cartesianCoordinates=e.Vector3.Zero(),this.follow()}return __extends(i,t),i.prototype.follow=function(){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta),this.position=this.target.position.add(this._cartesianCoordinates),this.setTarget(this.target.position)},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this.follow()},i.prototype.getTypeName=function(){return"ArcFollowCamera"},i})(e.TargetCamera);e.ArcFollowCamera=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addTouch(),this._setupInputs()}return __extends(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;if(e)return e.touchAngularSensibility},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;if(e)return e.touchMoveSensibility},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getTypeName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t})(e.FreeCamera);e.TouchCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;t.call(this,i,e.Vector3.Zero(),a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.zoomOnFactor=1,this.targetScreenOffset=e.Vector2.Zero(),this.allowUpsideDown=!0,this._viewMatrix=new e.Matrix,this.panningAxis=new e.Vector3(1,1,0),this.checkCollisions=!1,this.collisionRadius=new e.Vector3(.5,.5,.5),this._collider=new e.Collider,this._previousPosition=e.Vector3.Zero(),this._collisionVelocity=e.Vector3.Zero(),this._newPosition=e.Vector3.Zero(),this._onCollisionPositionChange=function(t,i,r){void 0===r&&(r=null),h.getScene().workerCollisions&&h.checkCollisions&&i.multiplyInPlace(h._collider.radius),r?(h.setPosition(i),h.onCollide&&h.onCollide(r)):h._previousPosition.copyFrom(h.position);var n=Math.cos(h.alpha),o=Math.sin(h.alpha),s=Math.cos(h.beta),a=Math.sin(h.beta);0===a&&(a=1e-4);var c=h._getTargetPosition();c.addToRef(new e.Vector3(h.radius*n*a,h.radius*s,h.radius*o*a),h._newPosition),h.position.copyFrom(h._newPosition);var l=h.upVector;h.allowUpsideDown&&h.beta<0&&(l=l.clone(),l=l.negate()),e.Matrix.LookAtLHToRef(h.position,c,l,h._viewMatrix),h._viewMatrix.m[12]+=h.targetScreenOffset.x,h._viewMatrix.m[13]+=h.targetScreenOffset.y,h._collisionTriggered=!1},s?this.target=s:this.target=e.Vector3.Zero(),this.alpha=r,this.beta=n,this.radius=o,this.getViewMatrix(),this.inputs=new e.ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad()}return __extends(i,t),Object.defineProperty(i.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.angularSensibilityX},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.angularSensibilityY},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.pinchPrecision},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;if(e)return e.panningSensibility},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysUp},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysDown},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysLeft},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;if(e)return e.keysRight},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;if(e)return e.wheelPrecision},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),i.prototype._initCache=function(){t.prototype._initCache.call(this),this._cache.target=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=e.Vector2.Zero()},i.prototype._updateCache=function(e){e||t.prototype._updateCache.call(this),this._cache.target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},i.prototype._getTargetPosition=function(){if(this.target.getAbsolutePosition){var e=this.target.getAbsolutePosition();return this._targetBoundingCenter?e.add(this._targetBoundingCenter):e}return this.target},i.prototype._isSynchronizedViewMatrix=function(){return!!t.prototype._isSynchronizedViewMatrix.call(this)&&(this._cache.target.equals(this.target)&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))},i.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2),this._useCtrlForPanning=i,this._panningMouseButton=r,this.inputs.attachElement(e,t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0}},i.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},i.prototype._checkInputs=function(){this._collisionTriggered||(this.inputs.checkInputs(),0===this.inertialAlphaOffset&&0===this.inertialBetaOffset&&0===this.inertialRadiusOffset||(this.getScene().useRightHandedSystem?this.alpha-=this.beta<=0?-this.inertialAlphaOffset:this.inertialAlphaOffset:this.alpha+=this.beta<=0?-this.inertialAlphaOffset:this.inertialAlphaOffset,this.beta+=this.inertialBetaOffset,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<e.Epsilon&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<e.Epsilon&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<e.Epsilon&&(this.inertialRadiusOffset=0)),0===this.inertialPanningX&&0===this.inertialPanningY||(this._localDirection||(this._localDirection=e.Vector3.Zero(),this._transformedDirection=e.Vector3.Zero()),this.inertialPanningX*=this.inertia,this.inertialPanningY*=this.inertia,Math.abs(this.inertialPanningX)<e.Epsilon&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<e.Epsilon&&(this.inertialPanningY=0),this._localDirection.copyFromFloats(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY),this._localDirection.multiplyInPlace(this.panningAxis),this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.Vector3.TransformNormalToRef(this._localDirection,this._cameraTransformMatrix,this._transformedDirection),this.panningAxis.y||(this._transformedDirection.y=0),this.target.getAbsolutePosition||this.target.addInPlace(this._transformedDirection)),this._checkLimits(),t.prototype._checkInputs.call(this))},i.prototype._checkLimits=function(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit)},i.prototype.rebuildAnglesAndRadius=function(){var e=this.position.subtract(this._getTargetPosition());this.radius=e.length(),this.alpha=Math.acos(e.x/Math.sqrt(Math.pow(e.x,2)+Math.pow(e.z,2))),e.z<0&&(this.alpha=2*Math.PI-this.alpha),this.beta=Math.acos(e.y/this.radius),this._checkLimits()},i.prototype.setPosition=function(e){this.position.equals(e)||(this.position.copyFrom(e),this.rebuildAnglesAndRadius())},i.prototype.setTarget=function(e,t){void 0===t&&(t=!1),this._getTargetPosition().equals(e)||(t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.center.clone():this._targetBoundingCenter=null,this.target=e,this.rebuildAnglesAndRadius())},i.prototype._getViewMatrix=function(){var t=Math.cos(this.alpha),i=Math.sin(this.alpha),r=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var o=this._getTargetPosition();if(o.addToRef(new e.Vector3(this.radius*t*n,this.radius*r,this.radius*i*n),this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions)this._collider.radius=this.collisionRadius,this._newPosition.subtractToRef(this.position,this._collisionVelocity),this._collisionTriggered=!0,this.getScene().collisionCoordinator.getNewPosition(this.position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId);else{this.position.copyFrom(this._newPosition);var s=this.upVector;this.allowUpsideDown&&this.beta<0&&(s=s.clone(),s=s.negate()),this.getScene().useRightHandedSystem?e.Matrix.LookAtRHToRef(this.position,o,s,this._viewMatrix):e.Matrix.LookAtLHToRef(this.position,o,s,this._viewMatrix),this._viewMatrix.m[12]+=this.targetScreenOffset.x,this._viewMatrix.m[13]+=this.targetScreenOffset.y}return this._currentTarget=o,this._viewMatrix},i.prototype.zoomOn=function(t,i){void 0===i&&(i=!1),t=t||this.getScene().meshes;var r=e.Mesh.MinMax(t),n=e.Vector3.Distance(r.min,r.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:r.min,max:r.max,distance:n},i)},i.prototype.focusOn=function(t,i){void 0===i&&(i=!1);var r,n;void 0===t.min?(r=t||this.getScene().meshes,r=e.Mesh.MinMax(r),n=e.Vector3.Distance(r.min,r.max)):(r=t,n=t.distance),this.target=e.Mesh.Center(r),i||(this.maxZ=2*n)},i.prototype.createRigCamera=function(t,r){var n;switch(this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===r?1:-1);break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===r?-1:1)}var o=new i(t,this.alpha+n,this.beta,this.radius,this.target,this.getScene());return o._cameraRigParams={},o},i.prototype._updateRigCameras=function(){var i=this._rigCameras[0],r=this._rigCameras[1];switch(i.beta=r.beta=this.beta,i.radius=r.radius=this.radius,this.cameraRigMode){case e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case e.Camera.RIG_MODE_VR:i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,r.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}t.prototype._updateRigCameras.call(this)},i.prototype.dispose=function(){this.inputs.clear(),t.prototype.dispose.call(this)},i.prototype.getTypeName=function(){return"ArcRotateCamera"},__decorate([e.serialize()],i.prototype,"alpha",void 0),__decorate([e.serialize()],i.prototype,"beta",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serializeAsVector3()],i.prototype,"target",void 0),__decorate([e.serialize()],i.prototype,"inertialAlphaOffset",void 0),__decorate([e.serialize()],i.prototype,"inertialBetaOffset",void 0),__decorate([e.serialize()],i.prototype,"inertialRadiusOffset",void 0),__decorate([e.serialize()],i.prototype,"lowerAlphaLimit",void 0),__decorate([e.serialize()],i.prototype,"upperAlphaLimit",void 0),__decorate([e.serialize()],i.prototype,"lowerBetaLimit",void 0),__decorate([e.serialize()],i.prototype,"upperBetaLimit",void 0),__decorate([e.serialize()],i.prototype,"lowerRadiusLimit",void 0),__decorate([e.serialize()],i.prototype,"upperRadiusLimit",void 0),__decorate([e.serialize()],i.prototype,"inertialPanningX",void 0),__decorate([e.serialize()],i.prototype,"inertialPanningY",void 0),__decorate([e.serialize()],i.prototype,"zoomOnFactor",void 0),__decorate([e.serialize()],i.prototype,"allowUpsideDown",void 0),i})(e.TargetCamera);e.ArcRotateCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e){t.call(this,e)}return __extends(i,t),i.prototype.addMouseWheel=function(){return this.add(new e.ArcRotateCameraMouseWheelInput),this},i.prototype.addPointers=function(){return this.add(new e.ArcRotateCameraPointersInput),this},i.prototype.addKeyboard=function(){return this.add(new e.ArcRotateCameraKeyboardMoveInput),this},i.prototype.addGamepad=function(){return this.add(new e.ArcRotateCameraGamepadInput),this},i.prototype.addVRDeviceOrientation=function(){return this.add(new e.ArcRotateCameraVRDeviceOrientationInput),this},i})(e.CameraInputsManager);e.ArcRotateCameraInputsManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderinGroupInfo=null,this._scene=e;for(var i=t.MIN_RENDERINGGROUPS;i<t.MAX_RENDERINGGROUPS;i++)this._autoClearDepthStencil[i]=!0}return t.prototype._renderParticles=function(e,t){if(0!==this._scene._activeParticleSystems.length){var i=this._scene.activeCamera;this._scene._particlesDuration.beginMonitoring();for(var r=0;r<this._scene._activeParticleSystems.length;r++){var n=this._scene._activeParticleSystems.data[r];n.renderingGroupId===e&&0!==(i.layerMask&n.layerMask)&&(this._clearDepthStencilBuffer(),n.emitter.position&&t&&t.indexOf(n.emitter)===-1||this._scene._activeParticles.addCount(n.render(),!1))}this._scene._particlesDuration.endMonitoring(!1)}},t.prototype._renderSprites=function(e){if(this._scene.spritesEnabled&&0!==this._scene.spriteManagers.length){var t=this._scene.activeCamera;this._scene._spritesDuration.beginMonitoring();for(var i=0;i<this._scene.spriteManagers.length;i++){var r=this._scene.spriteManagers[i];r.renderingGroupId===e&&0!==(t.layerMask&r.layerMask)&&(this._clearDepthStencilBuffer(),r.render())}this._scene._spritesDuration.endMonitoring(!1)}},t.prototype._clearDepthStencilBuffer=function(){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(0,!1,!0,!0),this._depthStencilBufferAlreadyCleaned=!0)},t.prototype._renderSpritesAndParticles=function(){this._currentRenderSprites&&this._renderSprites(this._currentIndex),this._currentRenderParticles&&this._renderParticles(this._currentIndex,this._currentActiveMeshes)},t.prototype.render=function(i,r,n,o){var s=this._scene.onRenderingGroupObservable.hasObservers()?this._scene.onRenderingGroupObservable:null,a=null;s&&(this._renderinGroupInfo||(this._renderinGroupInfo=new e.RenderingGroupInfo),a=this._renderinGroupInfo,a.scene=this._scene,a.camera=this._scene.activeCamera),this._currentActiveMeshes=r,this._currentRenderParticles=n,this._currentRenderSprites=o;for(var h=t.MIN_RENDERINGGROUPS;h<t.MAX_RENDERINGGROUPS;h++){this._depthStencilBufferAlreadyCleaned=h===t.MIN_RENDERINGGROUPS;var c=this._renderingGroups[h],l=!1;if(this._currentIndex=h,c){var u=0;s&&(u=Math.pow(2,h),a.renderStage=e.RenderingGroupInfo.STAGE_PRECLEAR,a.renderingGroupId=h,s.notifyObservers(a,u)),this._autoClearDepthStencil[h]&&this._clearDepthStencilBuffer(),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_PREOPAQUE,s.notifyObservers(a,u)),c.onBeforeTransparentRendering||(c.onBeforeTransparentRendering=this._renderSpritesAndParticles.bind(this)),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_PRETRANSPARENT,s.notifyObservers(a,u)),c.render(i)||(this._renderingGroups.splice(h,1),l=!0,this._renderSpritesAndParticles()),s&&(a.renderStage=e.RenderingGroupInfo.STAGE_POSTTRANSPARENT,s.notifyObservers(a,u))}else if(this._renderSpritesAndParticles(),s){var u=Math.pow(2,h);a.renderStage=e.RenderingGroupInfo.STAGE_PRECLEAR,
a.renderingGroupId=h,s.notifyObservers(a,u),a.renderStage=e.RenderingGroupInfo.STAGE_POSTTRANSPARENT,s.notifyObservers(a,u)}l&&h--}},t.prototype.reset=function(){for(var e=t.MIN_RENDERINGGROUPS;e<t.MAX_RENDERINGGROUPS;e++){var i=this._renderingGroups[e];i&&i.prepare()}},t.prototype.dispatch=function(t){var i=t.getMesh(),r=i.renderingGroupId||0;this._renderingGroups[r]||(this._renderingGroups[r]=new e.RenderingGroup(r,this._scene,this._customOpaqueSortCompareFn[r],this._customAlphaTestSortCompareFn[r],this._customTransparentSortCompareFn[r])),this._renderingGroups[r].dispatch(t)},t.prototype.setRenderingOrder=function(e,t,i,r){if(void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){var n=this._renderingGroups[e];n.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],n.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],n.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}},t.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._autoClearDepthStencil[e]=t},t.MAX_RENDERINGGROUPS=4,t.MIN_RENDERINGGROUPS=0,t})();e.RenderingManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=null),this.index=t,this._opaqueSubMeshes=new e.SmartArray(256),this._transparentSubMeshes=new e.SmartArray(256),this._alphaTestSubMeshes=new e.SmartArray(256),this._scene=i,this.opaqueSortCompareFn=r,this.alphaTestSortCompareFn=n,this.transparentSortCompareFn=o}return Object.defineProperty(t.prototype,"opaqueSortCompareFn",{set:function(e){this._opaqueSortCompareFn=e,e?this._renderOpaque=this.renderOpaqueSorted:this._renderOpaque=t.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"alphaTestSortCompareFn",{set:function(e){this._alphaTestSortCompareFn=e,e?this._renderAlphaTest=this.renderAlphaTestSorted:this._renderAlphaTest=t.renderUnsorted},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transparentSortCompareFn",{set:function(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=t.defaultTransparentSortCompare,this._renderTransparent=this.renderTransparentSorted},enumerable:!0,configurable:!0}),t.prototype.render=function(t){if(t)return t(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes),!0;if(0===this._opaqueSubMeshes.length&&0===this._alphaTestSubMeshes.length&&0===this._transparentSubMeshes.length)return this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),!1;var i=this._scene.getEngine();return this._renderOpaque(this._opaqueSubMeshes),i.setAlphaTesting(!0),this._renderAlphaTest(this._alphaTestSubMeshes),i.setAlphaTesting(!1),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),this._renderTransparent(this._transparentSubMeshes),i.setAlphaMode(e.Engine.ALPHA_DISABLE),!0},t.prototype.renderOpaqueSorted=function(e){return t.renderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera.globalPosition,!1)},t.prototype.renderAlphaTestSorted=function(e){return t.renderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera.globalPosition,!1)},t.prototype.renderTransparentSorted=function(e){return t.renderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera.globalPosition,!0)},t.renderSorted=function(e,t,i,r){for(var n,o=0;o<e.length;o++)n=e.data[o],n._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=n.getBoundingInfo().boundingSphere.centerWorld.subtract(i).length();var s=e.data.slice(0,e.length);for(s.sort(t),o=0;o<s.length;o++)n=s[o],n.render(r)},t.renderUnsorted=function(e){for(var t=0;t<e.length;t++){var i=e.data[t];i.render(!1)}},t.defaultTransparentSortCompare=function(e,i){return e._alphaIndex>i._alphaIndex?1:e._alphaIndex<i._alphaIndex?-1:t.backToFrontSortCompare(e,i)},t.backToFrontSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0},t.frontToBackSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0},t.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset()},t.prototype.dispatch=function(e){var t=e.getMaterial(),i=e.getMesh();t.needAlphaBlending()||i.visibility<1||i.hasVertexAlpha?this._transparentSubMeshes.push(e):t.needAlphaTesting()?this._alphaTestSubMeshes.push(e):this._opaqueSubMeshes.push(e)},t})();e.RenderingGroup=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return Object.defineProperty(e,"POINTERDOWN",{get:function(){return e._POINTERDOWN},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERUP",{get:function(){return e._POINTERUP},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERMOVE",{get:function(){return e._POINTERMOVE},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERWHEEL",{get:function(){return e._POINTERWHEEL},enumerable:!0,configurable:!0}),Object.defineProperty(e,"POINTERPICK",{get:function(){return e._POINTERPICK},enumerable:!0,configurable:!0}),e._POINTERDOWN=1,e._POINTERUP=2,e._POINTERMOVE=4,e._POINTERWHEEL=8,e._POINTERPICK=16,e})();e.PointerEventTypes=t;var i=(function(){function e(e,t){this.type=e,this.event=t}return e})();e.PointerInfoBase=i;var r=(function(t){function i(i,r,n,o){t.call(this,i,r),this.skipOnPointerObservable=!1,this.localPosition=new e.Vector2(n,o)}return __extends(i,t),i})(i);e.PointerInfoPre=r;var n=(function(e){function t(t,i,r){e.call(this,t,i),this.pickInfo=r}return __extends(t,e),t})(i);e.PointerInfo=n;var o=(function(){function e(){}return e.STAGE_PRECLEAR=1,e.STAGE_PREOPAQUE=2,e.STAGE_PRETRANSPARENT=3,e.STAGE_POSTTRANSPARENT=4,e})();e.RenderingGroupInfo=o;var s=(function(){function i(t){this.autoClear=!0,this.clearColor=new e.Color3(.2,.2,.3),this.ambientColor=new e.Color3(0,0,0),this.forceWireframe=!1,this.forcePointsCloud=!1,this.forceShowBoundingBoxes=!1,this.animationsEnabled=!0,this.constantlyUpdateMeshUnderPointer=!1,this.useRightHandedSystem=!1,this.hoverCursor="pointer",this.metadata=null,this.onDisposeObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onReadyObservable=new e.Observable,this.onBeforeCameraRenderObservable=new e.Observable,this.onAfterCameraRenderObservable=new e.Observable,this.onNewCameraAddedObservable=new e.Observable,this.onCameraRemovedObservable=new e.Observable,this.onNewLightAddedObservable=new e.Observable,this.onLightRemovedObservable=new e.Observable,this.onNewGeometryAddedObservable=new e.Observable,this.onGeometryRemovedObservable=new e.Observable,this.onNewMeshAddedObservable=new e.Observable,this.onMeshRemovedObservable=new e.Observable,this.onRenderingGroupObservable=new e.Observable,this.animations=[],this.onPrePointerObservable=new e.Observable,this.onPointerObservable=new e.Observable,this.cameraToUseForPointers=null,this._startingPointerPosition=new e.Vector2(0,0),this._startingPointerTime=0,this.fogEnabled=!0,this.fogMode=i.FOGMODE_NONE,this.fogColor=new e.Color3(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.shadowsEnabled=!0,this.lightsEnabled=!0,this.lights=new Array,this.cameras=new Array,this.activeCameras=new Array,this.meshes=new Array,this._geometries=new Array,this.materials=new Array,this.multiMaterials=new Array,this.texturesEnabled=!0,this.textures=new Array,this.particlesEnabled=!0,this.particleSystems=new Array,this.spritesEnabled=!0,this.spriteManagers=new Array,this.layers=new Array,this.highlightLayers=new Array,this.skeletonsEnabled=!0,this.skeletons=new Array,this.lensFlaresEnabled=!0,this.lensFlareSystems=new Array,this.collisionsEnabled=!0,this.gravity=new e.Vector3(0,(-9.807),0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=new Array,this.importedMeshesFiles=new Array,this.probesEnabled=!0,this.reflectionProbes=new Array,this._actionManagers=new Array,this._meshesForIntersections=new e.SmartArray(256),this.proceduralTexturesEnabled=!0,this._proceduralTextures=new Array,this.soundTracks=new Array,this._audioEnabled=!0,this._headphone=!1,this._totalMeshesCounter=new e.PerfCounter,this._totalLightsCounter=new e.PerfCounter,this._totalMaterialsCounter=new e.PerfCounter,this._totalTexturesCounter=new e.PerfCounter,this._totalVertices=new e.PerfCounter,this._activeIndices=new e.PerfCounter,this._activeParticles=new e.PerfCounter,this._lastFrameDuration=new e.PerfCounter,this._evaluateActiveMeshesDuration=new e.PerfCounter,this._renderTargetsDuration=new e.PerfCounter,this._particlesDuration=new e.PerfCounter,this._renderDuration=new e.PerfCounter,this._spritesDuration=new e.PerfCounter,this._activeBones=new e.PerfCounter,this._renderId=0,this._executeWhenReadyTimeoutId=-1,this._intermediateRendering=!1,this._toBeDisposed=new e.SmartArray(256),this._pendingData=[],this._activeMeshes=new e.SmartArray(256),this._processedMaterials=new e.SmartArray(256),this._renderTargets=new e.SmartArray(256),this._activeParticleSystems=new e.SmartArray(256),this._activeSkeletons=new e.SmartArray(32),this._softwareSkinnedMeshes=new e.SmartArray(32),this._activeAnimatables=new Array,this._transformMatrix=e.Matrix.Zero(),this._edgesRenderers=new e.SmartArray(16),this._uniqueIdCounter=0,this._engine=t,t.scenes.push(this),this._externalData=new e.StringDictionary,this._uid=null,this._renderingManager=new e.RenderingManager(this),this.postProcessManager=new e.PostProcessManager(this),this.postProcessRenderPipelineManager=new e.PostProcessRenderPipelineManager,this._boundingBoxRenderer=new e.BoundingBoxRenderer(this),e.OutlineRenderer&&(this._outlineRenderer=new e.OutlineRenderer(this)),this.attachControl(),e.SoundTrack&&(this.mainSoundTrack=new e.SoundTrack(this,{mainTrack:!0})),e.SimplificationQueue&&(this.simplificationQueue=new e.SimplificationQueue),this.workerCollisions=!1}return Object.defineProperty(i,"FOGMODE_NONE",{get:function(){return i._FOGMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_EXP",{get:function(){return i._FOGMODE_EXP},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_EXP2",{get:function(){return i._FOGMODE_EXP2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"FOGMODE_LINEAR",{get:function(){return i._FOGMODE_LINEAR},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"beforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"afterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"beforeCameraRender",{set:function(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"afterCameraRender",{set:function(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"unTranslatedPointer",{get:function(){return new e.Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"defaultMaterial",{get:function(){return this._defaultMaterial||(this._defaultMaterial=new e.StandardMaterial("default material",this)),this._defaultMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new e.DebugLayer(this)),this._debugLayer},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"workerCollisions",{get:function(){return this._workerCollisions},set:function(t){t=t&&!!Worker,this._workerCollisions=t,this.collisionCoordinator&&this.collisionCoordinator.destroy(),this.collisionCoordinator=t?new e.CollisionCoordinatorWorker:new e.CollisionCoordinatorLegacy,this.collisionCoordinator.init(this)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"SelectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"meshUnderPointer",{get:function(){return this._pointerOverMesh},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pointerX",{get:function(){return this._pointerX},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"pointerY",{get:function(){return this._pointerY},enumerable:!0,configurable:!0}),i.prototype.getCachedMaterial=function(){return this._cachedMaterial},i.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer},i.prototype.getOutlineRenderer=function(){return this._outlineRenderer},i.prototype.getEngine=function(){return this._engine},i.prototype.getTotalVertices=function(){return this._totalVertices.current},Object.defineProperty(i.prototype,"totalVerticesPerfCounter",{get:function(){return this._totalVertices},enumerable:!0,configurable:!0}),i.prototype.getActiveIndices=function(){return this._activeIndices.current},Object.defineProperty(i.prototype,"totalActiveIndicesPerfCounter",{get:function(){return this._activeIndices},enumerable:!0,configurable:!0}),i.prototype.getActiveParticles=function(){return this._activeParticles.current},Object.defineProperty(i.prototype,"activeParticlesPerfCounter",{get:function(){return this._activeParticles},enumerable:!0,configurable:!0}),i.prototype.getActiveBones=function(){return this._activeBones.current},Object.defineProperty(i.prototype,"activeBonesPerfCounter",{get:function(){return this._activeBones},enumerable:!0,configurable:!0}),i.prototype.getLastFrameDuration=function(){return this._lastFrameDuration.current},Object.defineProperty(i.prototype,"lastFramePerfCounter",{get:function(){return this._lastFrameDuration},enumerable:!0,configurable:!0}),i.prototype.getEvaluateActiveMeshesDuration=function(){return this._evaluateActiveMeshesDuration.current},Object.defineProperty(i.prototype,"evaluateActiveMeshesDurationPerfCounter",{get:function(){return this._evaluateActiveMeshesDuration},enumerable:!0,configurable:!0}),i.prototype.getActiveMeshes=function(){return this._activeMeshes},i.prototype.getRenderTargetsDuration=function(){return this._renderTargetsDuration.current},i.prototype.getRenderDuration=function(){return this._renderDuration.current},Object.defineProperty(i.prototype,"renderDurationPerfCounter",{get:function(){return this._renderDuration},enumerable:!0,configurable:!0}),i.prototype.getParticlesDuration=function(){return this._particlesDuration.current},Object.defineProperty(i.prototype,"particlesDurationPerfCounter",{get:function(){return this._particlesDuration},enumerable:!0,configurable:!0}),i.prototype.getSpritesDuration=function(){return this._spritesDuration.current},Object.defineProperty(i.prototype,"spriteDuractionPerfCounter",{get:function(){return this._spritesDuration},enumerable:!0,configurable:!0}),i.prototype.getAnimationRatio=function(){return this._animationRatio},i.prototype.getRenderId=function(){return this._renderId},i.prototype.incrementRenderId=function(){this._renderId++},i.prototype._updatePointerPosition=function(e){var t=this._engine.getRenderingCanvasClientRect();this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY,this.cameraToUseForPointers&&(this._pointerX=this._pointerX-this.cameraToUseForPointers.viewport.x*this._engine.getRenderWidth(),this._pointerY=this._pointerY-this.cameraToUseForPointers.viewport.y*this._engine.getRenderHeight())},i.prototype.attachControl=function(i,o,s){var a=this;void 0===i&&(i=!0),void 0===o&&(o=!0),void 0===s&&(s=!0);var h=function(e){return e.isPickable&&e.actionManager&&e.actionManager.hasPointerTriggers};this._onPointerMove=function(e){if(a._updatePointerPosition(e),a.onPrePointerObservable.hasObservers()){var i="mousewheel"===e.type||"DOMMouseScroll"===e.type?t.POINTERWHEEL:t.POINTERMOVE,o=new r(i,e,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(o,i),o.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){var s=a._engine.getRenderingCanvas();a.pointerMovePredicate||(a.pointerMovePredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&(a.constantlyUpdateMeshUnderPointer||null!==e.actionManager&&void 0!==e.actionManager)});var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerMovePredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh?(a.setPointerOverSprite(null),a.setPointerOverMesh(c.pickedMesh),a._pointerOverMesh.actionManager&&a._pointerOverMesh.actionManager.hasPointerTriggers?a._pointerOverMesh.actionManager.hoverCursor?s.style.cursor=a._pointerOverMesh.actionManager.hoverCursor:s.style.cursor=a.hoverCursor:s.style.cursor=""):(a.setPointerOverMesh(null),c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite?(a.setPointerOverSprite(c.pickedSprite),a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor):(a.setPointerOverSprite(null),s.style.cursor="")),a.onPointerMove&&a.onPointerMove(e,c),a.onPointerObservable.hasObservers()){var i="mousewheel"===e.type||"DOMMouseScroll"===e.type?t.POINTERWHEEL:t.POINTERMOVE,o=new n(i,e,c);a.onPointerObservable.notifyObservers(o,i)}}},this._onPointerDown=function(i){if(a._updatePointerPosition(i),a.onPrePointerObservable.hasObservers()){var o=t.POINTERDOWN,s=new r(o,i,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(s,o),s.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){a._startingPointerPosition.x=a._pointerX,a._startingPointerPosition.y=a._pointerY,a._startingPointerTime=(new Date).getTime(),a.pointerDownPredicate||(a.pointerDownPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()}),a._pickedDownMesh=null;var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerDownPredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh&&c.pickedMesh.actionManager){if(a._pickedDownMesh=c.pickedMesh,c.pickedMesh.actionManager.hasPickTriggers){switch(i.button){case 0:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i));break;case 1:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i));break;case 2:c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i))}c.pickedMesh.actionManager&&c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i))}if(c.pickedMesh.actionManager&&c.pickedMesh.actionManager.hasSpecificTrigger(e.ActionManager.OnLongPressTrigger)){var l=a;window.setTimeout((function(){var t=l.pick(l._unTranslatedPointerX,l._unTranslatedPointerY,(function(t){return t.isPickable&&t.isVisible&&t.isReady()&&t.actionManager&&t.actionManager.hasSpecificTrigger(e.ActionManager.OnLongPressTrigger)}),!1,l.cameraToUseForPointers);t.hit&&t.pickedMesh&&t.pickedMesh.actionManager&&0!==l._startingPointerTime&&(new Date).getTime()-l._startingPointerTime>e.ActionManager.LongPressDelay&&Math.abs(l._startingPointerPosition.x-l._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(l._startingPointerPosition.y-l._pointerY)<e.ActionManager.DragMovementThreshold&&(l._startingPointerTime=0,t.pickedMesh.actionManager.processTrigger(e.ActionManager.OnLongPressTrigger,e.ActionEvent.CreateNew(t.pickedMesh,i)))}),e.ActionManager.LongPressDelay)}}if(a.onPointerDown&&a.onPointerDown(i,c),a.onPointerObservable.hasObservers()){var o=t.POINTERDOWN,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}if(a._pickedDownSprite=null,a.spriteManagers.length>0&&(c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite&&c.pickedSprite.actionManager)){switch(a._pickedDownSprite=c.pickedSprite,i.button){case 0:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnLeftPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i));break;case 1:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnCenterPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i));break;case 2:c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnRightPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))}c.pickedSprite.actionManager&&c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickDownTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))}}},this._onPointerUp=function(i){if(a._updatePointerPosition(i),a.onPrePointerObservable.hasObservers()){var o=t.POINTERUP,s=new r(o,i,a._unTranslatedPointerX,a._unTranslatedPointerY);if(a.onPrePointerObservable.notifyObservers(s,o),s.skipOnPointerObservable)return}if(a.cameraToUseForPointers||a.activeCamera){a.pointerUpPredicate||(a.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()});var c=a.pick(a._unTranslatedPointerX,a._unTranslatedPointerY,a.pointerUpPredicate,!1,a.cameraToUseForPointers);if(c.hit&&c.pickedMesh){if(null!=a._pickedDownMesh&&c.pickedMesh==a._pickedDownMesh&&(a.onPointerPick&&a.onPointerPick(i,c),a.onPointerObservable.hasObservers())){var o=t.POINTERPICK,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}c.pickedMesh.actionManager&&(c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i)),c.pickedMesh.actionManager&&Math.abs(a._startingPointerPosition.x-a._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(a._startingPointerPosition.y-a._pointerY)<e.ActionManager.DragMovementThreshold&&c.pickedMesh.actionManager.processTrigger(e.ActionManager.OnPickTrigger,e.ActionEvent.CreateNew(c.pickedMesh,i)))}if(a._pickedDownMesh&&a._pickedDownMesh.actionManager&&a._pickedDownMesh!==c.pickedMesh&&a._pickedDownMesh.actionManager.processTrigger(e.ActionManager.OnPickOutTrigger,e.ActionEvent.CreateNew(a._pickedDownMesh,i)),a.onPointerUp&&a.onPointerUp(i,c),a.onPointerObservable.hasObservers()){var o=t.POINTERUP,s=new n(o,i,c);a.onPointerObservable.notifyObservers(s,o)}a._startingPointerTime=0,a.spriteManagers.length>0&&(c=a.pickSprite(a._unTranslatedPointerX,a._unTranslatedPointerY,h,!1,a.cameraToUseForPointers),c.hit&&c.pickedSprite&&c.pickedSprite.actionManager&&(c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickUpTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i)),c.pickedSprite.actionManager&&Math.abs(a._startingPointerPosition.x-a._pointerX)<e.ActionManager.DragMovementThreshold&&Math.abs(a._startingPointerPosition.y-a._pointerY)<e.ActionManager.DragMovementThreshold&&c.pickedSprite.actionManager.processTrigger(e.ActionManager.OnPickTrigger,e.ActionEvent.CreateNewFromSprite(c.pickedSprite,a,i))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==c.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(e.ActionManager.OnPickOutTrigger,e.ActionEvent.CreateNewFromSprite(a._pickedDownSprite,a,i)))}},this._onKeyDown=function(t){a.actionManager&&a.actionManager.processTrigger(e.ActionManager.OnKeyDownTrigger,e.ActionEvent.CreateNewFromScene(a,t))},this._onKeyUp=function(t){a.actionManager&&a.actionManager.processTrigger(e.ActionManager.OnKeyUpTrigger,e.ActionEvent.CreateNewFromScene(a,t))};var c=e.Tools.GetPointerPrefix(),l=this._engine.getRenderingCanvas();s&&(l.addEventListener(c+"move",this._onPointerMove,!1),l.addEventListener("mousewheel",this._onPointerMove,!1),l.addEventListener("DOMMouseScroll",this._onPointerMove,!1)),o&&l.addEventListener(c+"down",this._onPointerDown,!1),i&&l.addEventListener(c+"up",this._onPointerUp,!1),l.tabIndex=1,l.addEventListener("keydown",this._onKeyDown,!1),l.addEventListener("keyup",this._onKeyUp,!1)},i.prototype.detachControl=function(){var t=e.Tools.GetPointerPrefix(),i=this._engine.getRenderingCanvas();i.removeEventListener(t+"move",this._onPointerMove),i.removeEventListener(t+"down",this._onPointerDown),i.removeEventListener(t+"up",this._onPointerUp),i.removeEventListener("mousewheel",this._onPointerMove),i.removeEventListener("DOMMouseScroll",this._onPointerMove),i.removeEventListener("keydown",this._onKeyDown),i.removeEventListener("keyup",this._onKeyUp)},i.prototype.isReady=function(){if(this._pendingData.length>0)return!1;var t;for(t=0;t<this._geometries.length;t++){var i=this._geometries[t];if(i.delayLoadState===e.Engine.DELAYLOADSTATE_LOADING)return!1}for(t=0;t<this.meshes.length;t++){var r=this.meshes[t];if(!r.isReady())return!1;var n=r.material;if(n&&!n.isReady(r))return!1}return!0},i.prototype.resetCachedMaterial=function(){this._cachedMaterial=null},i.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},i.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},i.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},i.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},i.prototype._addPendingData=function(e){this._pendingData.push(e)},i.prototype._removePendingData=function(e){var t=this._pendingData.indexOf(e);t!==-1&&this._pendingData.splice(t,1)},i.prototype.getWaitingItemsCount=function(){return this._pendingData.length},i.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),this._executeWhenReadyTimeoutId===-1&&(this._executeWhenReadyTimeoutId=setTimeout((function(){t._checkIsReady()}),150))},i.prototype._checkIsReady=function(){var e=this;return this.isReady()?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1)):void(this._executeWhenReadyTimeoutId=setTimeout((function(){e._checkIsReady()}),150))},i.prototype.beginAnimation=function(t,i,r,n,o,s,a){if(void 0===o&&(o=1),this.stopAnimation(t),a||(a=new e.Animatable(this,t,i,r,n,o,s)),t.animations&&a.appendAnimations(t,t.animations),t.getAnimatables)for(var h=t.getAnimatables(),c=0;c<h.length;c++)this.beginAnimation(h[c],i,r,n,o,s,a);return a.reset(),a},i.prototype.beginDirectAnimation=function(t,i,r,n,o,s,a){void 0===s&&(s=1);var h=new e.Animatable(this,t,r,n,o,s,a,i);return h},i.prototype.getAnimatableByTarget=function(e){for(var t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},Object.defineProperty(i.prototype,"Animatables",{get:function(){return this._activeAnimatables},enumerable:!0,configurable:!0}),i.prototype.stopAnimation=function(e,t){var i=this.getAnimatableByTarget(e);i&&i.stop(t)},i.prototype._animate=function(){if(this.animationsEnabled&&0!==this._activeAnimatables.length){if(!this._animationStartDate){if(this._pendingData.length>0)return;this._animationStartDate=e.Tools.Now}for(var t=e.Tools.Now,i=t-this._animationStartDate,r=0;r<this._activeAnimatables.length;r++)this._activeAnimatables[r]._animate(i)}},i.prototype.getViewMatrix=function(){return this._viewMatrix},i.prototype.getProjectionMatrix=function(){return this._projectionMatrix},i.prototype.getTransformMatrix=function(){return this._transformMatrix},i.prototype.setTransformMatrix=function(t,i){this._viewMatrix=t,this._projectionMatrix=i,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?e.Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=e.Frustum.GetPlanes(this._transformMatrix)},i.prototype.addMesh=function(e){e.uniqueId=this._uniqueIdCounter++;this.meshes.push(e);this.collisionCoordinator.onMeshAdded(e),this.onNewMeshAddedObservable.notifyObservers(e)},i.prototype.removeMesh=function(e){var t=this.meshes.indexOf(e);return t!==-1&&this.meshes.splice(t,1),this.collisionCoordinator.onMeshRemoved(e),this.onMeshRemovedObservable.notifyObservers(e),t},i.prototype.removeSkeleton=function(e){var t=this.skeletons.indexOf(e);return t!==-1&&this.skeletons.splice(t,1),t},i.prototype.removeLight=function(e){var t=this.lights.indexOf(e);return t!==-1&&this.lights.splice(t,1),this.onLightRemovedObservable.notifyObservers(e),t},i.prototype.removeCamera=function(e){var t=this.cameras.indexOf(e);t!==-1&&this.cameras.splice(t,1);var i=this.activeCameras.indexOf(e);return i!==-1&&this.activeCameras.splice(i,1),this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},i.prototype.addLight=function(e){e.uniqueId=this._uniqueIdCounter++;this.lights.push(e);this.onNewLightAddedObservable.notifyObservers(e)},i.prototype.addCamera=function(e){e.uniqueId=this._uniqueIdCounter++;this.cameras.push(e);this.onNewCameraAddedObservable.notifyObservers(e)},i.prototype.switchActiveCamera=function(e,t){void 0===t&&(t=!0);var i=this._engine.getRenderingCanvas();this.activeCamera.detachControl(i),this.activeCamera=e,t&&e.attachControl(i)},i.prototype.setActiveCameraByID=function(e){var t=this.getCameraByID(e);return t?(this.activeCamera=t,t):null},i.prototype.setActiveCameraByName=function(e){var t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null},i.prototype.getMaterialByID=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].id===e)return this.materials[t];return null},i.prototype.getMaterialByName=function(e){for(var t=0;t<this.materials.length;t++)if(this.materials[t].name===e)return this.materials[t];return null},i.prototype.getLensFlareSystemByName=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},i.prototype.getLensFlareSystemByID=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},i.prototype.getCameraByID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null},i.prototype.getCameraByUniqueID=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null},i.prototype.getCameraByName=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null},i.prototype.getBoneByID=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].id===e)return i.bones[r];return null},i.prototype.getBoneByName=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].name===e)return i.bones[r];return null},i.prototype.getLightByName=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null},i.prototype.getLightByID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null},i.prototype.getLightByUniqueID=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];
return null},i.prototype.getParticleSystemByID=function(e){for(var t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null},i.prototype.getGeometryByID=function(e){for(var t=0;t<this._geometries.length;t++)if(this._geometries[t].id===e)return this._geometries[t];return null},i.prototype.pushGeometry=function(e,t){return!(!t&&this.getGeometryByID(e.id))&&(this._geometries.push(e),this.collisionCoordinator.onGeometryAdded(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)},i.prototype.removeGeometry=function(e){var t=this._geometries.indexOf(e);return t>-1&&(this._geometries.splice(t,1),this.collisionCoordinator.onGeometryDeleted(e),this.onGeometryRemovedObservable.notifyObservers(e),!0)},i.prototype.getGeometries=function(){return this._geometries},i.prototype.getMeshByID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null},i.prototype.getMeshesByID=function(e){return this.meshes.filter((function(t){return t.id===e}))},i.prototype.getMeshByUniqueID=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null},i.prototype.getLastMeshByID=function(e){for(var t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},i.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},i.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getLightByID(e);if(i)return i;var r=this.getCameraByID(e);if(r)return r;var n=this.getBoneByID(e);return n},i.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getLightByName(e);if(i)return i;var r=this.getCameraByName(e);if(r)return r;var n=this.getBoneByName(e);return n},i.prototype.getMeshByName=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null},i.prototype.getSoundByName=function(t){var i;if(e.AudioEngine){for(i=0;i<this.mainSoundTrack.soundCollection.length;i++)if(this.mainSoundTrack.soundCollection[i].name===t)return this.mainSoundTrack.soundCollection[i];for(var r=0;r<this.soundTracks.length;r++)for(i=0;i<this.soundTracks[r].soundCollection.length;i++)if(this.soundTracks[r].soundCollection[i].name===t)return this.soundTracks[r].soundCollection[i]}return null},i.prototype.getLastSkeletonByID=function(e){for(var t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},i.prototype.getSkeletonById=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null},i.prototype.getSkeletonByName=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null},i.prototype.isActiveMesh=function(e){return this._activeMeshes.indexOf(e)!==-1},Object.defineProperty(i.prototype,"uid",{get:function(){return this._uid||(this._uid=e.Tools.RandomId()),this._uid},enumerable:!0,configurable:!0}),i.prototype.addExternalData=function(e,t){return this._externalData.add(e,t)},i.prototype.getExternalData=function(e){return this._externalData.get(e)},i.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData.getOrAddWithFactory(e,t)},i.prototype.removeExternalData=function(e){return this._externalData.remove(e)},i.prototype._evaluateSubMesh=function(e,t){if(t.alwaysSelectAsActiveMesh||1===t.subMeshes.length||e.isInFrustum(this._frustumPlanes)){var i=e.getMaterial();t.showSubMeshesBoundingBox&&this._boundingBoxRenderer.renderList.push(e.getBoundingInfo().boundingBox),i&&(i.getRenderTargetTextures&&this._processedMaterials.indexOf(i)===-1&&(this._processedMaterials.push(i),this._renderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._activeIndices.addCount(e.indexCount,!1),this._renderingManager.dispatch(e))}},i.prototype._isInIntermediateRendering=function(){return this._intermediateRendering},i.prototype._evaluateActiveMeshes=function(){this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._boundingBoxRenderer.reset(),this._edgesRenderers.reset();var t,i;if(this._selectionOctree){var r=this._selectionOctree.select(this._frustumPlanes);t=r.data,i=r.length}else i=this.meshes.length,t=this.meshes;for(var n=0;n<i;n++){var o=t[n];if(!o.isBlocked&&(this._totalVertices.addCount(o.getTotalVertices(),!1),o.isReady()&&o.isEnabled())){o.computeWorldMatrix(),o.actionManager&&o.actionManager.hasSpecificTriggers([e.ActionManager.OnIntersectionEnterTrigger,e.ActionManager.OnIntersectionExitTrigger])&&this._meshesForIntersections.pushNoDuplicate(o);var s=o.getLOD(this.activeCamera);s&&(o._preActivate(),(o.alwaysSelectAsActiveMesh||o.isVisible&&o.visibility>0&&0!==(o.layerMask&this.activeCamera.layerMask)&&o.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(o),this.activeCamera._activeMeshes.push(o),o._activate(this._renderId),this._activeMesh(o,s)))}}this._particlesDuration.beginMonitoring();e.Tools.Now;if(this.particlesEnabled){e.Tools.StartPerformanceCounter("Particles",this.particleSystems.length>0);for(var a=0;a<this.particleSystems.length;a++){var h=this.particleSystems[a];h.isStarted()&&(!h.emitter.position||h.emitter&&h.emitter.isEnabled())&&(this._activeParticleSystems.push(h),h.animate())}e.Tools.EndPerformanceCounter("Particles",this.particleSystems.length>0)}this._particlesDuration.endMonitoring(!1)},i.prototype._activeMesh=function(e,t){if(t.skeleton&&this.skeletonsEnabled&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&t.skeleton.prepare(),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t)),(e.showBoundingBox||this.forceShowBoundingBoxes)&&this._boundingBoxRenderer.renderList.push(e.getBoundingInfo().boundingBox),e._edgesRenderer&&this._edgesRenderers.push(e._edgesRenderer),t&&t.subMeshes){var i,r;if(t._submeshesOctree&&t.useOctreeForRenderingSelection){var n=t._submeshesOctree.select(this._frustumPlanes);i=n.length,r=n.data}else r=t.subMeshes,i=r.length;for(var o=0;o<i;o++){var s=r[o];this._evaluateSubMesh(s,t)}}},i.prototype.updateTransformMatrix=function(e){this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))},i.prototype._renderForCamera=function(t){var i=this._engine;e.Tools.Now;if(this.activeCamera=t,!this.activeCamera)throw new Error("Active camera not set");e.Tools.StartPerformanceCounter("Rendering camera "+this.activeCamera.name),i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshesDuration.beginMonitoring(),e.Tools.StartPerformanceCounter("Active meshes evaluation"),this._evaluateActiveMeshes(),this._evaluateActiveMeshesDuration.endMonitoring(!1),e.Tools.EndPerformanceCounter("Active meshes evaluation");for(var r=0;r<this._softwareSkinnedMeshes.length;r++){var n=this._softwareSkinnedMeshes.data[r];n.applySkeleton(n.skeleton)}this._renderTargetsDuration.beginMonitoring();var o=!1;e.Tools.Now;if(this.renderTargetsEnabled&&this._renderTargets.length>0){this._intermediateRendering=!0,e.Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var s=0;s<this._renderTargets.length;s++){var a=this._renderTargets.data[s];if(a._shouldRender()){this._renderId++;var h=a.activeCamera&&a.activeCamera!==this.activeCamera;a.render(h,this.dumpNextRenderTargets)}}e.Tools.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._intermediateRendering=!1,this._renderId++,o=!0}var c=this._engine.getStencilBuffer(),l=!1;if(this.renderTargetsEnabled&&this.highlightLayers&&this.highlightLayers.length>0){this._intermediateRendering=!0;for(var u=0;u<this.highlightLayers.length;u++){var d=this.highlightLayers[u];if(d.shouldRender()&&(!d.camera||d.camera.cameraRigMode===e.Camera.RIG_MODE_NONE&&t===d.camera||d.camera.cameraRigMode!==e.Camera.RIG_MODE_NONE&&d.camera._rigCameras.indexOf(t)>-1)){l=!0;var a=d._mainTexture;a._shouldRender()&&(this._renderId++,a.render(!1,!1),o=!0)}}this._intermediateRendering=!1,this._renderId++}o&&i.restoreDefaultFramebuffer(),this._renderTargetsDuration.endMonitoring(!1),this.postProcessManager._prepareFrame(),this._renderDuration.beginMonitoring();var f,p;if(this.layers.length){for(i.setDepthBuffer(!1),f=0;f<this.layers.length;f++)p=this.layers[f],p.isBackground&&p.render();i.setDepthBuffer(!0)}e.Tools.StartPerformanceCounter("Main render"),l&&this._engine.setStencilBuffer(!0),this._renderingManager.render(null,null,!0,!0),l&&this._engine.setStencilBuffer(c),e.Tools.EndPerformanceCounter("Main render"),this._boundingBoxRenderer.render();for(var _=0;_<this._edgesRenderers.length;_++)this._edgesRenderers.data[_].render();if(this.lensFlaresEnabled){e.Tools.StartPerformanceCounter("Lens flares",this.lensFlareSystems.length>0);for(var m=0;m<this.lensFlareSystems.length;m++){var g=this.lensFlareSystems[m];0!==(t.layerMask&g.layerMask)&&g.render()}e.Tools.EndPerformanceCounter("Lens flares",this.lensFlareSystems.length>0)}if(this.layers.length){for(i.setDepthBuffer(!1),f=0;f<this.layers.length;f++)p=this.layers[f],p.isBackground||p.render();i.setDepthBuffer(!0)}if(l){i.setDepthBuffer(!1);for(var u=0;u<this.highlightLayers.length;u++)this.highlightLayers[u].shouldRender()&&this.highlightLayers[u].render();i.setDepthBuffer(!0)}this._renderDuration.endMonitoring(!1),this.postProcessManager._finalizeFrame(t.isIntermediate),this.activeCamera._updateFromScene(),this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera),e.Tools.EndPerformanceCounter("Rendering camera "+this.activeCamera.name)},i.prototype._processSubCameras=function(t){if(t.cameraRigMode===e.Camera.RIG_MODE_NONE)return void this._renderForCamera(t);for(var i=0;i<t._rigCameras.length;i++)this._renderForCamera(t._rigCameras[i]);this.activeCamera=t,this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix()),this.activeCamera._updateFromScene()},i.prototype._checkIntersections=function(){for(var t=0;t<this._meshesForIntersections.length;t++)for(var i=this._meshesForIntersections.data[t],r=0;r<i.actionManager.actions.length;r++){var n=i.actionManager.actions[r];if(n.trigger===e.ActionManager.OnIntersectionEnterTrigger||n.trigger===e.ActionManager.OnIntersectionExitTrigger){var o=n.getTriggerParameter(),s=o instanceof e.AbstractMesh?o:o.mesh,a=s.intersectsMesh(i,o.usePreciseIntersection),h=i._intersectionsInProgress.indexOf(s);a&&h===-1?n.trigger===e.ActionManager.OnIntersectionEnterTrigger?(n._executeCurrent(e.ActionEvent.CreateNew(i,null,s)),i._intersectionsInProgress.push(s)):n.trigger===e.ActionManager.OnIntersectionExitTrigger&&i._intersectionsInProgress.push(s):!a&&h>-1&&(n.trigger===e.ActionManager.OnIntersectionExitTrigger&&n._executeCurrent(e.ActionEvent.CreateNew(i,null,s)),i.actionManager.hasSpecificTrigger(e.ActionManager.OnIntersectionExitTrigger)&&n.trigger!==e.ActionManager.OnIntersectionExitTrigger||i._intersectionsInProgress.splice(h,1))}}},i.prototype.render=function(){this._lastFrameDuration.beginMonitoring(),this._particlesDuration.fetchNewFrame(),this._spritesDuration.fetchNewFrame(),this._activeParticles.fetchNewFrame(),this._renderDuration.fetchNewFrame(),this._renderTargetsDuration.fetchNewFrame(),this._evaluateActiveMeshesDuration.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this.getEngine().drawCallsPerfCounter.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),e.Tools.StartPerformanceCounter("Scene rendering"),this.actionManager&&this.actionManager.processTrigger(e.ActionManager.OnEveryFrameTrigger,null),this.simplificationQueue&&!this.simplificationQueue.running&&this.simplificationQueue.executeNext();var t=Math.max(i.MinDeltaTime,Math.min(this._engine.getDeltaTime(),i.MaxDeltaTime));this._animationRatio=.06*t,this._animate(),this._physicsEngine&&(e.Tools.StartPerformanceCounter("Physics"),this._physicsEngine._step(t/1e3),e.Tools.EndPerformanceCounter("Physics")),this.onBeforeRenderObservable.notifyObservers(this),this._renderTargetsDuration.beginMonitoring();var r=(e.Tools.Now,this.getEngine()),n=this.activeCamera;if(this.renderTargetsEnabled){e.Tools.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0);for(var o=0;o<this.customRenderTargets.length;o++){var s=this.customRenderTargets[o];if(s._shouldRender()){if(this._renderId++,this.activeCamera=s.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");r.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),s.render(n!==this.activeCamera,this.dumpNextRenderTargets)}}e.Tools.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._renderId++}if(this.customRenderTargets.length>0&&r.restoreDefaultFramebuffer(),this._renderTargetsDuration.endMonitoring(),this.activeCamera=n,this.proceduralTexturesEnabled){e.Tools.StartPerformanceCounter("Procedural textures",this._proceduralTextures.length>0);for(var a=0;a<this._proceduralTextures.length;a++){var h=this._proceduralTextures[a];h._shouldRender()&&h.render()}e.Tools.EndPerformanceCounter("Procedural textures",this._proceduralTextures.length>0)}if(this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,!0,!0),this.shadowsEnabled)for(var c=0;c<this.lights.length;c++){var l=this.lights[c],u=l.getShadowGenerator();l.isEnabled()&&u&&u.getShadowMap().getScene().textures.indexOf(u.getShadowMap())!==-1&&this._renderTargets.push(u.getShadowMap())}if(this._depthRenderer&&this._renderTargets.push(this._depthRenderer.getDepthMap()),this.postProcessRenderPipelineManager.update(),this.activeCameras.length>0)for(var d=0;d<this.activeCameras.length;d++)d>0&&this._engine.clear(0,!1,!0,!0),this._processSubCameras(this.activeCameras[d]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections(),e.AudioEngine&&this._updateAudioParameters(),this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this);for(var f=0;f<this._toBeDisposed.length;f++)this._toBeDisposed.data[f].dispose(),this._toBeDisposed[f]=null;this._toBeDisposed.reset(),this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),e.Tools.EndPerformanceCounter("Scene rendering"),this._lastFrameDuration.endMonitoring(),this._totalMeshesCounter.addCount(this.meshes.length,!0),this._totalLightsCounter.addCount(this.lights.length,!0),this._totalMaterialsCounter.addCount(this.materials.length,!0),this._totalTexturesCounter.addCount(this.textures.length,!0),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0)},i.prototype._updateAudioParameters=function(){if(this.audioEnabled&&(0!==this.mainSoundTrack.soundCollection.length||1!==this.soundTracks.length)){var t,i=e.Engine.audioEngine;if(t=this.activeCameras.length>0?this.activeCameras[0]:this.activeCamera,t&&i.canUseWebAudio){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z);var r=e.Matrix.Invert(t.getViewMatrix()),n=e.Vector3.TransformNormal(new e.Vector3(0,0,(-1)),r);n.normalize(),i.audioContext.listener.setOrientation(n.x,n.y,n.z,0,1,0);var o;for(o=0;o<this.mainSoundTrack.soundCollection.length;o++){var s=this.mainSoundTrack.soundCollection[o];s.useCustomAttenuation&&s.updateDistanceFromListener()}for(o=0;o<this.soundTracks.length;o++)for(var a=0;a<this.soundTracks[o].soundCollection.length;a++)s=this.soundTracks[o].soundCollection[a],s.useCustomAttenuation&&s.updateDistanceFromListener()}}},Object.defineProperty(i.prototype,"audioEnabled",{get:function(){return this._audioEnabled},set:function(t){this._audioEnabled=t,e.AudioEngine&&(this._audioEnabled?this._enableAudio():this._disableAudio())},enumerable:!0,configurable:!0}),i.prototype._disableAudio=function(){var e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)this.mainSoundTrack.soundCollection[e].pause();for(e=0;e<this.soundTracks.length;e++)for(var t=0;t<this.soundTracks[e].soundCollection.length;t++)this.soundTracks[e].soundCollection[t].pause()},i.prototype._enableAudio=function(){var e;for(e=0;e<this.mainSoundTrack.soundCollection.length;e++)this.mainSoundTrack.soundCollection[e].isPaused&&this.mainSoundTrack.soundCollection[e].play();for(e=0;e<this.soundTracks.length;e++)for(var t=0;t<this.soundTracks[e].soundCollection.length;t++)this.soundTracks[e].soundCollection[t].isPaused&&this.soundTracks[e].soundCollection[t].play()},Object.defineProperty(i.prototype,"headphone",{get:function(){return this._headphone},set:function(t){this._headphone=t,e.AudioEngine&&(this._headphone?this._switchAudioModeForHeadphones():this._switchAudioModeForNormalSpeakers())},enumerable:!0,configurable:!0}),i.prototype._switchAudioModeForHeadphones=function(){this.mainSoundTrack.switchPanningModelToHRTF();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].switchPanningModelToHRTF()},i.prototype._switchAudioModeForNormalSpeakers=function(){this.mainSoundTrack.switchPanningModelToEqualPower();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].switchPanningModelToEqualPower()},i.prototype.enableDepthRenderer=function(){return this._depthRenderer?this._depthRenderer:(this._depthRenderer=new e.DepthRenderer(this),this._depthRenderer)},i.prototype.disableDepthRenderer=function(){this._depthRenderer&&(this._depthRenderer.dispose(),this._depthRenderer=null)},i.prototype.freezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].freeze()},i.prototype.unfreezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].unfreeze()},i.prototype.dispose=function(){this.beforeRender=null,this.afterRender=null,this.skeletons=[],this._boundingBoxRenderer.dispose(),this._depthRenderer&&this._depthRenderer.dispose(),this._debugLayer&&this._debugLayer.hide(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.detachControl(),e.AudioEngine&&this.disposeSounds();var t,i=this._engine.getRenderingCanvas();for(t=0;t<this.cameras.length;t++)this.cameras[t].detachControl(i);for(;this.lights.length;)this.lights[0].dispose();for(;this.meshes.length;)this.meshes[0].dispose(!0);for(;this.cameras.length;)this.cameras[0].dispose();for(;this.materials.length;)this.materials[0].dispose();for(;this.particleSystems.length;)this.particleSystems[0].dispose();for(;this.spriteManagers.length;)this.spriteManagers[0].dispose();for(;this.layers.length;)this.layers[0].dispose();for(;this.highlightLayers.length;)this.highlightLayers[0].dispose();for(;this.textures.length;)this.textures[0].dispose();this.postProcessManager.dispose(),this._physicsEngine&&this.disablePhysicsEngine(),t=this._engine.scenes.indexOf(this),t>-1&&this._engine.scenes.splice(t,1),this._engine.wipeCaches()},i.prototype.disposeSounds=function(){this.mainSoundTrack.dispose();for(var e=0;e<this.soundTracks.length;e++)this.soundTracks[e].dispose()},i.prototype.getWorldExtends=function(){for(var t=new e.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new e.Vector3((-Number.MAX_VALUE),(-Number.MAX_VALUE),(-Number.MAX_VALUE)),r=0;r<this.meshes.length;r++){var n=this.meshes[r];n.computeWorldMatrix(!0);var o=n.getBoundingInfo().boundingBox.minimumWorld,s=n.getBoundingInfo().boundingBox.maximumWorld;e.Tools.CheckExtends(o,t,i),e.Tools.CheckExtends(s,t,i)}return{min:t,max:i}},i.prototype.createOrUpdateSelectionOctree=function(t,i){void 0===t&&(t=64),void 0===i&&(i=2),this._selectionOctree||(this._selectionOctree=new e.Octree(e.Octree.CreationFuncForMeshes,t,i));var r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},i.prototype.createPickingRay=function(t,i,r,n,o){void 0===o&&(o=!1);var s=this._engine;if(!n){if(!this.activeCamera)throw new Error("Active camera not set");n=this.activeCamera}var a=n.viewport,h=a.toGlobal(s.getRenderWidth(),s.getRenderHeight());return t=t/this._engine.getHardwareScalingLevel()-h.x,i=i/this._engine.getHardwareScalingLevel()-(this._engine.getRenderHeight()-h.y-h.height),e.Ray.CreateNew(t,i,h.width,h.height,r?r:e.Matrix.Identity(),o?e.Matrix.Identity():n.getViewMatrix(),n.getProjectionMatrix())},i.prototype.createPickingRayInCameraSpace=function(t,i,r){var n=this._engine;if(!r){if(!this.activeCamera)throw new Error("Active camera not set");r=this.activeCamera}var o=r.viewport,s=o.toGlobal(n.getRenderWidth(),n.getRenderHeight()),a=e.Matrix.Identity();return t=t/this._engine.getHardwareScalingLevel()-s.x,i=i/this._engine.getHardwareScalingLevel()-(this._engine.getRenderHeight()-s.y-s.height),e.Ray.CreateNew(t,i,s.width,s.height,a,a,r.getProjectionMatrix())},i.prototype._internalPick=function(t,i,r){for(var n=null,o=0;o<this.meshes.length;o++){var s=this.meshes[o];if(i){if(!i(s))continue}else if(!s.isEnabled()||!s.isVisible||!s.isPickable)continue;var a=s.getWorldMatrix(),h=t(a),c=s.intersects(h,r);if(c&&c.hit&&(r||null==n||!(c.distance>=n.distance))&&(n=c,r))break}return n||new e.PickingInfo},i.prototype._internalMultiPick=function(e,t){for(var i=new Array,r=0;r<this.meshes.length;r++){var n=this.meshes[r];if(t){if(!t(n))continue}else if(!n.isEnabled()||!n.isVisible||!n.isPickable)continue;var o=n.getWorldMatrix(),s=e(o),a=n.intersects(s,!1);a&&a.hit&&i.push(a)}return i},i.prototype._internalPickSprites=function(t,i,r,n){var o=null;if(n=n||this.activeCamera,this.spriteManagers.length>0)for(var s=0;s<this.spriteManagers.length;s++){var a=this.spriteManagers[s];if(a.isPickable){var h=a.intersects(t,n,i,r);if(h&&h.hit&&(r||null==o||!(h.distance>=o.distance))&&(o=h,r))break}}return o||new e.PickingInfo},i.prototype.pick=function(e,t,i,r,n){var o=this;return this._internalPick((function(i){return o.createPickingRay(e,t,i,n)}),i,r)},i.prototype.pickSprite=function(e,t,i,r,n){return this._internalPickSprites(this.createPickingRayInCameraSpace(e,t,n),i,r,n)},i.prototype.pickWithRay=function(t,i,r){var n=this;return this._internalPick((function(i){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(n._pickWithRayInverseMatrix),e.Ray.Transform(t,n._pickWithRayInverseMatrix)}),i,r)},i.prototype.multiPick=function(e,t,i,r){var n=this;return this._internalMultiPick((function(i){return n.createPickingRay(e,t,i,r)}),i)},i.prototype.multiPickWithRay=function(t,i){var r=this;return this._internalMultiPick((function(i){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=e.Matrix.Identity()),i.invertToRef(r._pickWithRayInverseMatrix),e.Ray.Transform(t,r._pickWithRayInverseMatrix)}),i)},i.prototype.setPointerOverMesh=function(t){this._pointerOverMesh!==t&&(this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)),this._pointerOverMesh=t,this._pointerOverMesh&&this._pointerOverMesh.actionManager&&this._pointerOverMesh.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNew(this._pointerOverMesh)))},i.prototype.getPointerOverMesh=function(){return this._pointerOverMesh},i.prototype.setPointerOverSprite=function(t){this._pointerOverSprite!==t&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOutTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=t,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(e.ActionManager.OnPointerOverTrigger,e.ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},i.prototype.getPointerOverSprite=function(){return this._pointerOverSprite},i.prototype.getPhysicsEngine=function(){return this._physicsEngine},i.prototype.enablePhysics=function(t,i){if(this._physicsEngine)return!0;try{return this._physicsEngine=new e.PhysicsEngine(t,i),!0}catch(r){return e.Tools.Error(r.message),!1}},i.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=void 0)},i.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},i.prototype.setGravity=function(t){e.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'"),this._physicsEngine&&this._physicsEngine.setGravity(t)},i.prototype.createCompoundImpostor=function(t,i){e.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child"),t.parts&&(i=t,t=t.parts);var r=t[0].mesh;r.physicsImpostor=new e.PhysicsImpostor(r,t[0].impostor,i,this);for(var n=1;n<t.length;n++){var o=t[n].mesh;o.parent!==r&&(o.position=o.position.subtract(r.position),o.parent=r),o.physicsImpostor=new e.PhysicsImpostor(o,t[n].impostor,i,this)}r.physicsImpostor.forceUpdate()},i.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor.dispose(),t.physicsImpostor=null},i.prototype.createDefaultCameraOrLight=function(){if(0===this.lights.length&&new e.HemisphericLight("default light",e.Vector3.Up(),this),!this.activeCamera){var t=new e.FreeCamera("default camera",e.Vector3.Zero(),this),i=this.getWorldExtends(),r=i.min.add(i.max.subtract(i.min).scale(.5));t.position=new e.Vector3(r.x,r.y,i.min.z-(i.max.z-i.min.z)),t.setTarget(r),this.activeCamera=t}},i.prototype._getByTags=function(t,i,r){if(void 0===i)return t;var n=[];r=r||function(e){};for(var o in t){var s=t[o];e.Tags.MatchesQuery(s,i)&&(n.push(s),r(s))}return n},i.prototype.getMeshesByTags=function(e,t){return this._getByTags(this.meshes,e,t)},i.prototype.getCamerasByTags=function(e,t){return this._getByTags(this.cameras,e,t)},i.prototype.getLightsByTags=function(e,t){return this._getByTags(this.lights,e,t)},i.prototype.getMaterialByTags=function(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t)},i._FOGMODE_NONE=0,i._FOGMODE_EXP=1,i._FOGMODE_EXP2=2,i._FOGMODE_LINEAR=3,i.MinDeltaTime=1,i.MaxDeltaTime=1e3,i})();e.Scene=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s){t instanceof e.Mesh?this._engine=t.getScene().getEngine():this._engine=t,this._updatable=r,this._data=i,this._strideSize=n,o||this.create(),this._instanced=s}return t.prototype.createVertexBuffer=function(t,i,r,n){return new e.VertexBuffer(this._engine,this,t,this._updatable,(!0),n?n:this._strideSize,this._instanced,i,r)},t.prototype.isUpdatable=function(){return this._updatable},t.prototype.getData=function(){return this._data},t.prototype.getBuffer=function(){return this._buffer},t.prototype.getStrideSize=function(){return this._strideSize},t.prototype.getIsInstanced=function(){return this._instanced},t.prototype.create=function(e){!e&&this._buffer||(e=e||this._data,this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))},t.prototype.update=function(e){this.create(e)},t.prototype.updateDirectly=function(e,t,i){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,t,i?i*this.getStrideSize():void 0),this._data=null)},t.prototype.dispose=function(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)},t})();e.Buffer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(i,r,n,o,s,a,h,c,l){if(!a)switch(n){case t.PositionKind:a=3;break;case t.NormalKind:a=3;break;case t.UVKind:case t.UV2Kind:case t.UV3Kind:case t.UV4Kind:case t.UV5Kind:case t.UV6Kind:a=2;break;case t.ColorKind:a=4;break;case t.MatricesIndicesKind:case t.MatricesIndicesExtraKind:a=4;break;case t.MatricesWeightsKind:case t.MatricesWeightsExtraKind:a=4}r instanceof e.Buffer?(a||(a=r.getStrideSize()),this._buffer=r,this._ownsBuffer=!1):(this._buffer=new e.Buffer(i,r,o,a,s,h),this._ownsBuffer=!0),this._stride=a,this._offset=c?c:0,this._size=l?l:a,this._kind=n}return t.prototype.getKind=function(){return this._kind},t.prototype.isUpdatable=function(){return this._buffer.isUpdatable()},t.prototype.getData=function(){return this._buffer.getData()},t.prototype.getBuffer=function(){return this._buffer.getBuffer()},t.prototype.getStrideSize=function(){return this._stride},t.prototype.getOffset=function(){return this._offset},t.prototype.getSize=function(){return this._size},t.prototype.getIsInstanced=function(){return this._buffer.getIsInstanced()},t.prototype.create=function(e){return this._buffer.create(e)},t.prototype.update=function(e){return this._buffer.update(e)},t.prototype.updateDirectly=function(e,t){return this._buffer.updateDirectly(e,t)},t.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose()},Object.defineProperty(t,"PositionKind",{get:function(){return t._PositionKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"NormalKind",{get:function(){return t._NormalKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UVKind",{get:function(){return t._UVKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV2Kind",{get:function(){return t._UV2Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV3Kind",{get:function(){return t._UV3Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV4Kind",{get:function(){return t._UV4Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV5Kind",{get:function(){return t._UV5Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"UV6Kind",{get:function(){return t._UV6Kind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ColorKind",{get:function(){return t._ColorKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesIndicesKind",{get:function(){return t._MatricesIndicesKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesWeightsKind",{get:function(){return t._MatricesWeightsKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesIndicesExtraKind",{get:function(){return t._MatricesIndicesExtraKind},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MatricesWeightsExtraKind",{get:function(){return t._MatricesWeightsExtraKind},enumerable:!0,configurable:!0}),t._PositionKind="position",t._NormalKind="normal",t._UVKind="uv",t._UV2Kind="uv2",t._UV3Kind="uv3",t._UV4Kind="uv4",t._UV5Kind="uv5",t._UV6Kind="uv6",t._ColorKind="color",t._MatricesIndicesKind="matricesIndices",t._MatricesWeightsKind="matricesWeights",t._MatricesIndicesExtraKind="matricesIndicesExtra",t._MatricesWeightsExtraKind="matricesWeightsExtra",t})();e.VertexBuffer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i){t.call(this,e,i.getScene()),i.instances.push(this),this._sourceMesh=i,this.position.copyFrom(i.position),this.rotation.copyFrom(i.rotation),this.scaling.copyFrom(i.scaling),i.rotationQuaternion&&(this.rotationQuaternion=i.rotationQuaternion.clone()),this.infiniteDistance=i.infiniteDistance,this.setPivotMatrix(i.getPivotMatrix()),
this.refreshBoundingInfo(),this._syncSubMeshes()}return __extends(i,t),Object.defineProperty(i.prototype,"receiveShadows",{get:function(){return this._sourceMesh.receiveShadows},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._sourceMesh.material},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"visibility",{get:function(){return this._sourceMesh.visibility},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"skeleton",{get:function(){return this._sourceMesh.skeleton},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"renderingGroupId",{get:function(){return this._sourceMesh.renderingGroupId},enumerable:!0,configurable:!0}),i.prototype.getTotalVertices=function(){return this._sourceMesh.getTotalVertices()},Object.defineProperty(i.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!0,configurable:!0}),i.prototype.getVerticesData=function(e,t){return this._sourceMesh.getVerticesData(e,t)},i.prototype.isVerticesDataPresent=function(e){return this._sourceMesh.isVerticesDataPresent(e)},i.prototype.getIndices=function(){return this._sourceMesh.getIndices()},Object.defineProperty(i.prototype,"_positions",{get:function(){return this._sourceMesh._positions},enumerable:!0,configurable:!0}),i.prototype.refreshBoundingInfo=function(){var t=this._sourceMesh.getBoundingInfo();this._boundingInfo=new e.BoundingInfo(t.minimum.clone(),t.maximum.clone()),this._updateBoundingInfo()},i.prototype._preActivate=function(){this._currentLOD&&this._currentLOD._preActivate()},i.prototype._activate=function(e){this._currentLOD&&this._currentLOD._registerInstanceForRenderId(this,e)},i.prototype.getLOD=function(e){return this._currentLOD=this.sourceMesh.getLOD(this.getScene().activeCamera,this.getBoundingInfo().boundingSphere),this._currentLOD===this.sourceMesh?this:this._currentLOD},i.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh)},i.prototype._generatePointsArray=function(){return this._sourceMesh._generatePointsArray()},i.prototype.clone=function(t,i,r){var n=this._sourceMesh.createInstance(t);if(e.Tools.DeepCopy(this,n,["name","subMeshes"],[]),this.refreshBoundingInfo(),i&&(n.parent=i),!r)for(var o=0;o<this.getScene().meshes.length;o++){var s=this.getScene().meshes[o];s.parent===this&&s.clone(s.name,n)}return n.computeWorldMatrix(!0),n},i.prototype.dispose=function(e){var i=this._sourceMesh.instances.indexOf(this);this._sourceMesh.instances.splice(i,1),t.prototype.dispose.call(this,e)},i})(e.AbstractMesh);e.InstancedMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=new Array}return e})();e._InstancesBatch=t;var i=(function(i){function r(n,o,s,a,h,c){if(void 0===s&&(s=null),void 0===c&&(c=!0),i.call(this,n,o),this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onBeforeDrawObservable=new e.Observable,this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this.instances=new Array,this._LODLevels=new Array,this._visibleInstances={},this._renderIdForInstances=new Array,this._batchCache=new t,this._instancesBufferSize=2048,this._sideOrientation=r._DEFAULTSIDE,this._areNormalsFrozen=!1,a){a._geometry&&a._geometry.applyToMesh(this),e.Tools.DeepCopy(a,this,["name","material","skeleton","instances","parent"],["_poseMatrix"]),this.parent=a.parent,this.setPivotMatrix(a.getPivotMatrix()),this.id=n+"."+a.id,this.material=a.material;var l;if(!h)for(l=0;l<o.meshes.length;l++){var u=o.meshes[l];if(u.parent===a){u.clone(n+"."+u.name,this,h)}}var d=this.getScene().getPhysicsEngine();if(c&&d){var f=d.getImpostorForPhysicsObject(a);f&&(this.physicsImpostor=f.clone(this))}for(l=0;l<o.particleSystems.length;l++){var p=o.particleSystems[l];p.emitter===a&&p.clone(p.name,this)}this.computeWorldMatrix(!0)}null!==s&&(this.parent=s)}return __extends(r,i),Object.defineProperty(r,"FRONTSIDE",{get:function(){return r._FRONTSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"BACKSIDE",{get:function(){return r._BACKSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"DOUBLESIDE",{get:function(){return r._DOUBLESIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"DEFAULTSIDE",{get:function(){return r._DEFAULTSIDE},enumerable:!0,configurable:!0}),Object.defineProperty(r,"NO_CAP",{get:function(){return r._NO_CAP},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_START",{get:function(){return r._CAP_START},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_END",{get:function(){return r._CAP_END},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CAP_ALL",{get:function(){return r._CAP_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"onBeforeDraw",{set:function(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)},enumerable:!0,configurable:!0}),r.prototype.toString=function(t){var r=i.prototype.toString.call(this,t);if(r+=", n vertices: "+this.getTotalVertices(),r+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(var n=0;n<this.animations.length;n++)r+=", animation[0]: "+this.animations[n].toString(t);return t&&(r+=", flat shading: "+(this._geometry?this.getVerticesData(e.VertexBuffer.PositionKind).length/3===this.getIndices().length?"YES":"NO":"UNKNOWN")),r},Object.defineProperty(r.prototype,"hasLODLevels",{get:function(){return this._LODLevels.length>0},enumerable:!0,configurable:!0}),r.prototype._sortLODLevels=function(){this._LODLevels.sort((function(e,t){return e.distance<t.distance?1:e.distance>t.distance?-1:0}))},r.prototype.addLODLevel=function(t,i){if(i&&i._masterMesh)return e.Tools.Warn("You cannot use a mesh as LOD level twice"),this;var r=new e.Internals.MeshLODLevel(t,i);return this._LODLevels.push(r),i&&(i._masterMesh=this),this._sortLODLevels(),this},r.prototype.getLODLevelAtDistance=function(e){for(var t=0;t<this._LODLevels.length;t++){var i=this._LODLevels[t];if(i.distance===e)return i.mesh}return null},r.prototype.removeLODLevel=function(e){for(var t=0;t<this._LODLevels.length;t++)this._LODLevels[t].mesh===e&&(this._LODLevels.splice(t,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this},r.prototype.getLOD=function(e,t){if(!this._LODLevels||0===this._LODLevels.length)return this;var i=(t?t:this.getBoundingInfo().boundingSphere).centerWorld.subtract(e.globalPosition).length();if(this._LODLevels[this._LODLevels.length-1].distance>i)return this.onLODLevelSelection&&this.onLODLevelSelection(i,this,this._LODLevels[this._LODLevels.length-1].mesh),this;for(var r=0;r<this._LODLevels.length;r++){var n=this._LODLevels[r];if(n.distance<i)return n.mesh&&(n.mesh._preActivate(),n.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)),this.onLODLevelSelection&&this.onLODLevelSelection(i,this,n.mesh),n.mesh}return this.onLODLevelSelection&&this.onLODLevelSelection(i,this,this),this},Object.defineProperty(r.prototype,"geometry",{get:function(){return this._geometry},enumerable:!0,configurable:!0}),r.prototype.getTotalVertices=function(){return this._geometry?this._geometry.getTotalVertices():0},r.prototype.getVerticesData=function(e,t){return this._geometry?this._geometry.getVerticesData(e,t):null},r.prototype.getVertexBuffer=function(e){if(this._geometry)return this._geometry.getVertexBuffer(e)},r.prototype.isVerticesDataPresent=function(e){return this._geometry?this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&this._delayInfo.indexOf(e)!==-1},r.prototype.getVerticesDataKinds=function(){if(!this._geometry){var e=[];return this._delayInfo&&this._delayInfo.forEach((function(t,i,r){e.push(t)})),e}return this._geometry.getVerticesDataKinds()},r.prototype.getTotalIndices=function(){return this._geometry?this._geometry.getTotalIndices():0},r.prototype.getIndices=function(e){return this._geometry?this._geometry.getIndices(e):[]},Object.defineProperty(r.prototype,"isBlocked",{get:function(){return null!==this._masterMesh&&void 0!==this._masterMesh},enumerable:!0,configurable:!0}),r.prototype.isReady=function(){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&i.prototype.isReady.call(this)},r.prototype.isDisposed=function(){return this._isDisposed},Object.defineProperty(r.prototype,"sideOrientation",{get:function(){return this._sideOrientation},set:function(e){this._sideOrientation=e},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"areNormalsFrozen",{get:function(){return this._areNormalsFrozen},enumerable:!0,configurable:!0}),r.prototype.freezeNormals=function(){this._areNormalsFrozen=!0},r.prototype.unfreezeNormals=function(){this._areNormalsFrozen=!1},Object.defineProperty(r.prototype,"overridenInstanceCount",{set:function(e){this._overridenInstanceCount=e},enumerable:!0,configurable:!0}),r.prototype._preActivate=function(){var e=this.getScene().getRenderId();this._preActivateId!==e&&(this._preActivateId=e,this._visibleInstances=null)},r.prototype._preActivateForIntermediateRendering=function(e){this._visibleInstances&&(this._visibleInstances.intermediateDefaultRenderId=e)},r.prototype._registerInstanceForRenderId=function(e,t){this._visibleInstances||(this._visibleInstances={},this._visibleInstances.defaultRenderId=t,this._visibleInstances.selfDefaultRenderId=this._renderId),this._visibleInstances[t]||(this._visibleInstances[t]=new Array),this._visibleInstances[t].push(e)},r.prototype.refreshBoundingInfo=function(){if(!this._boundingInfo.isLocked){var t=this.getVerticesData(e.VertexBuffer.PositionKind);if(t){var i=e.Tools.ExtractMinAndMax(t,0,this.getTotalVertices());this._boundingInfo=new e.BoundingInfo(i.minimum,i.maximum)}if(this.subMeshes)for(var r=0;r<this.subMeshes.length;r++)this.subMeshes[r].refreshBoundingInfo();this._updateBoundingInfo()}},r.prototype._createGlobalSubMesh=function(){var t=this.getTotalVertices();return t&&this.getIndices()?(this.releaseSubMeshes(),new e.SubMesh(0,0,t,0,this.getTotalIndices(),this)):null},r.prototype.subdivide=function(t){if(!(t<1)){for(var i=this.getTotalIndices(),r=i/t|0,n=0;r%3!==0;)r++;this.releaseSubMeshes();for(var o=0;o<t&&!(n>=i);o++)e.SubMesh.CreateFromIndices(0,n,Math.min(r,i-n),this),n+=r;this.synchronizeInstances()}},r.prototype.setVerticesData=function(t,i,r,n){if(this._geometry)this._geometry.setVerticesData(t,i,r,n);else{var o=new e.VertexData;o.set(i,t);var s=this.getScene();new e.Geometry(e.Geometry.RandomId(),s,o,r,this)}},r.prototype.setVerticesBuffer=function(t){if(!this._geometry){var i=this.getScene();new e.Geometry(e.Geometry.RandomId(),i).applyToMesh(this)}this._geometry.setVerticesBuffer(t)},r.prototype.updateVerticesData=function(e,t,i,r){this._geometry&&(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i))},r.prototype.updateVerticesDataDirectly=function(t,i,r,n){e.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3."),this._geometry&&(n?(this.makeGeometryUnique(),this.updateVerticesDataDirectly(t,i,r,!1)):this._geometry.updateVerticesDataDirectly(t,i,r))},r.prototype.updateMeshPositions=function(t,i){void 0===i&&(i=!0);var r=this.getVerticesData(e.VertexBuffer.PositionKind);if(t(r),this.updateVerticesData(e.VertexBuffer.PositionKind,r,!1,!1),i){var n=this.getIndices(),o=this.getVerticesData(e.VertexBuffer.NormalKind);e.VertexData.ComputeNormals(r,n,o),this.updateVerticesData(e.VertexBuffer.NormalKind,o,!1,!1)}},r.prototype.makeGeometryUnique=function(){if(this._geometry){var t=this._geometry,i=this._geometry.copy(e.Geometry.RandomId());t.releaseForMesh(this,!0),i.applyToMesh(this)}},r.prototype.setIndices=function(t,i){if(this._geometry)this._geometry.setIndices(t,i);else{var r=new e.VertexData;r.indices=t;var n=this.getScene();new e.Geometry(e.Geometry.RandomId(),n,r,(!1),this)}},r.prototype.toLeftHanded=function(){this._geometry&&this._geometry.toLeftHanded()},r.prototype._bind=function(t,i,r){var n,o=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(r){case e.Material.PointFillMode:n=null;break;case e.Material.WireFrameFillMode:n=t.getLinesIndexBuffer(this.getIndices(),o);break;default:case e.Material.TriangleFillMode:n=this._unIndexed?null:this._geometry.getIndexBuffer()}o.bindBuffers(this._geometry.getVertexBuffers(),n,i)},r.prototype._draw=function(t,i,r){if(this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){this.onBeforeDrawObservable.notifyObservers(this);var n=this.getScene().getEngine();switch(i){case e.Material.PointFillMode:n.drawPointClouds(t.verticesStart,t.verticesCount,r);break;case e.Material.WireFrameFillMode:this._unIndexed?n.drawUnIndexed(!1,t.verticesStart,t.verticesCount,r):n.draw(!1,0,r>0?t.linesIndexCount/2:t.linesIndexCount,r);break;default:this._unIndexed?n.drawUnIndexed(!0,t.verticesStart,t.verticesCount,r):n.draw(!0,t.indexStart,t.indexCount,r)}}},r.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},r.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},r.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},r.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},r.prototype._getInstancesRenderList=function(e){var t=this.getScene();if(this._batchCache.mustReturn=!1,this._batchCache.renderSelf[e]=this.isEnabled()&&this.isVisible,this._batchCache.visibleInstances[e]=null,this._visibleInstances){var i=t.getRenderId(),r=t._isInIntermediateRendering()?this._visibleInstances.intermediateDefaultRenderId:this._visibleInstances.defaultRenderId;this._batchCache.visibleInstances[e]=this._visibleInstances[i];var n=this._renderId;if(!this._batchCache.visibleInstances[e]&&r&&(this._batchCache.visibleInstances[e]=this._visibleInstances[r],i=Math.max(r,i),n=Math.max(this._visibleInstances.selfDefaultRenderId,i)),this._batchCache.visibleInstances[e]&&this._batchCache.visibleInstances[e].length){if(this._renderIdForInstances[e]===i)return this._batchCache.mustReturn=!0,this._batchCache;i!==n&&(this._batchCache.renderSelf[e]=!1)}this._renderIdForInstances[e]=i}return this._batchCache},r.prototype._renderWithInstances=function(t,i,r,n,o){for(var s=r.visibleInstances[t._id],a=s.length+1,h=16*a*4,c=this._instancesBufferSize,l=this._instancesBuffer;this._instancesBufferSize<h;)this._instancesBufferSize*=2;this._instancesData&&c==this._instancesBufferSize||(this._instancesData=new Float32Array(this._instancesBufferSize/4));var u=0,d=0,f=this.getWorldMatrix();if(r.renderSelf[t._id]&&(f.copyToArray(this._instancesData,u),u+=16,d++),s)for(var p=0;p<s.length;p++){var _=s[p];_.getWorldMatrix().copyToArray(this._instancesData,u),u+=16,d++}l&&c==this._instancesBufferSize?l.updateDirectly(this._instancesData,0,d):(l&&l.dispose(),l=new e.Buffer(o,this._instancesData,(!0),16,(!1),(!0)),this._instancesBuffer=l,this.setVerticesBuffer(l.createVertexBuffer("world0",0,4)),this.setVerticesBuffer(l.createVertexBuffer("world1",4,4)),this.setVerticesBuffer(l.createVertexBuffer("world2",8,4)),this.setVerticesBuffer(l.createVertexBuffer("world3",12,4))),o.bindBuffers(this.geometry.getVertexBuffers(),this.geometry.getIndexBuffer(),n),this._draw(t,i,d),o.unbindInstanceAttributes()},r.prototype._processRendering=function(e,t,i,r,n,o,s){var a=this.getScene(),h=a.getEngine();if(n)this._renderWithInstances(e,i,r,t,h);else if(r.renderSelf[e._id]&&(o&&o(!1,this.getWorldMatrix(),s),this._draw(e,i,this._overridenInstanceCount)),r.visibleInstances[e._id])for(var c=0;c<r.visibleInstances[e._id].length;c++){var l=r.visibleInstances[e._id][c],u=l.getWorldMatrix();o&&o(!0,u,s),this._draw(e,i)}},r.prototype.render=function(t,i){var r=this.getScene(),n=this._getInstancesRenderList(t._id);if(!n.mustReturn&&this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){this.onBeforeRenderObservable.notifyObservers(this);var o=r.getEngine(),s=null!==o.getCaps().instancedArrays&&null!==n.visibleInstances[t._id]&&void 0!==n.visibleInstances[t._id],a=t.getMaterial();if(a&&a.isReady(this,s)){var h=o.getDepthWrite();this.renderOutline&&(o.setDepthWrite(!1),r.getOutlineRenderer().render(t,n),o.setDepthWrite(h)),a._preBind();var c=a.getEffect(),l=r.forcePointsCloud?e.Material.PointFillMode:r.forceWireframe?e.Material.WireFrameFillMode:a.fillMode;this._bind(t,c,l);var u=this.getWorldMatrix();if(a.bind(u,this),i&&o.setAlphaMode(a.alphaMode),this._processRendering(t,c,l,n,s,this._onBeforeDraw,a),a.unbind(),this.renderOutline&&h&&(o.setDepthWrite(!0),o.setColorWrite(!1),r.getOutlineRenderer().render(t,n),o.setColorWrite(!0)),this.renderOverlay){var d=o.getAlphaMode();o.setAlphaMode(e.Engine.ALPHA_COMBINE),r.getOutlineRenderer().render(t,n,!0),o.setAlphaMode(d)}this.onAfterRenderObservable.notifyObservers(this)}}},r.prototype._onBeforeDraw=function(e,t,i){e&&i.bindOnlyWorldMatrix(t)},r.prototype.getEmittedParticleSystems=function(){for(var e=new Array,t=0;t<this.getScene().particleSystems.length;t++){var i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},r.prototype.getHierarchyEmittedParticleSystems=function(){var e=new Array,t=this.getDescendants();t.push(this);for(var i=0;i<this.getScene().particleSystems.length;i++){var r=this.getScene().particleSystems[i];t.indexOf(r.emitter)!==-1&&e.push(r)}return e},r.prototype._checkDelayState=function(){var t=this.getScene();this._geometry?this._geometry.load(t):this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(this,t))},r.prototype._queueLoad=function(t,i){var r=this;i._addPendingData(t);var n=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;e.Tools.LoadFile(this.delayLoadingFile,(function(t){t instanceof ArrayBuffer?r._delayLoadingFunction(t,r):r._delayLoadingFunction(JSON.parse(t),r),r.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,i._removePendingData(r)}),(function(){}),i.database,n)},r.prototype.isInFrustum=function(t){return this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING&&(!!i.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},r.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=0;t<i.length;t++)if(i[t].id===e)return void(this.material=i[t]);var r=this.getScene().multiMaterials;for(t=0;t<r.length;t++)if(r[t].id===e)return void(this.material=r[t])},r.prototype.getAnimatables=function(){var e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},r.prototype.bakeTransformIntoVertices=function(t){if(this.isVerticesDataPresent(e.VertexBuffer.PositionKind)){var i=this.subMeshes.splice(0);this._resetPointsArrayCache();var r,n=this.getVerticesData(e.VertexBuffer.PositionKind),o=[];for(r=0;r<n.length;r+=3)e.Vector3.TransformCoordinates(e.Vector3.FromArray(n,r),t).toArray(o,r);if(this.setVerticesData(e.VertexBuffer.PositionKind,o,this.getVertexBuffer(e.VertexBuffer.PositionKind).isUpdatable()),this.isVerticesDataPresent(e.VertexBuffer.NormalKind)){for(n=this.getVerticesData(e.VertexBuffer.NormalKind),o=[],r=0;r<n.length;r+=3)e.Vector3.TransformNormal(e.Vector3.FromArray(n,r),t).normalize().toArray(o,r);this.setVerticesData(e.VertexBuffer.NormalKind,o,this.getVertexBuffer(e.VertexBuffer.NormalKind).isUpdatable()),t.m[0]*t.m[5]*t.m[10]<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=i}}},r.prototype.bakeCurrentTransformIntoVertices=function(){this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=e.Quaternion.Identity()),this._worldMatrix=e.Matrix.Identity()},r.prototype._resetPointsArrayCache=function(){this._positions=null},r.prototype._generatePointsArray=function(){if(this._positions)return!0;this._positions=[];var t=this.getVerticesData(e.VertexBuffer.PositionKind);if(!t)return!1;for(var i=0;i<t.length;i+=3)this._positions.push(e.Vector3.FromArray(t,i));return!0},r.prototype.clone=function(e,t,i,n){return void 0===n&&(n=!0),new r(e,this.getScene(),t,this,i,n)},r.prototype.dispose=function(e){for(this._geometry&&this._geometry.releaseForMesh(this,!0),this._instancesBuffer&&(this._instancesBuffer.dispose(),this._instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(var t=this.getScene().highlightLayers,r=0;r<t.length;r++){var n=t[r];n&&(n.removeMesh(this),n.removeExcludedMesh(this))}i.prototype.dispose.call(this,e)},r.prototype.applyDisplacementMap=function(t,i,r,n){var o=this,s=this.getScene(),a=function(e){var t=document.createElement("canvas"),s=t.getContext("2d"),a=e.width,h=e.height;t.width=a,t.height=h,s.drawImage(e,0,0);var c=s.getImageData(0,0,a,h).data;o.applyDisplacementMapFromBuffer(c,a,h,i,r),n&&n(o)};e.Tools.LoadImage(t,a,(function(){}),s.database)},r.prototype.applyDisplacementMapFromBuffer=function(t,i,r,n,o){if(!this.isVerticesDataPresent(e.VertexBuffer.PositionKind)||!this.isVerticesDataPresent(e.VertexBuffer.NormalKind)||!this.isVerticesDataPresent(e.VertexBuffer.UVKind))return void e.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");for(var s=this.getVerticesData(e.VertexBuffer.PositionKind),a=this.getVerticesData(e.VertexBuffer.NormalKind),h=this.getVerticesData(e.VertexBuffer.UVKind),c=e.Vector3.Zero(),l=e.Vector3.Zero(),u=e.Vector2.Zero(),d=0;d<s.length;d+=3){e.Vector3.FromArrayToRef(s,d,c),e.Vector3.FromArrayToRef(a,d,l),e.Vector2.FromArrayToRef(h,d/3*2,u);var f=Math.abs(u.x)*i%i|0,p=Math.abs(u.y)*r%r|0,_=4*(f+p*i),m=t[_]/255,g=t[_+1]/255,v=t[_+2]/255,y=.3*m+.59*g+.11*v;l.normalize(),l.scaleInPlace(n+(o-n)*y),c=c.add(l),c.toArray(s,d)}e.VertexData.ComputeNormals(s,this.getIndices(),a),this.updateVerticesData(e.VertexBuffer.PositionKind,s),this.updateVerticesData(e.VertexBuffer.NormalKind,a)},r.prototype.convertToFlatShadedMesh=function(){var t,i,r=this.getVerticesDataKinds(),n=[],o=[],s=[],a=!1;for(t=0;t<r.length;t++){i=r[t];var h=this.getVertexBuffer(i);i!==e.VertexBuffer.NormalKind?(n[i]=h,o[i]=n[i].getData(),s[i]=[]):(a=h.isUpdatable(),r.splice(t,1),t--)}var c,l=this.subMeshes.slice(0),u=this.getIndices(),d=this.getTotalIndices();for(c=0;c<d;c++){var f=u[c];for(t=0;t<r.length;t++){i=r[t];for(var p=n[i].getStrideSize(),_=0;_<p;_++)s[i].push(o[i][f*p+_])}}var m=[],g=s[e.VertexBuffer.PositionKind];for(c=0;c<d;c+=3){u[c]=c,u[c+1]=c+1,u[c+2]=c+2;for(var v=e.Vector3.FromArray(g,3*c),y=e.Vector3.FromArray(g,3*(c+1)),x=e.Vector3.FromArray(g,3*(c+2)),b=v.subtract(y),A=x.subtract(y),T=e.Vector3.Normalize(e.Vector3.Cross(b,A)),E=0;E<3;E++)m.push(T.x),m.push(T.y),m.push(T.z)}for(this.setIndices(u),this.setVerticesData(e.VertexBuffer.NormalKind,m,a),t=0;t<r.length;t++)i=r[t],this.setVerticesData(i,s[i],n[i].isUpdatable());this.releaseSubMeshes();for(var P=0;P<l.length;P++){var S=l[P];new e.SubMesh(S.materialIndex,S.indexStart,S.indexCount,S.indexStart,S.indexCount,this)}this.synchronizeInstances()},r.prototype.convertToUnIndexedMesh=function(){var t,i,r=this.getVerticesDataKinds(),n=[],o=[],s=[];for(t=0;t<r.length;t++){i=r[t];var a=this.getVertexBuffer(i);n[i]=a,o[i]=n[i].getData(),s[i]=[]}var h,c=this.subMeshes.slice(0),l=this.getIndices(),u=this.getTotalIndices();for(h=0;h<u;h++){var d=l[h];for(t=0;t<r.length;t++){i=r[t];for(var f=n[i].getStrideSize(),p=0;p<f;p++)s[i].push(o[i][d*f+p])}}for(h=0;h<u;h+=3)l[h]=h,l[h+1]=h+1,l[h+2]=h+2;for(this.setIndices(l),t=0;t<r.length;t++)i=r[t],this.setVerticesData(i,s[i],n[i].isUpdatable());this.releaseSubMeshes();for(var _=0;_<c.length;_++){var m=c[_];new e.SubMesh(m.materialIndex,m.indexStart,m.indexCount,m.indexStart,m.indexCount,this)}this._unIndexed=!0,this.synchronizeInstances()},r.prototype.flipFaces=function(t){void 0===t&&(t=!1);var i,r=e.VertexData.ExtractFromMesh(this);if(t&&this.isVerticesDataPresent(e.VertexBuffer.NormalKind))for(i=0;i<r.normals.length;i++)r.normals[i]*=-1;var n;for(i=0;i<r.indices.length;i+=3)n=r.indices[i+1],r.indices[i+1]=r.indices[i+2],r.indices[i+2]=n;r.applyToMesh(this)},r.prototype.createInstance=function(t){return new e.InstancedMesh(t,this)},r.prototype.synchronizeInstances=function(){for(var e=0;e<this.instances.length;e++){var t=this.instances[e];t._syncSubMeshes()}},r.prototype.simplify=function(t,i,r,n){void 0===i&&(i=!0),void 0===r&&(r=e.SimplificationType.QUADRATIC),this.getScene().simplificationQueue.addTask({settings:t,parallelProcessing:i,mesh:this,simplificationType:r,successCallback:n})},r.prototype.optimizeIndices=function(t){for(var i=this,r=this.getIndices(),n=this.getVerticesData(e.VertexBuffer.PositionKind),o=[],s=0;s<n.length;s+=3)o.push(e.Vector3.FromArray(n,s));var a=[];e.AsyncLoop.SyncAsyncForLoop(o.length,40,(function(e){for(var t=o.length-1-e,i=o[t],r=0;r<t;++r){var n=o[r];if(i.equals(n)){a[t]=r;break}}}),(function(){for(var e=0;e<r.length;++e)r[e]=a[r[e]]||r[e];var n=i.subMeshes.slice(0);i.setIndices(r),i.subMeshes=n,t&&t(i)}))},r.Parse=function(t,i,n){var o=new r(t.name,i);if(o.id=t.id,e.Tags.AddTagsTo(o,t.tags),o.position=e.Vector3.FromArray(t.position),void 0!==t.metadata&&(o.metadata=t.metadata),t.rotationQuaternion?o.rotationQuaternion=e.Quaternion.FromArray(t.rotationQuaternion):t.rotation&&(o.rotation=e.Vector3.FromArray(t.rotation)),o.scaling=e.Vector3.FromArray(t.scaling),t.localMatrix?o.setPivotMatrix(e.Matrix.FromArray(t.localMatrix)):t.pivotMatrix&&o.setPivotMatrix(e.Matrix.FromArray(t.pivotMatrix)),o.setEnabled(t.isEnabled),o.isVisible=t.isVisible,o.infiniteDistance=t.infiniteDistance,o.showBoundingBox=t.showBoundingBox,o.showSubMeshesBoundingBox=t.showSubMeshesBoundingBox,void 0!==t.applyFog&&(o.applyFog=t.applyFog),void 0!==t.pickable&&(o.isPickable=t.pickable),void 0!==t.alphaIndex&&(o.alphaIndex=t.alphaIndex),o.receiveShadows=t.receiveShadows,o.billboardMode=t.billboardMode,void 0!==t.visibility&&(o.visibility=t.visibility),o.checkCollisions=t.checkCollisions,void 0!==t.isBlocker&&(o.isBlocker=t.isBlocker),o._shouldGenerateFlatShading=t.useFlatShading,t.freezeWorldMatrix&&(o._waitingFreezeWorldMatrix=t.freezeWorldMatrix),t.parentId&&(o._waitingParentId=t.parentId),void 0!==t.actions&&(o._waitingActions=t.actions),void 0!==t.overlayAlpha&&(o.overlayAlpha=t.overlayAlpha),void 0!==t.overlayColor&&(o.overlayColor=e.Color3.FromArray(t.overlayColor)),void 0!==t.renderOverlay&&(o.renderOverlay=t.renderOverlay),o.hasVertexAlpha=t.hasVertexAlpha,t.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+t.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(t.boundingBoxMinimum),e.Vector3.FromArray(t.boundingBoxMaximum)),t._binaryInfo&&(o._binaryInfo=t._binaryInfo),o._delayInfo=[],t.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),t.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),t.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),t.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),t.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),t.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),t.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),t.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),t.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.Geometry.ImportGeometry,e.SceneLoader.ForceFullSceneLoadingForIncremental&&o._checkDelayState()):e.Geometry.ImportGeometry(t,o),t.materialId?o.setMaterialByID(t.materialId):o.material=null,t.skeletonId>-1&&(o.skeleton=i.getLastSkeletonByID(t.skeletonId),t.numBoneInfluencers&&(o.numBoneInfluencers=t.numBoneInfluencers)),t.animations){for(var s=0;s<t.animations.length;s++){var a=t.animations[s];o.animations.push(e.Animation.Parse(a))}e.Node.ParseAnimationRanges(o,t,i)}if(t.autoAnimate&&i.beginAnimation(o,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),t.layerMask&&!isNaN(t.layerMask)?o.layerMask=Math.abs(parseInt(t.layerMask)):o.layerMask=268435455,t.physicsImpostor&&(o.physicsImpostor=new e.PhysicsImpostor(o,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},i)),t.instances)for(var h=0;h<t.instances.length;h++){var c=t.instances[h],l=o.createInstance(c.name);if(e.Tags.AddTagsTo(l,c.tags),l.position=e.Vector3.FromArray(c.position),c.parentId&&(l._waitingParentId=c.parentId),c.rotationQuaternion?l.rotationQuaternion=e.Quaternion.FromArray(c.rotationQuaternion):c.rotation&&(l.rotation=e.Vector3.FromArray(c.rotation)),l.scaling=e.Vector3.FromArray(c.scaling),l.checkCollisions=o.checkCollisions,t.animations){for(s=0;s<t.animations.length;s++)a=t.animations[s],l.animations.push(e.Animation.Parse(a));e.Node.ParseAnimationRanges(l,t,i)}}return o},r.CreateRibbon=function(t,i,r,n,o,s,a,h,c){return e.MeshBuilder.CreateRibbon(t,{pathArray:i,closeArray:r,closePath:n,offset:o,updatable:a,sideOrientation:h,instance:c},s)},r.CreateDisc=function(t,i,r,n,o,s){var a={radius:i,tessellation:r,sideOrientation:s,updatable:o};return e.MeshBuilder.CreateDisc(t,a,n)},r.CreateBox=function(t,i,r,n,o){var s={size:i,sideOrientation:o,updatable:n};return e.MeshBuilder.CreateBox(t,s,r)},r.CreateSphere=function(t,i,r,n,o,s){var a={segments:i,diameterX:r,diameterY:r,diameterZ:r,sideOrientation:s,updatable:o};return e.MeshBuilder.CreateSphere(t,a,n)},r.CreateCylinder=function(t,i,n,o,s,a,h,c,l){void 0!==h&&h instanceof e.Scene||(void 0!==h&&(l=c||r.DEFAULTSIDE,c=h),h=a,a=1);var u={height:i,diameterTop:n,diameterBottom:o,tessellation:s,subdivisions:a,sideOrientation:l,updatable:c};return e.MeshBuilder.CreateCylinder(t,u,h)},r.CreateTorus=function(t,i,r,n,o,s,a){var h={diameter:i,thickness:r,tessellation:n,sideOrientation:a,updatable:s};return e.MeshBuilder.CreateTorus(t,h,o)},r.CreateTorusKnot=function(t,i,r,n,o,s,a,h,c,l){var u={radius:i,tube:r,radialSegments:n,tubularSegments:o,p:s,q:a,sideOrientation:l,updatable:c};return e.MeshBuilder.CreateTorusKnot(t,u,h)},r.CreateLines=function(t,i,r,n,o){var s={points:i,updatable:n,instance:o};return e.MeshBuilder.CreateLines(t,s,r)},r.CreateDashedLines=function(t,i,r,n,o,s,a,h){var c={points:i,dashSize:r,gapSize:n,dashNb:o,updatable:a,instance:h};return e.MeshBuilder.CreateDashedLines(t,c,s)},r.ExtrudeShape=function(t,i,n,o,s,a,h,c,l,u){var d={shape:i,path:n,scale:o,rotation:s,cap:0===a?0:a||r.NO_CAP,sideOrientation:l,instance:u,updatable:c};return e.MeshBuilder.ExtrudeShape(t,d,h)},r.ExtrudeShapeCustom=function(t,i,n,o,s,a,h,c,l,u,d,f){var p={shape:i,path:n,scaleFunction:o,rotationFunction:s,ribbonCloseArray:a,ribbonClosePath:h,cap:0===c?0:c||r.NO_CAP,sideOrientation:d,instance:f,updatable:u};return e.MeshBuilder.ExtrudeShapeCustom(t,p,l)},r.CreateLathe=function(t,i,r,n,o,s,a){var h={shape:i,radius:r,tessellation:n,sideOrientation:a,updatable:s};return e.MeshBuilder.CreateLathe(t,h,o)},r.CreatePlane=function(t,i,r,n,o){var s={size:i,width:i,height:i,sideOrientation:o,updatable:n};return e.MeshBuilder.CreatePlane(t,s,r)},r.CreateGround=function(t,i,r,n,o,s){var a={width:i,height:r,subdivisions:n,updatable:s};return e.MeshBuilder.CreateGround(t,a,o)},r.CreateTiledGround=function(t,i,r,n,o,s,a,h,c){var l={xmin:i,zmin:r,xmax:n,zmax:o,subdivisions:s,precision:a,updatable:c};return e.MeshBuilder.CreateTiledGround(t,l,h)},r.CreateGroundFromHeightMap=function(t,i,r,n,o,s,a,h,c,l){var u={width:r,height:n,subdivisions:o,minHeight:s,maxHeight:a,updatable:c,onReady:l};return e.MeshBuilder.CreateGroundFromHeightMap(t,i,u,h)},r.CreateTube=function(t,i,r,n,o,s,a,h,c,l){var u={path:i,radius:r,tessellation:n,radiusFunction:o,arc:1,cap:s,updatable:h,sideOrientation:c,instance:l};return e.MeshBuilder.CreateTube(t,u,a)},r.CreatePolyhedron=function(t,i,r){return e.MeshBuilder.CreatePolyhedron(t,i,r)},r.CreateIcoSphere=function(t,i,r){
return e.MeshBuilder.CreateIcoSphere(t,i,r)},r.CreateDecal=function(t,i,r,n,o,s){var a={position:r,normal:n,size:o,angle:s};return e.MeshBuilder.CreateDecal(t,i,a)},r.prototype.setPositionsForCPUSkinning=function(){var t;return this._sourcePositions||(t=this.getVerticesData(e.VertexBuffer.PositionKind),this._sourcePositions=new Float32Array(t),this.getVertexBuffer(e.VertexBuffer.PositionKind).isUpdatable()||this.setVerticesData(e.VertexBuffer.PositionKind,t,!0)),this._sourcePositions},r.prototype.setNormalsForCPUSkinning=function(){var t;return this._sourceNormals||(t=this.getVerticesData(e.VertexBuffer.NormalKind),this._sourceNormals=new Float32Array(t),this.getVertexBuffer(e.VertexBuffer.NormalKind).isUpdatable()||this.setVerticesData(e.VertexBuffer.NormalKind,t,!0)),this._sourceNormals},r.prototype.applySkeleton=function(t){if(this.geometry&&this.geometry._softwareSkinningRenderId!=this.getScene().getRenderId()){if(this.geometry._softwareSkinningRenderId=this.getScene().getRenderId(),!this.isVerticesDataPresent(e.VertexBuffer.PositionKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.NormalKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind))return this;if(!this._sourcePositions){var i=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=i}this._sourceNormals||this.setNormalsForCPUSkinning();var r=this.getVerticesData(e.VertexBuffer.PositionKind);r instanceof Float32Array||(r=new Float32Array(r));var n=this.getVerticesData(e.VertexBuffer.NormalKind);n instanceof Float32Array||(n=new Float32Array(n));for(var o,s=this.getVerticesData(e.VertexBuffer.MatricesIndicesKind),a=this.getVerticesData(e.VertexBuffer.MatricesWeightsKind),h=this.numBoneInfluencers>4,c=h?this.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind):null,l=h?this.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind):null,u=t.getTransformMatrices(this),d=e.Vector3.Zero(),f=new e.Matrix,p=new e.Matrix,_=0,m=0;m<r.length;m+=3,_+=4){var g;for(o=0;o<4&&(g=a[_+o],g>0);o++)e.Matrix.FromFloat32ArrayToRefScaled(u,16*s[_+o],g,p),f.addToSelf(p);if(h)for(o=0;o<4&&(g=l[_+o],g>0);o++)e.Matrix.FromFloat32ArrayToRefScaled(u,16*c[_+o],g,p),f.addToSelf(p);e.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[m],this._sourcePositions[m+1],this._sourcePositions[m+2],f,d),d.toArray(r,m),e.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[m],this._sourceNormals[m+1],this._sourceNormals[m+2],f,d),d.toArray(n,m),f.reset()}return this.updateVerticesData(e.VertexBuffer.PositionKind,r),this.updateVerticesData(e.VertexBuffer.NormalKind,n),this}},r.MinMax=function(e){var t=null,i=null;return e.forEach((function(e,r,n){var o=e.getBoundingInfo().boundingBox;t?(t.MinimizeInPlace(o.minimumWorld),i.MaximizeInPlace(o.maximumWorld)):(t=o.minimumWorld,i=o.maximumWorld)})),{min:t,max:i}},r.Center=function(t){var i=t instanceof Array?e.Mesh.MinMax(t):t;return e.Vector3.Center(i.min,i.max)},r.MergeMeshes=function(t,i,n,o){void 0===i&&(i=!0);var s;if(!n){var a=0;for(s=0;s<t.length;s++)if(t[s]&&(a+=t[s].getTotalVertices(),a>65536))return e.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}var h,c,l;for(s=0;s<t.length;s++)t[s]&&(t[s].computeWorldMatrix(!0),c=e.VertexData.ExtractFromMesh(t[s],!0),c.transform(t[s].getWorldMatrix()),h?h.merge(c):(h=c,l=t[s]));if(o||(o=new r(l.name+"_merged",l.getScene())),h.applyToMesh(o),o.material=l.material,o.checkCollisions=l.checkCollisions,i)for(s=0;s<t.length;s++)t[s]&&t[s].dispose();return o},r._FRONTSIDE=0,r._BACKSIDE=1,r._DOUBLESIDE=2,r._DEFAULTSIDE=0,r._NO_CAP=0,r._CAP_START=1,r._CAP_END=2,r._CAP_ALL=3,r})(e.AbstractMesh);e.Mesh=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o,s,a){void 0===a&&(a=!0),this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=n,this._renderId=0,this._mesh=o,this._renderingMesh=s||o,o.subMeshes.push(this),this._trianglePlanes=[],this._id=o.subMeshes.length-1,a&&(this.refreshBoundingInfo(),o.computeWorldMatrix(!0))}return Object.defineProperty(t.prototype,"IsGlobal",{get:function(){return 0===this.verticesStart&&this.verticesCount==this._mesh.getTotalVertices()},enumerable:!0,configurable:!0}),t.prototype.getBoundingInfo=function(){return this.IsGlobal?this._mesh.getBoundingInfo():this._boundingInfo},t.prototype.getMesh=function(){return this._mesh},t.prototype.getRenderingMesh=function(){return this._renderingMesh},t.prototype.getMaterial=function(){var t=this._renderingMesh.material;if(t&&t instanceof e.MultiMaterial){var i=t;return i.getSubMaterial(this.materialIndex)}return t?t:this._mesh.getScene().defaultMaterial},t.prototype.refreshBoundingInfo=function(){if(this._lastColliderWorldVertices=null,!this.IsGlobal){var t=this._renderingMesh.getVerticesData(e.VertexBuffer.PositionKind);if(!t)return void(this._boundingInfo=this._mesh._boundingInfo);var i,r=this._renderingMesh.getIndices();i=0===this.indexStart&&this.indexCount===r.length?{minimum:this._renderingMesh.getBoundingInfo().minimum.clone(),maximum:this._renderingMesh.getBoundingInfo().maximum.clone()}:e.Tools.ExtractMinAndMaxIndexed(t,r,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias),this._boundingInfo=new e.BoundingInfo(i.minimum,i.maximum)}},t.prototype._checkCollision=function(e){return this.getBoundingInfo()._checkCollision(e)},t.prototype.updateBoundingInfo=function(e){this.getBoundingInfo()||this.refreshBoundingInfo(),this.getBoundingInfo().update(e)},t.prototype.isInFrustum=function(e){return this.getBoundingInfo().isInFrustum(e)},t.prototype.isCompletelyInFrustum=function(e){return this.getBoundingInfo().isCompletelyInFrustum(e)},t.prototype.render=function(e){this._renderingMesh.render(this,e)},t.prototype.getLinesIndexBuffer=function(e,t){if(!this._linesIndexBuffer){for(var i=[],r=this.indexStart;r<this.indexStart+this.indexCount;r+=3)i.push(e[r],e[r+1],e[r+1],e[r+2],e[r+2],e[r]);this._linesIndexBuffer=t.createIndexBuffer(i),this.linesIndexCount=i.length}return this._linesIndexBuffer},t.prototype.canIntersects=function(e){return e.intersectsBox(this.getBoundingInfo().boundingBox)},t.prototype.intersects=function(t,i,r,n){var o=null;if(this._mesh instanceof e.LinesMesh)for(var s=this._mesh,a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){var h=i[r[a]],c=i[r[a+1]],l=t.intersectionSegment(h,c,s.intersectionThreshold);if(!(l<0)&&(n||!o||l<o.distance)&&(o=new e.IntersectionInfo(null,null,l),n))break}else for(var a=this.indexStart;a<this.indexStart+this.indexCount;a+=3){var h=i[r[a]],c=i[r[a+1]],u=i[r[a+2]],d=t.intersectsTriangle(h,c,u);if(d){if(d.distance<0)continue;if((n||!o||d.distance<o.distance)&&(o=d,o.faceId=a/3,n))break}}return o},t.prototype.clone=function(i,r){var n=new t(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,i,r,(!1));return this.IsGlobal||(n._boundingInfo=new e.BoundingInfo(this.getBoundingInfo().minimum,this.getBoundingInfo().maximum)),n},t.prototype.dispose=function(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);var e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1)},t.CreateFromIndices=function(e,i,r,n,o){var s=Number.MAX_VALUE,a=-Number.MAX_VALUE;o=o||n;for(var h=o.getIndices(),c=i;c<i+r;c++){var l=h[c];l<s&&(s=l),l>a&&(a=l)}return new t(e,s,a-s+1,i,r,n,o)},t})();e.SubMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.updateSideOrientation=function(t,i){return t==e.Mesh.DOUBLESIDE?e.Mesh.DOUBLESIDE:void 0===t||null===t?e.Mesh.FRONTSIDE:t},t.CreateBox=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateBox(i);return o.applyToMesh(n,i.updatable),n},t.CreateSphere=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateSphere(i);return o.applyToMesh(n,i.updatable),n},t.CreateDisc=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateDisc(i);return o.applyToMesh(n,i.updatable),n},t.CreateIcoSphere=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateIcoSphere(i);return o.applyToMesh(n,i.updatable),n},t.CreateRibbon=function(t,i,r){var n=i.pathArray,o=i.closeArray,s=i.closePath,a=(i.offset,this.updateSideOrientation(i.sideOrientation,r)),h=i.instance,c=i.updatable;if(h){e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,e.Tmp.Vector3[0]),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,e.Tmp.Vector3[1]);var l=function(t){for(var i=n[0].length,r=0,o=h.sideOrientation===e.Mesh.DOUBLESIDE?2:1,s=1;s<=o;s++)for(var a=0;a<n.length;a++){var c=n[a],l=c.length;i=i<l?i:l;for(var u=0;u<i;)t[r]=c[u].x,t[r+1]=c[u].y,t[r+2]=c[u].z,c[u].x<e.Tmp.Vector3[0].x&&(e.Tmp.Vector3[0].x=c[u].x),c[u].x>e.Tmp.Vector3[1].x&&(e.Tmp.Vector3[1].x=c[u].x),c[u].y<e.Tmp.Vector3[0].y&&(e.Tmp.Vector3[0].y=c[u].y),c[u].y>e.Tmp.Vector3[1].y&&(e.Tmp.Vector3[1].y=c[u].y),c[u].z<e.Tmp.Vector3[0].z&&(e.Tmp.Vector3[0].z=c[u].z),c[u].z>e.Tmp.Vector3[1].z&&(e.Tmp.Vector3[1].z=c[u].z),u++,r+=3;h._closePath&&(t[r]=c[0].x,t[r+1]=c[0].y,t[r+2]=c[0].z,r+=3)}},u=h.getVerticesData(e.VertexBuffer.PositionKind);if(l(u),h._boundingInfo=new e.BoundingInfo(e.Tmp.Vector3[0],e.Tmp.Vector3[1]),h._boundingInfo.update(h._worldMatrix),h.updateVerticesData(e.VertexBuffer.PositionKind,u,!1,!1),!h.areNormalsFrozen){var d=h.getIndices(),f=h.getVerticesData(e.VertexBuffer.NormalKind);if(e.VertexData.ComputeNormals(u,d,f),h._closePath)for(var p=0,_=0,m=0;m<n.length;m++)p=3*h._idx[m],_=m+1<n.length?3*(h._idx[m+1]-1):f.length-3,f[p]=.5*(f[p]+f[_]),f[p+1]=.5*(f[p+1]+f[_+1]),f[p+2]=.5*(f[p+2]+f[_+2]),f[_]=f[p],f[_+1]=f[p+1],f[_+2]=f[p+2];h.updateVerticesData(e.VertexBuffer.NormalKind,f,!1,!1)}return h}var g=new e.Mesh(t,r);g.sideOrientation=a;var v=e.VertexData.CreateRibbon(i);return s&&(g._idx=v._idx),g._closePath=s,g._closeArray=o,v.applyToMesh(g,c),g},t.CreateCylinder=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateCylinder(i);return o.applyToMesh(n,i.updatable),n},t.CreateTorus=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateTorus(i);return o.applyToMesh(n,i.updatable),n},t.CreateTorusKnot=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreateTorusKnot(i);return o.applyToMesh(n,i.updatable),n},t.CreateLineSystem=function(t,i,r){var n=i.instance,o=i.lines;if(n){var s=function(e){for(var t=0,i=0;i<o.length;i++)for(var r=o[i],n=0;n<r.length;n++)e[t]=r[n].x,e[t+1]=r[n].y,e[t+2]=r[n].z,t+=3};return n.updateMeshPositions(s,!1),n}var a=new e.LinesMesh(t,r),h=e.VertexData.CreateLineSystem(i);return h.applyToMesh(a,i.updatable),a},t.CreateLines=function(e,i,r){var n=t.CreateLineSystem(e,{lines:[i.points],updatable:i.updatable,instance:i.instance},r);return n},t.CreateDashedLines=function(t,i,r){var n=i.points,o=i.instance,s=i.gapSize,a=(i.dashNb,i.dashSize);if(o){var h=function(t){var i=e.Vector3.Zero(),r=t.length/6,s=0,a=0,h=0,c=0,l=0,u=0,d=0,f=0;for(d=0;d<n.length-1;d++)n[d+1].subtractToRef(n[d],i),s+=i.length();for(h=s/r,c=o.dashSize*h/(o.dashSize+o.gapSize),d=0;d<n.length-1;d++)for(n[d+1].subtractToRef(n[d],i),a=Math.floor(i.length()/h),i.normalize(),f=0;f<a&&u<t.length;)l=h*f,t[u]=n[d].x+l*i.x,t[u+1]=n[d].y+l*i.y,t[u+2]=n[d].z+l*i.z,t[u+3]=n[d].x+(l+c)*i.x,t[u+4]=n[d].y+(l+c)*i.y,t[u+5]=n[d].z+(l+c)*i.z,u+=6,f++;for(;u<t.length;)t[u]=n[d].x,t[u+1]=n[d].y,t[u+2]=n[d].z,u+=3};return o.updateMeshPositions(h,!1),o}var c=new e.LinesMesh(t,r),l=e.VertexData.CreateDashedLines(i);return l.applyToMesh(c,i.updatable),c.dashSize=a,c.gapSize=s,c},t.ExtrudeShape=function(i,r,n){var o=r.path,s=r.shape,a=r.scale||1,h=r.rotation||0,c=0===r.cap?0:r.cap||e.Mesh.NO_CAP,l=r.updatable,u=this.updateSideOrientation(r.sideOrientation,n),d=r.instance,f=r.invertUV||!1;return t._ExtrudeShapeGeneric(i,s,o,a,h,null,null,!1,!1,c,!1,n,l,u,d,f)},t.ExtrudeShapeCustom=function(i,r,n){var o=r.path,s=r.shape,a=r.scaleFunction||function(){return 1},h=r.rotationFunction||function(){return 0},c=r.ribbonCloseArray||!1,l=r.ribbonClosePath||!1,u=0===r.cap?0:r.cap||e.Mesh.NO_CAP,d=r.updatable,f=this.updateSideOrientation(r.sideOrientation,n),p=r.instance,_=r.invertUV||!1;return t._ExtrudeShapeGeneric(i,s,o,null,null,a,h,c,l,u,!0,n,d,f,p,_)},t.CreateLathe=function(i,r,n){var o,s=r.arc<=0||r.arc>1?1:r.arc||1,a=void 0===r.closed||r.closed,h=r.shape,c=r.radius||1,l=r.tessellation||64,u=r.updatable,d=this.updateSideOrientation(r.sideOrientation,n),f=r.cap||e.Mesh.NO_CAP,p=2*Math.PI,_=new Array,m=r.invertUV||!1,g=0,v=0,y=p/l*s,x=new Array;for(g=0;g<=l;g++){var x=[];for(f!=e.Mesh.CAP_START&&f!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(0,h[0].y,0)),x.push(new e.Vector3(Math.cos(g*y)*h[0].x*c,h[0].y,Math.sin(g*y)*h[0].x*c))),v=0;v<h.length;v++)o=new e.Vector3(Math.cos(g*y)*h[v].x*c,h[v].y,Math.sin(g*y)*h[v].x*c),x.push(o);f!=e.Mesh.CAP_END&&f!=e.Mesh.CAP_ALL||(x.push(new e.Vector3(Math.cos(g*y)*h[h.length-1].x*c,h[h.length-1].y,Math.sin(g*y)*h[h.length-1].x*c)),x.push(new e.Vector3(0,h[h.length-1].y,0))),_.push(x)}var b=t.CreateRibbon(i,{pathArray:_,closeArray:a,sideOrientation:d,updatable:u,invertUV:m},n);return b},t.CreatePlane=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreatePlane(i);if(o.applyToMesh(n,i.updatable),i.sourcePlane){n.translate(i.sourcePlane.normal,i.sourcePlane.d);var s=Math.acos(e.Vector3.Dot(i.sourcePlane.normal,e.Axis.Z)),a=e.Vector3.Cross(e.Axis.Z,i.sourcePlane.normal);n.rotate(a,s)}return n},t.CreateGround=function(t,i,r){var n=new e.GroundMesh(t,r);n._setReady(!1),n._subdivisionsX=i.subdivisionsX||i.subdivisions||1,n._subdivisionsY=i.subdivisionsY||i.subdivisions||1,n._width=i.width||1,n._height=i.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ;var o=e.VertexData.CreateGround(i);return o.applyToMesh(n,i.updatable),n._setReady(!0),n},t.CreateTiledGround=function(t,i,r){var n=new e.Mesh(t,r),o=e.VertexData.CreateTiledGround(i);return o.applyToMesh(n,i.updatable),n},t.CreateGroundFromHeightMap=function(t,i,r,n){var o=r.width||10,s=r.height||10,a=r.subdivisions||1,h=r.minHeight||0,c=r.maxHeight||10,l=r.updatable,u=r.onReady,d=new e.GroundMesh(t,n);d._subdivisionsX=a,d._subdivisionsY=a,d._width=o,d._height=s,d._maxX=d._width/2,d._maxZ=d._height/2,d._minX=-d._maxX,d._minZ=-d._maxZ,d._setReady(!1);var f=function(t){var i=document.createElement("canvas"),r=i.getContext("2d"),n=t.width,f=t.height;i.width=n,i.height=f,r.drawImage(t,0,0);var p=r.getImageData(0,0,n,f).data,_=e.VertexData.CreateGroundFromHeightMap({width:o,height:s,subdivisions:a,minHeight:h,maxHeight:c,buffer:p,bufferWidth:n,bufferHeight:f});_.applyToMesh(d,l),d._setReady(!0),u&&u(d)};return e.Tools.LoadImage(i,f,(function(){}),n.database),d},t.CreateTube=function(i,r,n){var o=r.path,s=r.radius||1,a=r.tessellation||64,h=r.radiusFunction,c=r.cap||e.Mesh.NO_CAP,l=r.invertUV||!1,u=r.updatable,d=this.updateSideOrientation(r.sideOrientation,n),f=r.instance;r.arc=r.arc<=0||r.arc>1?1:r.arc||1;var p,_,m=function(t,i,r,n,o,s,a,h){for(var c,l,u,d,f=i.getTangents(),p=i.getNormals(),_=i.getDistances(),m=2*Math.PI,g=m/o*h,v=function(){return n},y=s||v,x=e.Tmp.Matrix[0],b=a===e.Mesh._NO_CAP||a===e.Mesh.CAP_END?0:2,A=0;A<t.length;A++){l=y(A,_[A]),c=Array(),u=p[A];for(var T=0;T<o;T++)e.Matrix.RotationAxisToRef(f[A],g*T,x),d=c[T]?c[T]:e.Vector3.Zero(),e.Vector3.TransformCoordinatesToRef(u,x,d),d.scaleInPlace(l).addInPlace(t[A]),c[T]=d;r[b]=c,b++}var E=function(e,i){for(var r=Array(),n=0;n<e;n++)r.push(t[i]);return r};switch(a){case e.Mesh.NO_CAP:break;case e.Mesh.CAP_START:r[0]=E(o,0),r[1]=r[2].slice(0);break;case e.Mesh.CAP_END:r[b]=r[b-1].slice(0),r[b+1]=E(o,t.length-1);break;case e.Mesh.CAP_ALL:r[0]=E(o,0),r[1]=r[2].slice(0),r[b]=r[b-1].slice(0),r[b+1]=E(o,t.length-1)}return r};if(f){var g=r.arc||f.arc;return p=f.path3D.update(o),_=m(o,p,f.pathArray,s,f.tessellation,h,f.cap,g),f=t.CreateRibbon(null,{pathArray:_,instance:f}),f.path3D=p,f.pathArray=_,f.arc=g,f}p=new e.Path3D(o);var v=new Array;c=c<0||c>3?0:c,_=m(o,p,v,s,a,h,c,r.arc);var y=t.CreateRibbon(i,{pathArray:_,closePath:!0,closeArray:!1,updatable:u,sideOrientation:d,invertUV:l},n);return y.pathArray=_,y.path3D=p,y.tessellation=a,y.cap=c,y.arc=r.arc,y},t.CreatePolyhedron=function(t,i,r){var n=new e.Mesh(t,r);i.sideOrientation=this.updateSideOrientation(i.sideOrientation,r);var o=e.VertexData.CreatePolyhedron(i);return o.applyToMesh(n,i.updatable),n},t.CreateDecal=function(t,i,r){var n=i.getIndices(),o=i.getVerticesData(e.VertexBuffer.PositionKind),s=i.getVerticesData(e.VertexBuffer.NormalKind),a=r.position||e.Vector3.Zero(),h=r.normal||e.Vector3.Up(),c=r.size||new e.Vector3(1,1,1),l=r.angle||0;if(!h){var u=new e.Vector3(0,0,1),d=i.getScene().activeCamera,f=e.Vector3.TransformCoordinates(u,d.getWorldMatrix());h=d.globalPosition.subtract(f)}var p=-Math.atan2(h.z,h.x)-Math.PI/2,_=Math.sqrt(h.x*h.x+h.z*h.z),m=Math.atan2(h.y,_),g=e.Matrix.RotationYawPitchRoll(p,m,l).multiply(e.Matrix.Translation(a.x,a.y,a.z)),v=e.Matrix.Invert(g),y=i.getWorldMatrix(),x=y.multiply(v),b=new e.VertexData;b.indices=[],b.positions=[],b.normals=[],b.uvs=[];for(var A=0,T=function(t){var i=n[t],r=new e.PositionNormalVertex;return r.position=new e.Vector3(o[3*i],o[3*i+1],o[3*i+2]),r.position=e.Vector3.TransformCoordinates(r.position,x),r.normal=new e.Vector3(s[3*i],s[3*i+1],s[3*i+2]),r},E=function(t,i){if(0===t.length)return t;for(var r=.5*Math.abs(e.Vector3.Dot(c,i)),n=function(t,n){var o=e.Vector3.GetClipFactor(t.position,n.position,i,r);return new e.PositionNormalVertex(e.Vector3.Lerp(t.position,n.position,o),e.Vector3.Lerp(t.normal,n.normal,o))},o=new Array,s=0;s<t.length;s+=3){var a,h,l,u,d,f,p,_=0,m=e.Vector3.Dot(t[s].position,i)-r,g=e.Vector3.Dot(t[s+1].position,i)-r,v=e.Vector3.Dot(t[s+2].position,i)-r;switch(a=m>0,h=g>0,l=v>0,_=(a?1:0)+(h?1:0)+(l?1:0)){case 0:o.push(t[s]),o.push(t[s+1]),o.push(t[s+2]);break;case 1:if(a&&(u=t[s+1],d=t[s+2],f=n(t[s],u),p=n(t[s],d)),h){u=t[s],d=t[s+2],f=n(t[s+1],u),p=n(t[s+1],d),o.push(f),o.push(d.clone()),o.push(u.clone()),o.push(d.clone()),o.push(f.clone()),o.push(p);break}l&&(u=t[s],d=t[s+1],f=n(t[s+2],u),p=n(t[s+2],d)),o.push(u.clone()),o.push(d.clone()),o.push(f),o.push(p),o.push(f.clone()),o.push(d.clone());break;case 2:a||(u=t[s].clone(),d=n(u,t[s+1]),f=n(u,t[s+2]),o.push(u),o.push(d),o.push(f)),h||(u=t[s+1].clone(),d=n(u,t[s+2]),f=n(u,t[s]),o.push(u),o.push(d),o.push(f)),l||(u=t[s+2].clone(),d=n(u,t[s]),f=n(u,t[s+1]),o.push(u),o.push(d),o.push(f));break;case 3:}}return o},P=0;P<n.length;P+=3){var S=new Array;if(S.push(T(P)),S.push(T(P+1)),S.push(T(P+2)),S=E(S,new e.Vector3(1,0,0)),S=E(S,new e.Vector3((-1),0,0)),S=E(S,new e.Vector3(0,1,0)),S=E(S,new e.Vector3(0,(-1),0)),S=E(S,new e.Vector3(0,0,1)),S=E(S,new e.Vector3(0,0,(-1))),0!==S.length)for(var M=0;M<S.length;M++){var C=S[M];b.indices.push(A),C.position.toArray(b.positions,3*A),C.normal.toArray(b.normals,3*A),b.uvs.push(.5+C.position.x/c.x),b.uvs.push(.5+C.position.y/c.y),A++}}var R=new e.Mesh(t,i.getScene());return b.applyToMesh(R),R.position=a.clone(),R.rotation=new e.Vector3(m,p,l),R},t._ExtrudeShapeGeneric=function(i,r,n,o,s,a,h,c,l,u,d,f,p,_,m,g){var v,y,x=function(t,i,r,n,o,s,a,h,c,l){for(var u=r.getTangents(),d=r.getNormals(),f=r.getBinormals(),p=r.getDistances(),_=0,m=function(){return o},g=function(){return s},v=l?h:g,y=l?a:m,x=c===e.Mesh.NO_CAP||c===e.Mesh.CAP_END?0:2,b=e.Tmp.Matrix[0],A=0;A<i.length;A++){for(var T=new Array,E=v(A,p[A]),P=y(A,p[A]),S=0;S<t.length;S++){e.Matrix.RotationAxisToRef(u[A],_,b);var M=u[A].scale(t[S].z).add(d[A].scale(t[S].x)).add(f[A].scale(t[S].y)),C=T[S]?T[S]:e.Vector3.Zero();e.Vector3.TransformCoordinatesToRef(M,b,C),C.scaleInPlace(P).addInPlace(i[A]),T[S]=C}n[x]=T,_+=E,x++}var R=function(t){var i,r=Array(),n=e.Vector3.Zero();for(i=0;i<t.length;i++)n.addInPlace(t[i]);for(n.scaleInPlace(1/t.length),i=0;i<t.length;i++)r.push(n);return r};switch(c){case e.Mesh.NO_CAP:break;case e.Mesh.CAP_START:n[0]=R(n[2]),n[1]=n[2].slice(0);break;case e.Mesh.CAP_END:n[x]=n[x-1],n[x+1]=R(n[x-1]);break;case e.Mesh.CAP_ALL:n[0]=R(n[2]),n[1]=n[2].slice(0),n[x]=n[x-1],n[x+1]=R(n[x-1])}return n};if(m)return v=m.path3D.update(n),y=x(r,n,m.path3D,m.pathArray,o,s,a,h,m.cap,d),m=e.Mesh.CreateRibbon(null,y,null,null,null,f,null,null,m);v=new e.Path3D(n);var b=new Array;u=u<0||u>3?0:u,y=x(r,n,v,b,o,s,a,h,u,d);var A=t.CreateRibbon(i,{pathArray:y,closeArray:c,closePath:l,updatable:p,sideOrientation:_,invertUV:g},f);return A.pathArray=y,A.path3D=v,A.cap=u,A},t})();e.MeshBuilder=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.hasAlpha=!1,this.getAlphaFromRGB=!1,this.level=1,this.coordinatesIndex=0,this.coordinatesMode=e.Texture.EXPLICIT_MODE,this.wrapU=e.Texture.WRAP_ADDRESSMODE,this.wrapV=e.Texture.WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.isCube=!1,this.isRenderTarget=!1,this.animations=new Array,this.onDisposeObservable=new e.Observable,this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this._scene=t,this._scene.textures.push(this),this._uid=null}return Object.defineProperty(t.prototype,"uid",{get:function(){return this._uid||(this._uid=e.Tools.RandomId()),this._uid},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return this.name},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getTextureMatrix=function(){return null},t.prototype.getReflectionTextureMatrix=function(){return null},t.prototype.getInternalTexture=function(){return this._texture},t.prototype.isReady=function(){return this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED||!!this._texture&&this._texture.isReady},t.prototype.getSize=function(){return this._texture._width?new e.Size(this._texture._width,this._texture._height):this._texture._size?new e.Size(this._texture._size,this._texture._size):e.Size.Zero()},t.prototype.getBaseSize=function(){return this.isReady()&&this._texture?this._texture._size?new e.Size(this._texture._size,this._texture._size):new e.Size(this._texture._baseWidth,this._texture._baseHeight):e.Size.Zero()},t.prototype.scale=function(e){},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),t.prototype._removeFromCache=function(e,t){for(var i=this._scene.getEngine().getLoadedTexturesCache(),r=0;r<i.length;r++){var n=i[r];if(n.url===e&&n.noMipmap===t)return void i.splice(r,1)}},t.prototype._getFromCache=function(e,t,i){for(var r=this._scene.getEngine().getLoadedTexturesCache(),n=0;n<r.length;n++){var o=r[n];if(o.url===e&&o.noMipmap===t&&(!i||i===o.samplingMode))return o.references++,o}return null},t.prototype.delayLoad=function(){},t.prototype.clone=function(){return null},t.prototype.releaseInternalTexture=function(){this._texture&&(this._scene.getEngine().releaseInternalTexture(this._texture),delete this._texture)},t.prototype.dispose=function(){this.getScene().stopAnimation(this);var e=this._scene.textures.indexOf(this);e>=0&&this._scene.textures.splice(e,1),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())},t.prototype.serialize=function(){if(!this.name)return null;var t=e.SerializationHelper.Serialize(this);return e.Animation.AppendSerializedAnimations(this,t),t},__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"hasAlpha",void 0),__decorate([e.serialize()],t.prototype,"getAlphaFromRGB",void 0),__decorate([e.serialize()],t.prototype,"level",void 0),__decorate([e.serialize()],t.prototype,"coordinatesIndex",void 0),__decorate([e.serialize()],t.prototype,"coordinatesMode",void 0),__decorate([e.serialize()],t.prototype,"wrapU",void 0),__decorate([e.serialize()],t.prototype,"wrapV",void 0),__decorate([e.serialize()],t.prototype,"anisotropicFilteringLevel",void 0),__decorate([e.serialize()],t.prototype,"isCube",void 0),__decorate([e.serialize()],t.prototype,"isRenderTarget",void 0),t})();e.BaseTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a,h,c,l,u){var d=this;if(void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=i.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=null),void 0===c&&(c=null),void 0===l&&(l=null),void 0===u&&(u=!1),t.call(this,n),this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.name=r,this.url=r,this._noMipmap=o,this._invertY=s,this._samplingMode=a,this._buffer=l,this._deleteBuffer=u,r){this._texture=this._getFromCache(r,o,a);var f=function(){d._onLoadObservarble&&d._onLoadObservarble.hasObservers()&&d.onLoadObservable.notifyObservers(!0),h&&h()};this._texture?this._texture.isReady?e.Tools.SetImmediate((function(){return f()})):this._texture.onLoadedCallbacks.push(f):n.useDelayedTextureLoading?(this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=f,this._delayedOnError=c):(this._texture=n.getEngine().createTexture(r,o,s,n,this._samplingMode,f,c,this._buffer),u&&delete this._buffer)}}return __extends(i,t),Object.defineProperty(i.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!0,configurable:!0}),i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this._samplingMode),this._texture||(this._texture=this.getScene().getEngine().createTexture(this.url,this._noMipmap,this._invertY,this.getScene(),this._samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer),this._deleteBuffer&&delete this._buffer))},i.prototype.updateSamplingMode=function(e){this._texture&&(this._samplingMode=e,this.getScene().getEngine().updateTextureSamplingMode(e,this._texture))},i.prototype._prepareRowForTextureGeneration=function(t,i,r,n){t*=this.uScale,i*=this.vScale,t-=.5*this.uScale,i-=.5*this.vScale,r-=.5,e.Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,this._rowGenerationMatrix,n),n.x+=.5*this.uScale+this.uOffset,n.y+=.5*this.vScale+this.vOffset,n.z+=.5},i.prototype.getTextureMatrix=function(){return this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng?this._cachedTextureMatrix:(this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedTextureMatrix||(this._cachedTextureMatrix=e.Matrix.Zero(),this._rowGenerationMatrix=new e.Matrix,this._t0=e.Vector3.Zero(),this._t1=e.Vector3.Zero(),this._t2=e.Vector3.Zero()),e.Matrix.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),e.Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix.m[0]=this._t1.x,this._cachedTextureMatrix.m[1]=this._t1.y,this._cachedTextureMatrix.m[2]=this._t1.z,this._cachedTextureMatrix.m[4]=this._t2.x,this._cachedTextureMatrix.m[5]=this._t2.y,this._cachedTextureMatrix.m[6]=this._t2.z,this._cachedTextureMatrix.m[8]=this._t0.x,this._cachedTextureMatrix.m[9]=this._t0.y,this._cachedTextureMatrix.m[10]=this._t0.z,this._cachedTextureMatrix)},i.prototype.getReflectionTextureMatrix=function(){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.coordinatesMode===this._cachedCoordinatesMode)return this._cachedTextureMatrix;switch(this._cachedTextureMatrix||(this._cachedTextureMatrix=e.Matrix.Zero(),this._projectionModeMatrix=e.Matrix.Zero()),this._cachedCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case i.PLANAR_MODE:e.Matrix.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix[0]=this.uScale,this._cachedTextureMatrix[5]=this.vScale,this._cachedTextureMatrix[12]=this.uOffset,this._cachedTextureMatrix[13]=this.vOffset;break;case i.PROJECTION_MODE:e.Matrix.IdentityToRef(this._projectionModeMatrix),this._projectionModeMatrix.m[0]=.5,this._projectionModeMatrix.m[5]=-.5,this._projectionModeMatrix.m[10]=0,this._projectionModeMatrix.m[12]=.5,this._projectionModeMatrix.m[13]=.5,this._projectionModeMatrix.m[14]=1,this._projectionModeMatrix.m[15]=1,this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix,this._cachedTextureMatrix);break;default:e.Matrix.IdentityToRef(this._cachedTextureMatrix)}return this._cachedTextureMatrix},i.prototype.clone=function(){var t=this;return e.SerializationHelper.Clone((function(){return new i(t._texture.url,t.getScene(),t._noMipmap,t._invertY,t._samplingMode)}),this)},Object.defineProperty(i.prototype,"onLoadObservable",{get:function(){return this._onLoadObservarble||(this._onLoadObservarble=new e.Observable),this._onLoadObservarble},enumerable:!0,configurable:!0}),i.CreateFromBase64String=function(e,t,r,n,o,s,a,h){return void 0===s&&(s=i.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===h&&(h=null),new i("data:"+t,r,n,o,s,a,h,e)},i.Parse=function(t,r,n){if(t.customType){var o=e.Tools.Instantiate(t.customType);return o.Parse(t,r,n)}if(t.isCube)return e.CubeTexture.Parse(t,r,n);if(!t.name&&!t.isRenderTarget)return null;var s=e.SerializationHelper.Parse((function(){if(t.mirrorPlane){var o=new e.MirrorTexture(t.name,t.renderTargetSize,r);return o._waitingRenderList=t.renderList,o.mirrorPlane=e.Plane.FromArray(t.mirrorPlane),o}if(t.isRenderTarget){var s=new e.RenderTargetTexture(t.name,t.renderTargetSize,r);return s._waitingRenderList=t.renderList,s}var a;return a=t.base64String?i.CreateFromBase64String(t.base64String,t.name,r):new i(n+t.name,r)}),t,r);if(t.animations)for(var a=0;a<t.animations.length;a++){var h=t.animations[a];s.animations.push(e.Animation.Parse(h))}return s},i.LoadFromDataString=function(e,t,r,n,o,s,a,h,c){return void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=i.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=null),void 0===c&&(c=null),"data:"!==e.substr(0,5)&&(e="data:"+e),new i(e,r,o,s,a,h,c,t,n)},i.NEAREST_SAMPLINGMODE=1,i.BILINEAR_SAMPLINGMODE=2,i.TRILINEAR_SAMPLINGMODE=3,i.EXPLICIT_MODE=0,i.SPHERICAL_MODE=1,i.PLANAR_MODE=2,i.CUBIC_MODE=3,i.PROJECTION_MODE=4,i.SKYBOX_MODE=5,i.INVCUBIC_MODE=6,i.EQUIRECTANGULAR_MODE=7,i.FIXED_EQUIRECTANGULAR_MODE=8,i.CLAMP_ADDRESSMODE=0,i.WRAP_ADDRESSMODE=1,i.MIRROR_ADDRESSMODE=2,__decorate([e.serialize()],i.prototype,"url",void 0),__decorate([e.serialize()],i.prototype,"uOffset",void 0),__decorate([e.serialize()],i.prototype,"vOffset",void 0),__decorate([e.serialize()],i.prototype,"uScale",void 0),__decorate([e.serialize()],i.prototype,"vScale",void 0),__decorate([e.serialize()],i.prototype,"uAng",void 0),__decorate([e.serialize()],i.prototype,"vAng",void 0),__decorate([e.serialize()],i.prototype,"wAng",void 0),i})(e.BaseTexture);e.Texture=t;
})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){if(void 0===a&&(a=null),void 0===h&&(h=null),t.call(this,r),this.coordinatesMode=e.Texture.CUBIC_MODE,this.name=i,this.url=i,this._noMipmap=o,this.hasAlpha=!1,i||s){if(this._texture=this._getFromCache(i,o),!s){n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[];for(var c=0;c<n.length;c++)s.push(i+n[c]);this._extensions=n}this._files=s,this._texture?a&&(this._texture.isReady?e.Tools.SetImmediate((function(){return a()})):this._texture.onLoadedCallbacks.push(a)):r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this._texture=r.getEngine().createCubeTexture(i,r,s,o,a,h),this.isCube=!0,this._textureMatrix=e.Matrix.Identity()}}return __extends(i,t),i.CreateFromImages=function(e,t,r){return new i("",t,null,r,e)},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||(this._texture=this.getScene().getEngine().createCubeTexture(this.url,this.getScene(),this._files,this._noMipmap)))},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.Parse=function(t,i,r){var n=e.SerializationHelper.Parse((function(){return new e.CubeTexture(r+t.name,i,t.extensions)}),t,i);if(t.animations)for(var o=0;o<t.animations.length;o++){var s=t.animations[o];n.animations.push(e.Animation.Parse(s))}return n},i.prototype.clone=function(){var t=this;return e.SerializationHelper.Clone((function(){return new i(t.url,t.getScene(),t._extensions,t._noMipmap,t._files)}),this)},i})(e.BaseTexture);e.CubeTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c,l,u){void 0===s&&(s=!0),void 0===a&&(a=e.Engine.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=!0),void 0===u&&(u=!1),t.call(this,null,n,!o),this.isCube=h,this.renderList=new Array,this.renderParticles=!0,this.renderSprites=!1,this.coordinatesMode=e.Texture.PROJECTION_MODE,this.onAfterUnbindObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.onClearObservable=new e.Observable,this._currentRefreshId=-1,this._refreshRate=1,this.name=i,this.isRenderTarget=!0,this._size=r,this._generateMipMaps=o,this._doNotChangeAspectRatio=s,c===e.Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE),h?(this._texture=n.getEngine().createRenderTargetCubeTexture(r,{generateMipMaps:o,samplingMode:c,generateDepthBuffer:l,generateStencilBuffer:u}),this.coordinatesMode=e.Texture.INVCUBIC_MODE,this._textureMatrix=e.Matrix.Identity()):this._texture=n.getEngine().createRenderTargetTexture(r,{generateMipMaps:o,type:a,samplingMode:c,generateDepthBuffer:l,generateStencilBuffer:u}),this._renderingManager=new e.RenderingManager(n)}return __extends(i,t),Object.defineProperty(i,"REFRESHRATE_RENDER_ONCE",{get:function(){return i._REFRESHRATE_RENDER_ONCE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"REFRESHRATE_RENDER_ONEVERYFRAME",{get:function(){return i._REFRESHRATE_RENDER_ONEVERYFRAME},enumerable:!0,configurable:!0}),Object.defineProperty(i,"REFRESHRATE_RENDER_ONEVERYTWOFRAMES",{get:function(){return i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onAfterUnbind",{set:function(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"onClear",{set:function(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)},enumerable:!0,configurable:!0}),i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},i.prototype.isReady=function(){return!!this.getScene().renderTargetsEnabled&&t.prototype.isReady.call(this)},i.prototype.getRenderSize=function(){return this._size},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this._size*e;this.resize(t,this._generateMipMaps)},i.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:t.prototype.getReflectionTextureMatrix.call(this)},i.prototype.resize=function(e,t){this.releaseInternalTexture(),this.isCube?this._texture=this.getScene().getEngine().createRenderTargetCubeTexture(e):this._texture=this.getScene().getEngine().createRenderTargetTexture(e,t)},i.prototype.render=function(e,t){var i=this.getScene();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(!0)),this._waitingRenderList){this.renderList=[];for(var r=0;r<this._waitingRenderList.length;r++){var n=this._waitingRenderList[r];this.renderList.push(i.getMeshByID(n))}delete this._waitingRenderList}if(this.renderListPredicate){this.renderList.splice(0);for(var o=this.getScene().meshes,r=0;r<o.length;r++){var s=o[r];this.renderListPredicate(s)&&this.renderList.push(s)}}if(!this.renderList||0!==this.renderList.length){this._renderingManager.reset();for(var a=this.renderList?this.renderList:i.getActiveMeshes().data,h=this.renderList?this.renderList.length:i.getActiveMeshes().length,c=i.getRenderId(),l=0;l<h;l++){var s=a[l];if(s){if(!s.isReady()){this.resetRefreshCounter();continue}if(s._preActivateForIntermediateRendering(c),s.isEnabled()&&s.isVisible&&s.subMeshes&&0!==(s.layerMask&i.activeCamera.layerMask)){s._activate(c);for(var u=0;u<s.subMeshes.length;u++){var d=s.subMeshes[u];i._activeIndices.addCount(d.indexCount,!1),this._renderingManager.dispatch(d)}}}}if(this.isCube)for(var f=0;f<6;f++)this.renderToTarget(f,a,h,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this.renderToTarget(0,a,h,e,t);this.onAfterUnbindObservable.notifyObservers(this),this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),i.resetCachedMaterial()}},i.prototype.renderToTarget=function(t,i,r,n,o){var s=this.getScene(),a=s.getEngine();n&&s.postProcessManager._prepareFrame(this._texture)||(this.isCube?a.bindFramebuffer(this._texture,t):a.bindFramebuffer(this._texture)),this.onBeforeRenderObservable.notifyObservers(t),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):a.clear(s.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this._renderingManager.render(this.customRenderFunction,i,this.renderParticles,this.renderSprites),n&&s.postProcessManager._finalizeFrame(!1,this._texture,t),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0),this.onAfterRenderObservable.notifyObservers(t),o&&e.Tools.DumpFramebuffer(this._size,this._size,a),this.isCube&&5!==t||(this.isCube&&5===t&&a.generateMipMapsForCubemap(this._texture),a.unBindFramebuffer(this._texture,this.isCube))},i.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},i.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t)},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.renderList=this.renderList.slice(0),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);e.renderTargetSize=this.getRenderSize(),e.renderList=[];for(var i=0;i<this.renderList.length;i++)e.renderList.push(this.renderList[i].id);return e},i._REFRESHRATE_RENDER_ONCE=0,i._REFRESHRATE_RENDER_ONEVERYFRAME=1,i._REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,i})(e.Texture);e.RenderTargetTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){void 0===a&&(a=!0),void 0===h&&(h=!1),t.call(this,null,o,!a),this.isCube=h,this.isEnabled=!0,this._currentRefreshId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._textures=new Array,this._floats=new Array,this._floatsArrays={},this._colors3=new Array,this._colors4=new Array,this._vectors2=new Array,this._vectors3=new Array,this._matrices=new Array,this._fallbackTextureUsed=!1,o._proceduralTextures.push(this),this.name=i,this.isRenderTarget=!0,this._size=r,this._generateMipMaps=a,this.setFragment(n),this._fallbackTexture=s;var c=o.getEngine();h?(this._texture=c.createRenderTargetCubeTexture(r,{generateMipMaps:a}),this.setFloat("face",0)):this._texture=c.createRenderTargetTexture(r,a);var l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(c,l,e.VertexBuffer.PositionKind,(!1),(!1),2);var u=[];u.push(0),u.push(1),u.push(2),u.push(0),u.push(2),u.push(3),this._indexBuffer=c.createIndexBuffer(u)}return __extends(i,t),i.prototype.reset=function(){if(void 0!==this._effect){var e=this.getScene().getEngine();e._releaseEffect(this._effect)}},i.prototype.isReady=function(){var t,i=this,r=this.getScene().getEngine();return!!this._fragment&&(!!this._fallbackTextureUsed||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._effect=r.createEffect(t,[e.VertexBuffer.PositionKind],this._uniforms,this._samplers,"",null,null,(function(){i.releaseInternalTexture(),i._fallbackTexture&&(i._texture=i._fallbackTexture._texture,i._texture.references++),i._fallbackTextureUsed=!0})),this._effect.isReady()))},i.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},i.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(i.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!0,configurable:!0}),i.prototype._shouldRender=function(){return!!(this.isEnabled&&this.isReady()&&this._texture)&&(!this._fallbackTextureUsed&&(this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)))},i.prototype.getRenderSize=function(){return this._size},i.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this.getScene().getEngine().createRenderTargetTexture(e,t))},i.prototype._checkUniform=function(e){this._uniforms.indexOf(e)===-1&&this._uniforms.push(e)},i.prototype.setTexture=function(e,t){return this._samplers.indexOf(e)===-1&&this._samplers.push(e),this._textures[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.render=function(e){var t=this.getScene(),i=t.getEngine();i.enableEffect(this._effect),i.setState(!1);for(var r in this._textures)this._effect.setTexture(r,this._textures[r]);for(r in this._floats)this._effect.setFloat(r,this._floats[r]);for(r in this._floatsArrays)this._effect.setArray(r,this._floatsArrays[r]);for(r in this._colors3)this._effect.setColor3(r,this._colors3[r]);for(r in this._colors4){var n=this._colors4[r];this._effect.setFloat4(r,n.r,n.g,n.b,n.a)}for(r in this._vectors2)this._effect.setVector2(r,this._vectors2[r]);for(r in this._vectors3)this._effect.setVector3(r,this._vectors3[r]);for(r in this._matrices)this._effect.setMatrix(r,this._matrices[r]);if(i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this.isCube)for(var o=0;o<6;o++)i.bindFramebuffer(this._texture,o),this._effect.setFloat("face",o),i.clear(t.clearColor,!0,!0,!0),i.draw(!0,0,6),5===o&&i.generateMipMapsForCubemap(this._texture);else i.bindFramebuffer(this._texture),i.clear(t.clearColor,!0,!0,!0),i.draw(!0,0,6);i.unBindFramebuffer(this._texture,this.isCube),this.onGenerated&&this.onGenerated()},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t},i.prototype.dispose=function(){var i=this.getScene()._proceduralTextures.indexOf(this);i>=0&&this.getScene()._proceduralTextures.splice(i,1);var r=this._vertexBuffers[e.VertexBuffer.PositionKind];r&&(r.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&this.getScene().getEngine()._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),t.prototype.dispose.call(this)},i})(e.Texture);e.ProceduralTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,r,n,o,!0),this.mirrorPlane=new e.Plane(0,1,0,1),this._transformMatrix=e.Matrix.Zero(),this._mirrorMatrix=e.Matrix.Zero(),this.onBeforeRenderObservable.add((function(){e.Matrix.ReflectionToRef(s.mirrorPlane,s._mirrorMatrix),s._savedViewMatrix=n.getViewMatrix(),s._mirrorMatrix.multiplyToRef(s._savedViewMatrix,s._transformMatrix),n.setTransformMatrix(s._transformMatrix,n.getProjectionMatrix()),n.clipPlane=s.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=e.Vector3.TransformCoordinates(n.activeCamera.position,s._mirrorMatrix)})),this.onAfterRenderObservable.add((function(){n.setTransformMatrix(s._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,delete n.clipPlane}))}return __extends(i,t),i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.mirrorPlane=this.mirrorPlane.clone(),t.renderList=this.renderList.slice(0),t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.mirrorPlane.asArray(),e},i})(e.RenderTargetTexture);e.MirrorTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,r,n,o,!0),this.refractionPlane=new e.Plane(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((function(){n.clipPlane=s.refractionPlane})),this.onAfterRenderObservable.add((function(){delete n.clipPlane}))}return __extends(i,t),i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e.width,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.refractionPlane=this.refractionPlane.clone(),t.renderList=this.renderList.slice(0),t.depth=this.depth,t},i.prototype.serialize=function(){if(!this.name)return null;var e=t.prototype.serialize.call(this);return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e},i})(e.RenderTargetTexture);e.RefractionTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,n,!o),this.name=i,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=o,r.getContext?(this._canvas=r,this._texture=n.getEngine().createDynamicTexture(r.width,r.height,o,s)):(this._canvas=document.createElement("canvas"),r.width?this._texture=n.getEngine().createDynamicTexture(r.width,r.height,o,s):this._texture=n.getEngine().createDynamicTexture(r,r,o,s));var a=this.getSize();this._canvas.width=a.width,this._canvas.height=a.height,this._context=this._canvas.getContext("2d")}return __extends(i,t),Object.defineProperty(i.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),i.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._canvas.width=t.width,this._canvas.height=t.height,this.releaseInternalTexture(),this._texture=this.getScene().getEngine().createDynamicTexture(t.width,t.height,this._generateMipMaps,this._samplingMode)},i.prototype.getContext=function(){return this._context},i.prototype.clear=function(){var e=this.getSize();this._context.fillRect(0,0,e.width,e.height)},i.prototype.update=function(e){this.getScene().getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e)},i.prototype.drawText=function(e,t,i,r,n,o,s,a){void 0===a&&(a=!0);var h=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,h.width,h.height)),this._context.font=r,null===t){var c=this._context.measureText(e);t=(h.width-c.width)/2}this._context.fillStyle=n,this._context.fillText(e,t,i),a&&this.update(s)},i.prototype.clone=function(){var e=this.getSize(),t=new i(this.name,e,this.getScene(),this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t},i})(e.Texture);e.DynamicTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,n,!o,s),this._autoLaunch=!0;var c;this.name=i,r instanceof HTMLVideoElement?this.video=r:(c=r,this.video=document.createElement("video"),this.video.autoplay=!1,this.video.loop=!0),this._generateMipMaps=o,this._samplingMode=a,e.Tools.IsExponentOfTwo(this.video.videoWidth)&&e.Tools.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=e.Texture.WRAP_ADDRESSMODE,this.wrapV=e.Texture.WRAP_ADDRESSMODE):(this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),c?(this.video.addEventListener("canplaythrough",(function(){h._createTexture()})),c.forEach((function(e){var t=document.createElement("source");t.src=e,h.video.appendChild(t)}))):this._createTexture(),this._lastUpdate=e.Tools.Now}return __extends(i,t),i.prototype._createTexture=function(){this._texture=this.getScene().getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this._samplingMode),this._texture.isReady=!0},i.prototype.update=function(){this._autoLaunch&&(this._autoLaunch=!1,this.video.play());var t=e.Tools.Now;return!(t-this._lastUpdate<15||this.video.readyState!==this.video.HAVE_ENOUGH_DATA)&&(this._lastUpdate=t,this.getScene().getEngine().updateVideoTexture(this._texture,this.video,this._invertY),!0)},i})(e.Texture);e.VideoTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s){t.call(this,e,r,null,n,o,s),this._animate=!0,this._time=0,this._texturePath=i,this.loadJson(i),this.refreshRate=1}return __extends(i,t),i.prototype.loadJson=function(t){function i(){e.Tools.Log("No config file found in "+t+" trying to use ShadersStore or DOM element");try{n.setFragment(n._texturePath)}catch(i){e.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}}var r=this,n=this,o=t+"/config.json",s=new XMLHttpRequest;s.open("GET",o,!0),s.addEventListener("load",(function(){if(200===s.status||e.Tools.ValidateXHRData(s,1))try{r._config=JSON.parse(s.response),r.updateShaderUniforms(),r.updateTextures(),r.setFragment(r._texturePath+"/custom"),r._animate=r._config.animate,r.refreshRate=r._config.refreshrate}catch(t){i()}else i()}),!1),s.addEventListener("error",(function(){i()}),!1);try{s.send()}catch(a){e.Tools.Error("CustomProceduralTexture: Error on XHR send request.")}},i.prototype.isReady=function(){if(!t.prototype.isReady.call(this))return!1;for(var e in this._textures){var i=this._textures[e];if(!i.isReady())return!1}return!0},i.prototype.render=function(e){this._animate&&(this._time+=.03*this.getScene().getAnimationRatio(),this.updateShaderUniforms()),t.prototype.render.call(this,e)},i.prototype.updateTextures=function(){for(var t=0;t<this._config.sampler2Ds.length;t++)this.setTexture(this._config.sampler2Ds[t].sample2Dname,new e.Texture(this._texturePath+"/"+this._config.sampler2Ds[t].textureRelativeUrl,this.getScene()))},i.prototype.updateShaderUniforms=function(){if(this._config)for(var t=0;t<this._config.uniforms.length;t++){var i=this._config.uniforms[t];switch(i.type){case"float":this.setFloat(i.name,i.value);break;case"color3":this.setColor3(i.name,new e.Color3(i.r,i.g,i.b));break;case"color4":this.setColor4(i.name,new e.Color4(i.r,i.g,i.b,i.a));break;case"vector2":this.setVector2(i.name,new e.Vector2(i.x,i.y));break;case"vector3":this.setVector3(i.name,new e.Vector3(i.x,i.y,i.z))}}this.setFloat("time",this._time)},Object.defineProperty(i.prototype,"animate",{get:function(){return this._animate},set:function(e){this._animate=e},enumerable:!0,configurable:!0}),i})(e.ProceduralTexture);e.CustomProceduralTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._defines={},this._currentRank=32,this._maxRank=-1}return t.prototype.addFallback=function(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},t.prototype.addCPUSkinningFallback=function(e,t){this._meshRank=e,this._mesh=t,e>this._maxRank&&(this._maxRank=e)},Object.defineProperty(t.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),t.prototype.reduce=function(t){for(var i=this._defines[this._currentRank],r=0;r<i.length;r++)t=t.replace("#define "+i[r],"");return this._mesh&&this._currentRank===this._meshRank&&(this._mesh.computeBonesUsingShaders=!1,t=t.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),e.Tools.Log("Falling back to CPU skinning for "+this._mesh.name)),this._currentRank++,t},t})();e.EffectFallbacks=t;var i=(function(){function t(e,t,i,r,n,o,s,a,h,c){var l=this;this._isReady=!1,this._compilationError="",this._valueCache={},this._engine=n,this.name=e,this.defines=o,this._uniformsNames=i.concat(r),this._samplers=r,this._attributesNames=t,this.onError=h,this.onCompiled=a,this._indexParameters=c;var u,d;e.vertexElement?(u=document.getElementById(e.vertexElement),u||(u=e.vertexElement)):u=e.vertex||e,e.fragmentElement?(d=document.getElementById(e.fragmentElement),d||(d=e.fragmentElement)):d=e.fragment||e,this._loadVertexShader(u,(function(e){l._processIncludes(e,(function(e){l._loadFragmentShader(d,(function(i){l._processIncludes(i,(function(i){l._prepareEffect(e,i,t,o,s)}))}))}))}))}return t.prototype.isReady=function(){return this._isReady},t.prototype.getProgram=function(){return this._program},t.prototype.getAttributesNames=function(){return this._attributesNames},t.prototype.getAttributeLocation=function(e){return this._attributes[e]},t.prototype.getAttributeLocationByName=function(e){var t=this._attributesNames.indexOf(e);return this._attributes[t]},t.prototype.getAttributesCount=function(){return this._attributes.length},t.prototype.getUniformIndex=function(e){return this._uniformsNames.indexOf(e)},t.prototype.getUniform=function(e){return this._uniforms[this._uniformsNames.indexOf(e)]},t.prototype.getSamplers=function(){return this._samplers},t.prototype.getCompilationError=function(){return this._compilationError},t.prototype.getVertexShaderSource=function(){return this._engine.getVertexShaderSource(this._program)},t.prototype.getFragmentShaderSource=function(){return this._engine.getFragmentShaderSource(this._program)},t.prototype._loadVertexShader=function(i,r){if(i instanceof HTMLElement){var n=e.Tools.GetDOMTextContent(i);return void r(n)}if("base64:"===i.substr(0,7)){var o=window.atob(i.substr(7));return void r(o)}if(t.ShadersStore[i+"VertexShader"])return void r(t.ShadersStore[i+"VertexShader"]);var s;s="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,e.Tools.LoadFile(s+".vertex.fx",r)},t.prototype._loadFragmentShader=function(i,r){if(i instanceof HTMLElement){var n=e.Tools.GetDOMTextContent(i);return void r(n)}if("base64:"===i.substr(0,7)){var o=window.atob(i.substr(7));return void r(o)}if(t.ShadersStore[i+"PixelShader"])return void r(t.ShadersStore[i+"PixelShader"]);if(t.ShadersStore[i+"FragmentShader"])return void r(t.ShadersStore[i+"FragmentShader"]);var s;s="."===i[0]||"/"===i[0]||i.indexOf("http")>-1?i:e.Engine.ShadersRepository+i,e.Tools.LoadFile(s+".fragment.fx",r)},t.prototype._dumpShadersName=function(){this.name.vertexElement?(e.Tools.Error("Vertex shader:"+this.name.vertexElement),e.Tools.Error("Fragment shader:"+this.name.fragmentElement)):this.name.vertex?(e.Tools.Error("Vertex shader:"+this.name.vertex),e.Tools.Error("Fragment shader:"+this.name.fragment)):(e.Tools.Error("Vertex shader:"+this.name),e.Tools.Error("Fragment shader:"+this.name))},t.prototype._processIncludes=function(i,r){for(var n=this,o=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,s=o.exec(i),a=new String(i);null!=s;){var h=s[1];if(!t.IncludesShadersStore[h]){var c=e.Engine.ShadersRepository+"ShadersInclude/"+h+".fx";return void e.Tools.LoadFile(c,(function(e){t.IncludesShadersStore[h]=e,n._processIncludes(a,r)}))}var l=t.IncludesShadersStore[h];if(s[2])for(var u=s[3].split(","),d=0;d<u.length;d+=2){var f=new RegExp(u[d],"g"),p=u[d+1];l=l.replace(f,p)}if(s[4]){var _=s[5];if(_.indexOf("..")!==-1){var m=_.split(".."),g=parseInt(m[0]),v=parseInt(m[1]),y=l.slice(0);l="",isNaN(v)&&(v=this._indexParameters[m[1]]);for(var x=g;x<=v;x++)l+=y.replace(/\{X\}/g,x)+"\n"}else l=l.replace(/\{X\}/g,_)}a=a.replace(s[0],l),s=o.exec(i)}r(a)},t.prototype._processPrecision=function(e){return e.indexOf("precision highp float")===-1?e=this._engine.getCaps().highPrecisionShaderSupported?"precision highp float;\n"+e:"precision mediump float;\n"+e:this._engine.getCaps().highPrecisionShaderSupported||(e=e.replace("precision highp float","precision mediump float")),e},t.prototype._prepareEffect=function(t,i,r,n,o){try{var s=this._engine;t=this._processPrecision(t),i=this._processPrecision(i),this._program=s.createShaderProgram(t,i,n),this._uniforms=s.getUniforms(this._program,this._uniformsNames),this._attributes=s.getAttributes(this._program,r);var a;for(a=0;a<this._samplers.length;a++){var h=this.getUniform(this._samplers[a]);null==h&&(this._samplers.splice(a,1),a--)}s.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this)}catch(c){this._compilationError=c.message,e.Tools.Error("Unable to compile effect: "),e.Tools.Error("Defines: "+n),e.Tools.Error("Error: "+this._compilationError),this._dumpShadersName(),o&&o.isMoreFallbacks?(e.Tools.Error("Trying next fallback."),n=o.reduce(n),this._prepareEffect(t,i,r,n,o)):this.onError&&this.onError(this,this._compilationError)}},Object.defineProperty(t.prototype,"isSupported",{get:function(){return""===this._compilationError},enumerable:!0,configurable:!0}),t.prototype._bindTexture=function(e,t){this._engine._bindTexture(this._samplers.indexOf(e),t)},t.prototype.setTexture=function(e,t){this._engine.setTexture(this._samplers.indexOf(e),this.getUniform(e),t)},t.prototype.setTextureArray=function(e,t){if(this._samplers.indexOf(e+"Ex")===-1)for(var i=this._samplers.indexOf(e),r=1;r<t.length;r++)this._samplers.splice(i+r,0,e+"Ex");this._engine.setTextureArray(this._samplers.indexOf(e),this.getUniform(e),t)},t.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers.indexOf(e),t)},t.prototype._cacheMatrix=function(t,i){var r=!1,n=this._valueCache[t];n&&n instanceof e.Matrix||(r=!0,n=new e.Matrix);for(var o=n.m,s=i.m,a=0;a<16;a++)o[a]!==s[a]&&(o[a]=s[a],r=!0);return this._valueCache[t]=n,r},t.prototype._cacheFloat2=function(e,t,i){var r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;var n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n},t.prototype._cacheFloat3=function(e,t,i,r){var n=this._valueCache[e];if(!n)return n=[t,i,r],this._valueCache[e]=n,!0;var o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==r&&(n[2]=r,o=!0),o},t.prototype._cacheFloat4=function(e,t,i,r,n){var o=this._valueCache[e];if(!o)return o=[t,i,r,n],this._valueCache[e]=o,!0;var s=!1;return o[0]!==t&&(o[0]=t,s=!0),o[1]!==i&&(o[1]=i,s=!0),o[2]!==r&&(o[2]=r,s=!0),o[3]!==n&&(o[3]=n,s=!0),s},t.prototype.setIntArray=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray(this.getUniform(e),t),this},t.prototype.setIntArray2=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray2(this.getUniform(e),t),this},t.prototype.setIntArray3=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray3(this.getUniform(e),t),this},t.prototype.setIntArray4=function(e,t){return this._valueCache[e]=null,this._engine.setIntArray4(this.getUniform(e),t),this},t.prototype.setFloatArray=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray(this.getUniform(e),t),this},t.prototype.setFloatArray2=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray2(this.getUniform(e),t),this},t.prototype.setFloatArray3=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray3(this.getUniform(e),t),this},t.prototype.setFloatArray4=function(e,t){return this._valueCache[e]=null,this._engine.setFloatArray4(this.getUniform(e),t),this},t.prototype.setArray=function(e,t){return this._valueCache[e]=null,this._engine.setArray(this.getUniform(e),t),this},t.prototype.setArray2=function(e,t){return this._valueCache[e]=null,this._engine.setArray2(this.getUniform(e),t),this},t.prototype.setArray3=function(e,t){return this._valueCache[e]=null,this._engine.setArray3(this.getUniform(e),t),this},t.prototype.setArray4=function(e,t){return this._valueCache[e]=null,this._engine.setArray4(this.getUniform(e),t),this},t.prototype.setMatrices=function(e,t){return this._valueCache[e]=null,this._engine.setMatrices(this.getUniform(e),t),this},t.prototype.setMatrix=function(e,t){return this._cacheMatrix(e,t)&&this._engine.setMatrix(this.getUniform(e),t),this},t.prototype.setMatrix3x3=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix3x3(this.getUniform(e),t),this},t.prototype.setMatrix2x2=function(e,t){return this._valueCache[e]=null,this._engine.setMatrix2x2(this.getUniform(e),t),this},t.prototype.setFloat=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setFloat(this.getUniform(e),t),this)},t.prototype.setBool=function(e,t){var i=this._valueCache[e];return void 0!==i&&i===t?this:(this._valueCache[e]=t,this._engine.setBool(this.getUniform(e),t?1:0),
this)},t.prototype.setVector2=function(e,t){return this._cacheFloat2(e,t.x,t.y)&&this._engine.setFloat2(this.getUniform(e),t.x,t.y),this},t.prototype.setFloat2=function(e,t,i){return this._cacheFloat2(e,t,i)&&this._engine.setFloat2(this.getUniform(e),t,i),this},t.prototype.setVector3=function(e,t){return this._cacheFloat3(e,t.x,t.y,t.z)&&this._engine.setFloat3(this.getUniform(e),t.x,t.y,t.z),this},t.prototype.setFloat3=function(e,t,i,r){return this._cacheFloat3(e,t,i,r)&&this._engine.setFloat3(this.getUniform(e),t,i,r),this},t.prototype.setVector4=function(e,t){return this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&this._engine.setFloat4(this.getUniform(e),t.x,t.y,t.z,t.w),this},t.prototype.setFloat4=function(e,t,i,r,n){return this._cacheFloat4(e,t,i,r,n)&&this._engine.setFloat4(this.getUniform(e),t,i,r,n),this},t.prototype.setColor3=function(e,t){return this._cacheFloat3(e,t.r,t.g,t.b)&&this._engine.setColor3(this.getUniform(e),t),this},t.prototype.setColor4=function(e,t,i){return this._cacheFloat4(e,t.r,t.g,t.b,i)&&this._engine.setColor4(this.getUniform(e),t,i),this},t.ShadersStore={},t.IncludesShadersStore={},t})();e.Effect=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.PrepareDefinesForLights=function(t,i,r,n){void 0===n&&(n=4);for(var o=0,s=!1,a=!1,h=!1,c=!1,l=0;l<t.lights.length;l++){var u=t.lights[l];if(u.isEnabled()){if(u._excludedMeshesIds.length>0){for(var d=0;d<u._excludedMeshesIds.length;d++){var f=t.getMeshByID(u._excludedMeshesIds[d]);f&&u.excludedMeshes.push(f)}u._excludedMeshesIds=[]}if(u._includedOnlyMeshesIds.length>0){for(var p=0;p<u._includedOnlyMeshesIds.length;p++){var _=t.getMeshByID(u._includedOnlyMeshesIds[p]);_&&u.includedOnlyMeshes.push(_)}u._includedOnlyMeshesIds=[]}if(u.canAffectMesh(i)){s=!0,void 0===r["LIGHT"+o]&&(a=!0),r["LIGHT"+o]=!0;var m;if(m=u instanceof e.SpotLight?"SPOTLIGHT"+o:u instanceof e.HemisphericLight?"HEMILIGHT"+o:u instanceof e.PointLight?"POINTLIGHT"+o:"DIRLIGHT"+o,void 0===r[m]&&(a=!0),r[m]=!0,u.specular.equalsFloats(0,0,0)||void 0===r.SPECULARTERM||(r.SPECULARTERM=!0),t.shadowsEnabled){var g=u.getShadowGenerator();i&&i.receiveShadows&&g&&(void 0===r["SHADOW"+o]&&(a=!0),r["SHADOW"+o]=!0,r.SHADOWS=!0,(g.useVarianceShadowMap||g.useBlurVarianceShadowMap)&&(void 0===r["SHADOWVSM"+o]&&(a=!0),r["SHADOWVSM"+o]=!0),g.usePoissonSampling&&(void 0===r["SHADOWPCF"+o]&&(a=!0),r["SHADOWPCF"+o]=!0),h=!0)}if(u.lightmapMode!=e.Light.LIGHTMAP_DEFAULT&&(c=!0,void 0===r["LIGHTMAPEXCLUDED"+o]&&(a=!0),void 0===r["LIGHTMAPNOSPECULAR"+o]&&(a=!0),r["LIGHTMAPEXCLUDED"+o]=!0,u.lightmapMode==e.Light.LIGHTMAP_SHADOWSONLY&&(r["LIGHTMAPNOSPECULAR"+o]=!0)),o++,o===n)break}}}var v=t.getEngine().getCaps();return h&&v.textureFloat&&v.textureFloatLinearFiltering&&v.textureFloatRender&&(void 0===r.SHADOWFULLFLOAT&&(a=!0),r.SHADOWFULLFLOAT=!0),void 0===r.LIGHTMAPEXCLUDED&&(a=!0),c&&(r.LIGHTMAPEXCLUDED=!0),a&&r.rebuild(),s},t.PrepareUniformsAndSamplersList=function(e,t,i,r){void 0===r&&(r=4);for(var n=0;n<r&&i["LIGHT"+n];n++)e.push("vLightData"+n,"vLightDiffuse"+n,"vLightSpecular"+n,"vLightDirection"+n,"vLightGround"+n,"lightMatrix"+n,"shadowsInfo"+n),t.push("shadowSampler"+n)},t.HandleFallbacksForShadows=function(e,t,i){void 0===i&&(i=4);for(var r=0;r<i&&e["LIGHT"+r];r++)r>0&&t.addFallback(r,"LIGHT"+r),e["SHADOW"+r]&&t.addFallback(0,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(0,"SHADOWPCF"+r),e["SHADOWVSM"+r]&&t.addFallback(0,"SHADOWVSM"+r)},t.PrepareAttributesForBones=function(t,i,r,n){r.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,i),t.push(e.VertexBuffer.MatricesIndicesKind),t.push(e.VertexBuffer.MatricesWeightsKind),r.NUM_BONE_INFLUENCERS>4&&(t.push(e.VertexBuffer.MatricesIndicesExtraKind),t.push(e.VertexBuffer.MatricesWeightsExtraKind)))},t.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&(e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"))},t.BindLightShadow=function(e,t,i,r,n,o){var s=e.getShadowGenerator();return i.receiveShadows&&s&&(e.needCube()?o||(o=!0,n.setFloat2("depthValues",t.activeCamera.minZ,t.activeCamera.maxZ)):n.setMatrix("lightMatrix"+r,s.getTransformMatrix()),n.setTexture("shadowSampler"+r,s.getShadowMapForRendering()),n.setFloat3("shadowsInfo"+r,s.getDarkness(),s.blurScale/s.getShadowMap().getSize().width,s.bias)),o},t.BindLightProperties=function(t,i,r){t instanceof e.PointLight?t.transferToEffect(i,"vLightData"+r):t instanceof e.DirectionalLight?t.transferToEffect(i,"vLightData"+r):t instanceof e.SpotLight?t.transferToEffect(i,"vLightData"+r,"vLightDirection"+r):t instanceof e.HemisphericLight&&t.transferToEffect(i,"vLightData"+r,"vLightGround"+r)},t.BindLights=function(i,r,n,o,s){void 0===s&&(s=4);for(var a=0,h=!1,c=0;c<i.lights.length;c++){var l=i.lights[c];if(l.isEnabled()&&l.canAffectMesh(r)&&(t.BindLightProperties(l,n,a),l.diffuse.scaleToRef(l.intensity,e.Tmp.Color3[0]),n.setColor4("vLightDiffuse"+a,e.Tmp.Color3[0],l.range),o.SPECULARTERM&&(l.specular.scaleToRef(l.intensity,e.Tmp.Color3[1]),n.setColor3("vLightSpecular"+a,e.Tmp.Color3[1])),i.shadowsEnabled&&(h=this.BindLightShadow(l,i,r,a,n,h)),a++,a===s))break}},t.BindFogParameters=function(t,i,r){t.fogEnabled&&i.applyFog&&t.fogMode!==e.Scene.FOGMODE_NONE&&(r.setFloat4("vFogInfos",t.fogMode,t.fogStart,t.fogEnd,t.fogDensity),r.setColor3("vFogColor",t.fogColor))},t.BindBonesParameters=function(e,t){if(e&&e.useBones&&e.computeBonesUsingShaders){var i=e.skeleton.getTransformMatrices(e);i&&t.setMatrices("mBones",i)}},t.BindLogDepth=function(e,t,i){e.LOGARITHMICDEPTH&&t.setFloat("logarithmicDepthConstant",2/(Math.log(i.activeCamera.maxZ+1)/Math.LN2))},t.BindClipPlane=function(e,t){if(t.clipPlane){var i=t.clipPlane;e.setFloat4("vClipPlane",i.normal.x,i.normal.y,i.normal.z,i.d)}},t})();e.MaterialHelper=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.isEnabled=!0,this.leftColor=e.Color3.White(),this.rightColor=e.Color3.Black(),this.bias=0,this.power=1}return t.prototype.clone=function(){var i=new t;return e.Tools.DeepCopy(this,i),i},t.prototype.serialize=function(){var e={};return e.isEnabled=this.isEnabled,e.leftColor=this.leftColor,e.rightColor=this.rightColor,e.bias=this.bias,e.power=this.power,e},t.Parse=function(i){var r=new t;return r.isEnabled=i.isEnabled,r.leftColor=e.Color3.FromArray(i.leftColor),r.rightColor=e.Color3.FromArray(i.rightColor),r.bias=i.bias,r.power=i.power||1,r},t})();e.FresnelParameters=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e.prototype.rebuild=function(){this._keys&&delete this._keys,this._keys=Object.keys(this)},e.prototype.isEqual=function(e){if(this._keys.length!==e._keys.length)return!1;for(var t=0;t<this._keys.length;t++){var i=this._keys[t];if(this[i]!==e[i])return!1}return!0},e.prototype.cloneTo=function(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(var t=0;t<this._keys.length;t++){var i=this._keys[t];e[i]=this[i]}},e.prototype.reset=function(){for(var e=0;e<this._keys.length;e++){var t=this._keys[e];"number"==typeof this[t]?this[t]=0:this[t]=!1}},e.prototype.toString=function(){for(var e="",t=0;t<this._keys.length;t++){var i=this._keys[t];"number"==typeof this[i]?e+="#define "+i+" "+this[i]+"\n":this[i]&&(e+="#define "+i+"\n")}return e},e})();e.MaterialDefines=t;var i=(function(){function t(i,r,n){this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this.alpha=1,this.backFaceCulling=!0,this.doNotSerialize=!1,this.onDisposeObservable=new e.Observable,this.onBindObservable=new e.Observable,this.onUnBindObservable=new e.Observable,this.alphaMode=e.Engine.ALPHA_COMBINE,this.disableDepthWrite=!1,this.fogEnabled=!0,this.pointSize=1,this.zOffset=0,this._wasPreviouslyReady=!1,this._fillMode=t.TriangleFillMode,this.name=i,this.id=i,this._scene=r,r.useRightHandedSystem?this.sideOrientation=t.ClockWiseSideOrientation:this.sideOrientation=t.CounterClockWiseSideOrientation,n||r.materials.push(this)}return Object.defineProperty(t,"TriangleFillMode",{get:function(){return t._TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WireFrameFillMode",{get:function(){return t._WireFrameFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"PointFillMode",{get:function(){return t._PointFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ClockWiseSideOrientation",{get:function(){return t._ClockWiseSideOrientation},enumerable:!0,configurable:!0}),Object.defineProperty(t,"CounterClockWiseSideOrientation",{get:function(){return t._CounterClockWiseSideOrientation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBind",{set:function(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wireframe",{get:function(){return this._fillMode===t.WireFrameFillMode},set:function(e){this._fillMode=e?t.WireFrameFillMode:t.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pointsCloud",{get:function(){return this._fillMode===t.PointFillMode},set:function(e){this._fillMode=e?t.PointFillMode:t.TriangleFillMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fillMode",{get:function(){return this._fillMode},set:function(e){this._fillMode=e},enumerable:!0,configurable:!0}),t.prototype.toString=function(e){var t="Name: "+this.name;return t},Object.defineProperty(t.prototype,"isFrozen",{get:function(){return this.checkReadyOnlyOnce},enumerable:!0,configurable:!0}),t.prototype.freeze=function(){this.checkReadyOnlyOnce=!0},t.prototype.unfreeze=function(){this.checkReadyOnlyOnce=!1},t.prototype.isReady=function(e,t){return!0},t.prototype.getEffect=function(){return this._effect},t.prototype.getScene=function(){return this._scene},t.prototype.needAlphaBlending=function(){return this.alpha<1},t.prototype.needAlphaTesting=function(){return!1},t.prototype.getAlphaTestTexture=function(){return null},t.prototype.markDirty=function(){this._wasPreviouslyReady=!1},t.prototype._preBind=function(){var e=this._scene.getEngine(),i=this.sideOrientation===t.ClockWiseSideOrientation;e.enableEffect(this._effect),e.setState(this.backFaceCulling,this.zOffset,!1,i)},t.prototype.bind=function(e,t){if(this._scene._cachedMaterial=this,this.onBindObservable.notifyObservers(t),this.disableDepthWrite){var i=this._scene.getEngine();this._cachedDepthWriteState=i.getDepthWrite(),i.setDepthWrite(!1)}},t.prototype.bindOnlyWorldMatrix=function(e){},t.prototype.unbind=function(){if(this.onUnBindObservable.notifyObservers(this),this.disableDepthWrite){var e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}},t.prototype.clone=function(e){return null},t.prototype.getBindedMeshes=function(){for(var e=new Array,t=0;t<this._scene.meshes.length;t++){var i=this._scene.meshes[t];i.material===this&&e.push(i)}return e},t.prototype.dispose=function(e,t){this.getScene().stopAnimation(this);var i=this._scene.materials.indexOf(this);for(i>=0&&this._scene.materials.splice(i,1),e&&this._effect&&(this._scene.getEngine()._releaseEffect(this._effect),this._effect=null),i=0;i<this._scene.meshes.length;i++){var r=this._scene.meshes[i];r.material===this&&(r.material=null)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBindObservable.clear(),this.onUnBindObservable.clear()},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.ParseMultiMaterial=function(t,i){var r=new e.MultiMaterial(t.name,i);r.id=t.id,e.Tags.AddTagsTo(r,t.tags);for(var n=0;n<t.materials.length;n++){var o=t.materials[n];o?r.subMaterials.push(i.getMaterialByID(o)):r.subMaterials.push(null)}return r},t.Parse=function(t,i,r){if(!t.customType)return e.StandardMaterial.Parse(t,i,r);var n=e.Tools.Instantiate(t.customType);return n.Parse(t,i,r)},t._TriangleFillMode=0,t._WireFrameFillMode=1,t._PointFillMode=2,t._ClockWiseSideOrientation=0,t._CounterClockWiseSideOrientation=1,__decorate([e.serialize()],t.prototype,"id",void 0),__decorate([e.serialize()],t.prototype,"name",void 0),__decorate([e.serialize()],t.prototype,"checkReadyOnEveryCall",void 0),__decorate([e.serialize()],t.prototype,"checkReadyOnlyOnce",void 0),__decorate([e.serialize()],t.prototype,"state",void 0),__decorate([e.serialize()],t.prototype,"alpha",void 0),__decorate([e.serialize()],t.prototype,"backFaceCulling",void 0),__decorate([e.serialize()],t.prototype,"sideOrientation",void 0),__decorate([e.serialize()],t.prototype,"alphaMode",void 0),__decorate([e.serialize()],t.prototype,"disableDepthWrite",void 0),__decorate([e.serialize()],t.prototype,"fogEnabled",void 0),__decorate([e.serialize()],t.prototype,"pointSize",void 0),__decorate([e.serialize()],t.prototype,"zOffset",void 0),__decorate([e.serialize()],t.prototype,"wireframe",null),__decorate([e.serialize()],t.prototype,"pointsCloud",null),__decorate([e.serialize()],t.prototype,"fillMode",null),t})();e.Material=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(){e.call(this),this.DIFFUSE=!1,this.AMBIENT=!1,this.OPACITY=!1,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.SPECULAR=!1,this.BUMP=!1,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.ALPHATEST=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.INVERTNORMALMAPX=!1,this.INVERTNORMALMAPY=!1,this.SHADOWFULLFLOAT=!1,this.CAMERACOLORGRADING=!1,this.CAMERACOLORCURVES=!1,this.rebuild()}return __extends(t,e),t})(e.MaterialDefines),i=(function(i){function r(r,n){var o=this;i.call(this,r,n),this.ambientColor=new e.Color3(0,0,0),this.diffuseColor=new e.Color3(1,1,1),this.specularColor=new e.Color3(1,1,1),this.emissiveColor=new e.Color3(0,0,0),this.specularPower=64,this.useAlphaFromDiffuseTexture=!1,this.useEmissiveAsIllumination=!1,this.linkEmissiveWithDiffuse=!1,this.useReflectionFresnelFromSpecular=!1,this.useSpecularOverAlpha=!1,this.useReflectionOverAlpha=!1,this.disableLighting=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.useLightmapAsShadowmap=!1,this.useGlossinessFromSpecularMapAlpha=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.cameraColorGradingTexture=null,this.cameraColorCurves=null,this._renderTargets=new e.SmartArray(16),this._worldViewProjectionMatrix=e.Matrix.Zero(),this._globalAmbientColor=new e.Color3(0,0,0),this._defines=new t,this._cachedDefines=new t,this._cachedDefines.BonesPerMesh=-1,this.getRenderTargetTextures=function(){return o._renderTargets.reset(),o.reflectionTexture&&o.reflectionTexture.isRenderTarget&&o._renderTargets.push(o.reflectionTexture),o.refractionTexture&&o.refractionTexture.isRenderTarget&&o._renderTargets.push(o.refractionTexture),o._renderTargets}}return __extends(r,i),Object.defineProperty(r.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),r.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this.opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled},r.prototype.needAlphaTesting=function(){return null!=this.diffuseTexture&&this.diffuseTexture.hasAlpha},r.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this.diffuseTexture&&this.diffuseTexture.hasAlpha&&this.useAlphaFromDiffuseTexture},r.prototype.getAlphaTestTexture=function(){return this.diffuseTexture},r.prototype._checkCache=function(e,t,i){return!t||this._defines.INSTANCES===i&&!(!t._materialDefines||!t._materialDefines.isEqual(this._defines))},r.prototype.isReady=function(i,n){if(this.isFrozen&&this._wasPreviouslyReady)return!0;var o=this.getScene(),s=o.getEngine(),a=!1,h=!1;if(this._defines.reset(),o.lightsEnabled&&!this.disableLighting&&(h=e.MaterialHelper.PrepareDefinesForLights(o,i,this._defines,this.maxSimultaneousLights)),!this.checkReadyOnEveryCall&&this._renderId===o.getRenderId()&&this._checkCache(o,i,n))return!0;if(o.texturesEnabled){if(this.diffuseTexture&&r.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;a=!0,this._defines.DIFFUSE=!0}if(this.ambientTexture&&r.AmbientTextureEnabled){if(!this.ambientTexture.isReady())return!1;a=!0,this._defines.AMBIENT=!0}if(this.opacityTexture&&r.OpacityTextureEnabled){if(!this.opacityTexture.isReady())return!1;a=!0,this._defines.OPACITY=!0,this.opacityTexture.getAlphaFromRGB&&(this._defines.OPACITYRGB=!0)}if(this.reflectionTexture&&r.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady())return!1;switch(h=!0,this._defines.REFLECTION=!0,this.roughness>0&&(this._defines.ROUGHNESS=!0),this.useReflectionOverAlpha&&(this._defines.REFLECTIONOVERALPHA=!0),this.reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE&&(this._defines.INVERTCUBICMAP=!0),this._defines.REFLECTIONMAP_3D=this.reflectionTexture.isCube,this.reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:this._defines.REFLECTIONMAP_CUBIC=!0;break;case e.Texture.EXPLICIT_MODE:this._defines.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:this._defines.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:this._defines.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:this._defines.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:this._defines.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0}}if(this.emissiveTexture&&r.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady())return!1;a=!0,this._defines.EMISSIVE=!0}if(this.lightmapTexture&&r.LightmapTextureEnabled){if(!this.lightmapTexture.isReady())return!1;a=!0,this._defines.LIGHTMAP=!0,this._defines.USELIGHTMAPASSHADOWMAP=this.useLightmapAsShadowmap}if(this.specularTexture&&r.SpecularTextureEnabled){if(!this.specularTexture.isReady())return!1;a=!0,this._defines.SPECULAR=!0,this._defines.GLOSSINESS=this.useGlossinessFromSpecularMapAlpha}if(o.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&r.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;a=!0,this._defines.BUMP=!0,this.useParallax&&(this._defines.PARALLAX=!0,this.useParallaxOcclusion&&(this._defines.PARALLAXOCCLUSION=!0)),this.invertNormalMapX&&(this._defines.INVERTNORMALMAPX=!0),this.invertNormalMapY&&(this._defines.INVERTNORMALMAPY=!0)}if(this.refractionTexture&&r.RefractionTextureEnabled){if(!this.refractionTexture.isReady())return!1;a=!0,this._defines.REFRACTION=!0,this._defines.REFRACTIONMAP_3D=this.refractionTexture.isCube}if(this.cameraColorGradingTexture&&r.ColorGradingTextureEnabled){if(!this.cameraColorGradingTexture.isReady())return!1;this._defines.CAMERACOLORGRADING=!0}}if(o.clipPlane&&(this._defines.CLIPPLANE=!0),s.getAlphaTesting()&&(this._defines.ALPHATEST=!0),this._shouldUseAlphaFromDiffuseTexture()&&(this._defines.ALPHAFROMDIFFUSE=!0),this.useEmissiveAsIllumination&&(this._defines.EMISSIVEASILLUMINATION=!0),this.linkEmissiveWithDiffuse&&(this._defines.LINKEMISSIVEWITHDIFFUSE=!0),this.useLogarithmicDepth&&(this._defines.LOGARITHMICDEPTH=!0),this.cameraColorCurves&&(this._defines.CAMERACOLORCURVES=!0),(this.pointsCloud||o.forcePointsCloud)&&(this._defines.POINTSIZE=!0),o.fogEnabled&&i&&i.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(this._defines.FOG=!0),r.FresnelEnabled&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled||this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled||this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled||this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled)&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._defines.DIFFUSEFRESNEL=!0),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&(this._defines.OPACITYFRESNEL=!0),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._defines.REFLECTIONFRESNEL=!0,this.useReflectionFresnelFromSpecular&&(this._defines.REFLECTIONFRESNELFROMSPECULAR=!0)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._defines.REFRACTIONFRESNEL=!0),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._defines.EMISSIVEFRESNEL=!0),h=!0,this._defines.FRESNEL=!0),this._defines.SPECULARTERM&&this.useSpecularOverAlpha&&(this._defines.SPECULAROVERALPHA=!0),i&&(h&&i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(this._defines.NORMAL=!0),a&&(i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(this._defines.UV1=!0),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(this._defines.UV2=!0)),i.useVertexColors&&i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(this._defines.VERTEXCOLOR=!0,i.hasVertexAlpha&&(this._defines.VERTEXALPHA=!0)),i.useBones&&i.computeBonesUsingShaders&&(this._defines.NUM_BONE_INFLUENCERS=i.numBoneInfluencers,this._defines.BonesPerMesh=i.skeleton.bones.length+1),n&&(this._defines.INSTANCES=!0)),!this._defines.isEqual(this._cachedDefines)){this._defines.cloneTo(this._cachedDefines),o.resetCachedMaterial();var c=new e.EffectFallbacks;this._defines.REFLECTION&&c.addFallback(0,"REFLECTION"),this._defines.SPECULAR&&c.addFallback(0,"SPECULAR"),this._defines.BUMP&&c.addFallback(0,"BUMP"),this._defines.PARALLAX&&c.addFallback(1,"PARALLAX"),this._defines.PARALLAXOCCLUSION&&c.addFallback(0,"PARALLAXOCCLUSION"),this._defines.SPECULAROVERALPHA&&c.addFallback(0,"SPECULAROVERALPHA"),this._defines.FOG&&c.addFallback(1,"FOG"),this._defines.POINTSIZE&&c.addFallback(0,"POINTSIZE"),this._defines.LOGARITHMICDEPTH&&c.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(this._defines,c,this.maxSimultaneousLights),this._defines.SPECULARTERM&&c.addFallback(0,"SPECULARTERM"),this._defines.DIFFUSEFRESNEL&&c.addFallback(1,"DIFFUSEFRESNEL"),this._defines.OPACITYFRESNEL&&c.addFallback(2,"OPACITYFRESNEL"),this._defines.REFLECTIONFRESNEL&&c.addFallback(3,"REFLECTIONFRESNEL"),this._defines.EMISSIVEFRESNEL&&c.addFallback(4,"EMISSIVEFRESNEL"),this._defines.FRESNEL&&c.addFallback(4,"FRESNEL");var l=[e.VertexBuffer.PositionKind];this._defines.NORMAL&&l.push(e.VertexBuffer.NormalKind),this._defines.UV1&&l.push(e.VertexBuffer.UVKind),this._defines.UV2&&l.push(e.VertexBuffer.UV2Kind),this._defines.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,i,this._defines,c),e.MaterialHelper.PrepareAttributesForInstances(l,this._defines);var u="default",d=this._defines.toString(),f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","depthValues","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","logarithmicDepthConstant"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"];this._defines.CAMERACOLORCURVES&&e.ColorCurves.PrepareUniforms(f),this._defines.CAMERACOLORGRADING&&e.ColorGradingTexture.PrepareUniformsAndSamplers(f,p),e.MaterialHelper.PrepareUniformsAndSamplersList(f,p,this._defines,this.maxSimultaneousLights),this._effect=o.getEngine().createEffect(u,l,f,p,d,c,this.onCompiled,this.onError,{maxSimultaneousLights:this.maxSimultaneousLights-1})}return!!this._effect.isReady()&&(this._renderId=o.getRenderId(),this._wasPreviouslyReady=!0,i&&(i._materialDefines||(i._materialDefines=new t),this._defines.cloneTo(i._materialDefines)),!0)},r.prototype.unbind=function(){this.reflectionTexture&&this.reflectionTexture.isRenderTarget&&this._effect.setTexture("reflection2DSampler",null),this.refractionTexture&&this.refractionTexture.isRenderTarget&&this._effect.setTexture("refraction2DSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._effect.setMatrix("world",e)},r.prototype.bind=function(t,n){var o=this.getScene();if(this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(n,this._effect),o.getCachedMaterial()!==this){if(this._effect.setMatrix("viewProjection",o.getTransformMatrix()),r.FresnelEnabled&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._effect.setColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._effect.setColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._effect.setColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._effect.setColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._effect.setColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._effect.setColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._effect.setColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._effect.setColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._effect.setColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this.diffuseTexture&&r.DiffuseTextureEnabled&&(this._effect.setTexture("diffuseSampler",this.diffuseTexture),this._effect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._effect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.ambientTexture&&r.AmbientTextureEnabled&&(this._effect.setTexture("ambientSampler",this.ambientTexture),this._effect.setFloat2("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level),this._effect.setMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix())),this.opacityTexture&&r.OpacityTextureEnabled&&(this._effect.setTexture("opacitySampler",this.opacityTexture),this._effect.setFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level),this._effect.setMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix())),this.reflectionTexture&&r.ReflectionTextureEnabled&&(this.reflectionTexture.isCube?this._effect.setTexture("reflectionCubeSampler",this.reflectionTexture):this._effect.setTexture("reflection2DSampler",this.reflectionTexture),this._effect.setMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix()),this._effect.setFloat2("vReflectionInfos",this.reflectionTexture.level,this.roughness)),this.emissiveTexture&&r.EmissiveTextureEnabled&&(this._effect.setTexture("emissiveSampler",this.emissiveTexture),this._effect.setFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level),this._effect.setMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix())),this.lightmapTexture&&r.LightmapTextureEnabled&&(this._effect.setTexture("lightmapSampler",this.lightmapTexture),this._effect.setFloat2("vLightmapInfos",this.lightmapTexture.coordinatesIndex,this.lightmapTexture.level),this._effect.setMatrix("lightmapMatrix",this.lightmapTexture.getTextureMatrix())),this.specularTexture&&r.SpecularTextureEnabled&&(this._effect.setTexture("specularSampler",this.specularTexture),this._effect.setFloat2("vSpecularInfos",this.specularTexture.coordinatesIndex,this.specularTexture.level),this._effect.setMatrix("specularMatrix",this.specularTexture.getTextureMatrix())),this.bumpTexture&&o.getEngine().getCaps().standardDerivatives&&r.BumpTextureEnabled&&(this._effect.setTexture("bumpSampler",this.bumpTexture),this._effect.setFloat3("vBumpInfos",this.bumpTexture.coordinatesIndex,1/this.bumpTexture.level,this.parallaxScaleBias),this._effect.setMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix())),this.refractionTexture&&r.RefractionTextureEnabled){var s=1;this.refractionTexture.isCube?this._effect.setTexture("refractionCubeSampler",this.refractionTexture):(this._effect.setTexture("refraction2DSampler",this.refractionTexture),this._effect.setMatrix("refractionMatrix",this.refractionTexture.getReflectionTextureMatrix()),this.refractionTexture.depth&&(s=this.refractionTexture.depth)),this._effect.setFloat4("vRefractionInfos",this.refractionTexture.level,this.indexOfRefraction,s,this.invertRefractionY?-1:1)}this.cameraColorGradingTexture&&r.ColorGradingTextureEnabled&&e.ColorGradingTexture.Bind(this.cameraColorGradingTexture,this._effect)}e.MaterialHelper.BindClipPlane(this._effect,o),this.pointsCloud&&this._effect.setFloat("pointSize",this.pointSize),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),this._effect.setVector3("vEyePosition",o._mirroredCameraPosition?o._mirroredCameraPosition:o.activeCamera.position),this._effect.setColor3("vAmbientColor",this._globalAmbientColor),this._defines.SPECULARTERM&&this._effect.setColor4("vSpecularColor",this.specularColor,this.specularPower),this._effect.setColor3("vEmissiveColor",this.emissiveColor)}o.getCachedMaterial()===this&&this.isFrozen||(this._effect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*n.visibility),o.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(o,n,this._effect,this._defines,this.maxSimultaneousLights),(o.fogEnabled&&n.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this.reflectionTexture||this.refractionTexture)&&this._effect.setMatrix("view",o.getViewMatrix()),e.MaterialHelper.BindFogParameters(o,n,this._effect),e.MaterialHelper.BindLogDepth(this._defines,this._effect,o),
this.cameraColorCurves&&e.ColorCurves.Bind(this.cameraColorCurves,this._effect)),i.prototype.bind.call(this,t,n)},r.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0&&e.push(this.ambientTexture),this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0&&e.push(this.opacityTexture),this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0&&e.push(this.reflectionTexture),this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0&&e.push(this.emissiveTexture),this.specularTexture&&this.specularTexture.animations&&this.specularTexture.animations.length>0&&e.push(this.specularTexture),this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this.lightmapTexture&&this.lightmapTexture.animations&&this.lightmapTexture.animations.length>0&&e.push(this.lightmapTexture),this.refractionTexture&&this.refractionTexture.animations&&this.refractionTexture.animations.length>0&&e.push(this.refractionTexture),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.animations&&this.cameraColorGradingTexture.animations.length>0&&e.push(this.cameraColorGradingTexture),e},r.prototype.dispose=function(e,t){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.ambientTexture&&this.ambientTexture.dispose(),this.opacityTexture&&this.opacityTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose(),this.emissiveTexture&&this.emissiveTexture.dispose(),this.specularTexture&&this.specularTexture.dispose(),this.bumpTexture&&this.bumpTexture.dispose(),this.lightmapTexture&&this.lightmapTexture.dispose(),this.refractionTexture&&this.refractionTexture.dispose(),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.dispose()),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r.DiffuseTextureEnabled=!0,r.AmbientTextureEnabled=!0,r.OpacityTextureEnabled=!0,r.ReflectionTextureEnabled=!0,r.EmissiveTextureEnabled=!0,r.SpecularTextureEnabled=!0,r.BumpTextureEnabled=!0,r.FresnelEnabled=!0,r.LightmapTextureEnabled=!0,r.RefractionTextureEnabled=!0,r.ColorGradingTextureEnabled=!0,__decorate([e.serializeAsTexture()],r.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"ambientTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"specularTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("diffuse")],r.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3("specular")],r.prototype,"specularColor",void 0),__decorate([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),__decorate([e.serialize()],r.prototype,"specularPower",void 0),__decorate([e.serialize()],r.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([e.serialize()],r.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize()],r.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([e.serialize()],r.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([e.serialize()],r.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useReflectionOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"disableLighting",void 0),__decorate([e.serialize()],r.prototype,"useParallax",void 0),__decorate([e.serialize()],r.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],r.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize()],r.prototype,"roughness",void 0),__decorate([e.serialize()],r.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],r.prototype,"invertRefractionY",void 0),__decorate([e.serialize()],r.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"diffuseFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"reflectionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"refractionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize()],r.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.serialize()],r.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapX",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapY",void 0),__decorate([e.serializeAsTexture()],r.prototype,"cameraColorGradingTexture",void 0),__decorate([e.serializeAsColorCurves()],r.prototype,"cameraColorCurves",void 0),__decorate([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.Material);e.StandardMaterial=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i){t.call(this,e,i,!0),this.subMaterials=new Array,i.multiMaterials.push(this)}return __extends(i,t),i.prototype.getSubMaterial=function(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},i.prototype.isReady=function(e){for(var t=0;t<this.subMaterials.length;t++){var i=this.subMaterials[t];if(i&&!this.subMaterials[t].isReady(e))return!1}return!0},i.prototype.clone=function(e,t){for(var r=new i(e,this.getScene()),n=0;n<this.subMaterials.length;n++){var o=null;o=t?this.subMaterials[n].clone(e+"-"+this.subMaterials[n].name):this.subMaterials[n],r.subMaterials.push(o)}return r},i.prototype.serialize=function(){var t={};t.name=this.name,t.id=this.id,t.tags=e.Tags.GetTags(this),t.materials=[];for(var i=0;i<this.subMaterials.length;i++){var r=this.subMaterials[i];r?t.materials.push(r.id):t.materials.push(null)}return t},i})(e.Material);e.MultiMaterial=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return Object.defineProperty(t,"NO_LOGGING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MINIMAL_LOGGING",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"SUMMARY_LOGGING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(t,"DETAILED_LOGGING",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ForceFullSceneLoadingForIncremental",{get:function(){return t._ForceFullSceneLoadingForIncremental},set:function(e){t._ForceFullSceneLoadingForIncremental=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ShowLoadingScreen",{get:function(){return t._ShowLoadingScreen},set:function(e){t._ShowLoadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"loggingLevel",{get:function(){return t._loggingLevel},set:function(e){t._loggingLevel=e},enumerable:!0,configurable:!0}),t._getDefaultPlugin=function(){return t._registeredPlugins[".babylon"]},t._getPluginForExtension=function(e){var i=t._registeredPlugins[e];return i?i:t._getDefaultPlugin()},t._getPluginForFilename=function(e){e.name&&(e=e.name);var i=e.lastIndexOf("."),r=e.indexOf("?");r===-1&&(r=e.length);var n=e.substring(i,r).toLowerCase();return t._getPluginForExtension(n)},t._getDirectLoad=function(e){return e.substr&&"data:"===e.substr(0,5)?e.substr(5):null},t.GetPluginForExtension=function(e){return t._getPluginForExtension(e).plugin},t.RegisterPlugin=function(e){if("string"==typeof e.extensions){var i=e.extensions;t._registeredPlugins[i.toLowerCase()]={plugin:e,isBinary:!1}}else{var r=e.extensions;Object.keys(r).forEach((function(i){t._registeredPlugins[i.toLowerCase()]={plugin:e,isBinary:r[i].isBinary}}))}},t.ImportMesh=function(i,r,n,o,s,a,h){if(n.substr&&"/"===n.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");if(n.substr&&"/"===n.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");var c=t._getDirectLoad(n),l={};o._addPendingData(l);var u=function(u){o.database=d;var f=c?t._getDefaultPlugin():t._getPluginForFilename(n),p=f.plugin,_=f.isBinary,m=function(e){var t=[],a=[],c=[];try{if(p.importMesh){var u=p;if(!u.importMesh(i,o,e,r,t,a,c))return h&&h(o,"Unable to import meshes from "+r+n),void o._removePendingData(l);s&&(o.importedMeshesFiles.push(r+n),s(t,a,c),o._removePendingData(l))}else{var d=p;d.importMeshAsync(i,o,e,r,(function(e,t,i){s&&(o.importedMeshesFiles.push(r+n),s(e,t,i),o._removePendingData(l))}),(function(){h&&h(o,"Unable to import meshes from "+r+n),o._removePendingData(l)}))}}catch(f){h&&h(o,"Unable to import meshes from "+r+n,f),o._removePendingData(l)}};return c?void m(c):void e.Tools.LoadFile(r+n,(function(e){m(e)}),a,d,_)};if(o.getEngine().enableOfflineSupport&&!c)var d=new e.Database(r+n,u);else u(!0)},t.Load=function(i,r,n,o,s,a){t.Append(i,r,new e.Scene(n),o,s,a)},t.Append=function(i,r,n,o,s,a){if(r.substr&&"/"===r.substr(0,1))return void e.Tools.Error("Wrong sceneFilename parameter");var h,c=t._getDirectLoad(r),l=c?t._getDefaultPlugin():t._getPluginForFilename(r),u=l.plugin,d=l.isBinary,f={};n._addPendingData(f),t.ShowLoadingScreen&&n.getEngine().displayLoadingUI();var p=function(e){if(n.database=h,u.load){var r=u;if(!r.load(n,e,i))return a&&a(n),n._removePendingData(f),void n.getEngine().hideLoadingUI();o&&o(n),n._removePendingData(f)}else{var s=u;s.loadAsync(n,e,i,(function(){o&&o(n),n._removePendingData(f)}),(function(){a&&a(n),n._removePendingData(f),n.getEngine().hideLoadingUI()}))}t.ShowLoadingScreen&&n.executeWhenReady((function(){n.getEngine().hideLoadingUI()}))},_=function(t){e.Tools.LoadFile(i+r,p,s,h,d)};return c?void p(c):void(i.indexOf("file:")===-1?n.getEngine().enableOfflineSupport?h=new e.Database(i+r,_):_(!0):e.Tools.ReadFile(r,p,s,d))},t._ForceFullSceneLoadingForIncremental=!1,t._ShowLoadingScreen=!0,t._loggingLevel=t.NO_LOGGING,t._registeredPlugins={},t})();e.SceneLoader=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=function(t,i,r,n){for(var o=0,s=i.materials.length;o<s;o++){var a=i.materials[o];if(a.id===t)return e.Material.Parse(a,r,n)}return null},r=function(e,t,i){t=t instanceof Array?t:[t];for(var r in t)if(e.name===t[r])return i.push(e.id),!0;return!(!e.parentId||i.indexOf(e.parentId)===-1)&&(i.push(e.id),!0)},n=function(e,t){return e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown")};e.SceneLoader.RegisterPlugin({extensions:".babylon",importMesh:function(t,o,s,a,h,c,l){var u="importMesh has failed JSON parse";try{var d=JSON.parse(s);u="";var f,p,_=e.SceneLoader.loggingLevel===e.SceneLoader.DETAILED_LOGGING,m=[],g=[],v=[];for(f=0,p=d.meshes.length;f<p;f++){var y=d.meshes[f];if(!t||r(y,t,v)){if(t instanceof Array&&delete t[t.indexOf(y.name)],y.geometryId&&d.geometries){var x=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach((function(t){!x&&d.geometries[t]&&d.geometries[t]instanceof Array&&d.geometries[t].forEach((function(i){if(i.id===y.geometryId){switch(t){case"boxes":e.Geometry.Primitives.Box.Parse(i,o);break;case"spheres":e.Geometry.Primitives.Sphere.Parse(i,o);break;case"cylinders":e.Geometry.Primitives.Cylinder.Parse(i,o);break;case"toruses":e.Geometry.Primitives.Torus.Parse(i,o);break;case"grounds":e.Geometry.Primitives.Ground.Parse(i,o);break;case"planes":e.Geometry.Primitives.Plane.Parse(i,o);break;case"torusKnots":e.Geometry.Primitives.TorusKnot.Parse(i,o);break;case"vertexData":e.Geometry.Parse(i,o,a)}x=!0}}))})),x||e.Tools.Warn("Geometry not found for mesh "+y.id)}if(y.materialId){var b=g.indexOf(y.materialId)!==-1;if(!b&&d.multiMaterials)for(var A=0,T=d.multiMaterials.length;A<T;A++){var E=d.multiMaterials[A];if(E.id===y.materialId){for(var P=0,S=E.materials.length;P<S;P++){var M=E.materials[P];g.push(M);var C=i(M,d,o,a);u+="\n\tMaterial "+C.toString(_)}g.push(E.id);var R=e.Material.ParseMultiMaterial(E,o);b=!0,u+="\n\tMulti-Material "+R.toString(_);break}}if(!b){g.push(y.materialId);var C=i(y.materialId,d,o,a);C?u+="\n\tMaterial "+C.toString(_):e.Tools.Warn("Material not found for mesh "+y.id)}}if(y.skeletonId>-1&&o.skeletons){var O=m.indexOf(y.skeletonId)>-1;if(!O)for(var D=0,I=d.skeletons.length;D<I;D++){var L=d.skeletons[D];if(L.id===y.skeletonId){var w=e.Skeleton.Parse(L,o);l.push(w),m.push(L.id),u+="\n\tSkeleton "+w.toString(_)}}}var B=e.Mesh.Parse(y,o,a);h.push(B),u+="\n\tMesh "+B.toString(_)}}var F;for(f=0,p=o.meshes.length;f<p;f++)F=o.meshes[f],F._waitingParentId&&(F.parent=o.getLastEntryByID(F._waitingParentId),F._waitingParentId=void 0);for(f=0,p=o.meshes.length;f<p;f++)F=o.meshes[f],F._waitingFreezeWorldMatrix?(F.freezeWorldMatrix(),F._waitingFreezeWorldMatrix=void 0):F.computeWorldMatrix(!0);if(d.particleSystems)for(f=0,p=d.particleSystems.length;f<p;f++){var V=d.particleSystems[f];v.indexOf(V.emitterId)!==-1&&c.push(e.ParticleSystem.Parse(V,o,a))}return!0}catch(N){throw e.Tools.Log(n("importMesh",d?d.producer:"Unknown")+u),u=null,N}finally{null!==u&&e.SceneLoader.loggingLevel!==e.SceneLoader.NO_LOGGING&&e.Tools.Log(n("importMesh",d?d.producer:"Unknown")+(e.SceneLoader.loggingLevel!==e.SceneLoader.MINIMAL_LOGGING?u:""))}},load:function(t,i,r){var o="importScene has failed JSON parse";try{var s=JSON.parse(i);o="";var a=e.SceneLoader.loggingLevel===e.SceneLoader.DETAILED_LOGGING;if(t.useDelayedTextureLoading=s.useDelayedTextureLoading&&!e.SceneLoader.ForceFullSceneLoadingForIncremental,t.autoClear=s.autoClear,t.clearColor=e.Color4.FromArray(s.clearColor),t.ambientColor=e.Color3.FromArray(s.ambientColor),s.gravity&&(t.gravity=e.Vector3.FromArray(s.gravity)),s.fogMode&&0!==s.fogMode)switch(t.fogMode=s.fogMode,t.fogColor=e.Color3.FromArray(s.fogColor),t.fogStart=s.fogStart,t.fogEnd=s.fogEnd,t.fogDensity=s.fogDensity,o+="\tFog mode for scene:  ",t.fogMode){case 1:o+="exp\n";break;case 2:o+="exp2\n";break;case 3:o+="linear\n"}if(s.physicsEnabled){var h;"cannon"===s.physicsEngine?h=new e.CannonJSPlugin:"oimo"===s.physicsEngine&&(h=new e.OimoJSPlugin),o="\tPhysics engine "+(s.physicsEngine?s.physicsEngine:"oimo")+" enabled\n";var c=s.physicsGravity?e.Vector3.FromArray(s.physicsGravity):null;t.enablePhysics(c,h)}void 0!==s.metadata&&(t.metadata=s.metadata),void 0!=s.collisionsEnabled&&(t.collisionsEnabled=s.collisionsEnabled),t.workerCollisions=!!s.workerCollisions;var l,u;for(l=0,u=s.lights.length;l<u;l++){var d=s.lights[l],f=e.Light.Parse(d,t);o+=0===l?"\n\tLights:":"",o+="\n\t\t"+f.toString(a)}if(s.animations)for(l=0,u=s.animations.length;l<u;l++){var p=s.animations[l],_=e.Animation.Parse(p);t.animations.push(_),o+=0===l?"\n\tAnimations:":"",o+="\n\t\t"+_.toString(a)}if(s.autoAnimate&&t.beginAnimation(t,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1),s.materials)for(l=0,u=s.materials.length;l<u;l++){var m=s.materials[l],g=e.Material.Parse(m,t,r);o+=0===l?"\n\tMaterials:":"",o+="\n\t\t"+g.toString(a)}if(s.multiMaterials)for(l=0,u=s.multiMaterials.length;l<u;l++){var v=s.multiMaterials[l],y=e.Material.ParseMultiMaterial(v,t);o+=0===l?"\n\tMultiMaterials:":"",o+="\n\t\t"+y.toString(a)}if(s.skeletons)for(l=0,u=s.skeletons.length;l<u;l++){var x=s.skeletons[l],b=e.Skeleton.Parse(x,t);o+=0===l?"\n\tSkeletons:":"",o+="\n\t\t"+b.toString(a)}var A=s.geometries;if(A){var T=A.boxes;if(T)for(l=0,u=T.length;l<u;l++){var E=T[l];e.Geometry.Primitives.Box.Parse(E,t)}var P=A.spheres;if(P)for(l=0,u=P.length;l<u;l++){var S=P[l];e.Geometry.Primitives.Sphere.Parse(S,t)}var M=A.cylinders;if(M)for(l=0,u=M.length;l<u;l++){var C=M[l];e.Geometry.Primitives.Cylinder.Parse(C,t)}var R=A.toruses;if(R)for(l=0,u=R.length;l<u;l++){var O=R[l];e.Geometry.Primitives.Torus.Parse(O,t)}var D=A.grounds;if(D)for(l=0,u=D.length;l<u;l++){var I=D[l];e.Geometry.Primitives.Ground.Parse(I,t)}var L=A.planes;if(L)for(l=0,u=L.length;l<u;l++){var w=L[l];e.Geometry.Primitives.Plane.Parse(w,t)}var B=A.torusKnots;if(B)for(l=0,u=B.length;l<u;l++){var F=B[l];e.Geometry.Primitives.TorusKnot.Parse(F,t)}var V=A.vertexData;if(V)for(l=0,u=V.length;l<u;l++){var N=V[l];e.Geometry.Parse(N,t,r)}}for(l=0,u=s.meshes.length;l<u;l++){var U=s.meshes[l],z=e.Mesh.Parse(U,t,r);o+=0===l?"\n\tMeshes:":"",o+="\n\t\t"+z.toString(a)}for(l=0,u=s.cameras.length;l<u;l++){var k=s.cameras[l],G=e.Camera.Parse(k,t);o+=0===l?"\n\tCameras:":"",o+="\n\t\t"+G.toString(a)}for(s.activeCameraID&&t.setActiveCameraByID(s.activeCameraID),l=0,u=t.cameras.length;l<u;l++){var G=t.cameras[l];G._waitingParentId&&(G.parent=t.getLastEntryByID(G._waitingParentId),G._waitingParentId=void 0)}for(l=0,u=t.lights.length;l<u;l++){var f=t.lights[l];f._waitingParentId&&(f.parent=t.getLastEntryByID(f._waitingParentId),f._waitingParentId=void 0)}var W,Y=[];if(e.AudioEngine&&s.sounds)for(l=0,u=s.sounds.length;l<u;l++){var H=s.sounds[l];if(e.Engine.audioEngine.canUseWebAudio)H.url||(H.url=H.name),Y[H.url]?e.Sound.Parse(H,t,r,Y[H.url]):(W=e.Sound.Parse(H,t,r),Y[H.url]=W);else{new e.Sound(H.name,null,t)}}for(Y=[],l=0,u=t.meshes.length;l<u;l++){var z=t.meshes[l];z._waitingParentId&&(z.parent=t.getLastEntryByID(z._waitingParentId),z._waitingParentId=void 0),z._waitingActions&&(e.ActionManager.Parse(z._waitingActions,z,t),z._waitingActions=void 0)}for(l=0,u=t.meshes.length;l<u;l++){var X=t.meshes[l];X._waitingFreezeWorldMatrix?(X.freezeWorldMatrix(),X._waitingFreezeWorldMatrix=void 0):X.computeWorldMatrix(!0)}if(s.particleSystems)for(l=0,u=s.particleSystems.length;l<u;l++){var j=s.particleSystems[l];e.ParticleSystem.Parse(j,t,r)}if(s.lensFlareSystems)for(l=0,u=s.lensFlareSystems.length;l<u;l++){var K=s.lensFlareSystems[l];e.LensFlareSystem.Parse(K,t,r)}if(s.shadowGenerators)for(l=0,u=s.shadowGenerators.length;l<u;l++){var Z=s.shadowGenerators[l];e.ShadowGenerator.Parse(Z,t)}return s.actions&&e.ActionManager.Parse(s.actions,null,t),!0}catch(q){throw e.Tools.Log(n("importScene",s?s.producer:"Unknown")+o),o=null,q}finally{null!==o&&e.SceneLoader.loggingLevel!==e.SceneLoader.NO_LOGGING&&e.Tools.Log(n("importScene",s?s.producer:"Unknown")+(e.SceneLoader.loggingLevel!==e.SceneLoader.MINIMAL_LOGGING?o:""))}}})})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a){if(void 0===s&&(s=.01),void 0===a&&(a=e.Texture.TRILINEAR_SAMPLINGMODE),this.name=t,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.fogEnabled=!0,this.isPickable=!1,this.onDisposeObservable=new e.Observable,this._vertexBuffers={},this._capacity=r,this._spriteTexture=new e.Texture(i,o,(!0),(!1),a),this._spriteTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._spriteTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return;this.cellWidth=n,this.cellHeight=n}this._epsilon=s,this._scene=o,this._scene.spriteManagers.push(this);for(var h=[],c=0,l=0;l<r;l++)h.push(c),h.push(c+1),h.push(c+2),h.push(c),h.push(c+2),h.push(c+3),c+=4;this._indexBuffer=o.getEngine().createIndexBuffer(h),this._vertexData=new Float32Array(16*r*4),this._buffer=new e.Buffer(o.getEngine(),this._vertexData,(!0),16);var u=this._buffer.createVertexBuffer(e.VertexBuffer.PositionKind,0,4),d=this._buffer.createVertexBuffer("options",4,4),f=this._buffer.createVertexBuffer("cellInfo",8,4),p=this._buffer.createVertexBuffer(e.VertexBuffer.ColorKind,12,4);this._vertexBuffers[e.VertexBuffer.PositionKind]=u,this._vertexBuffers.options=d,this._vertexBuffers.cellInfo=f,this._vertexBuffers[e.VertexBuffer.ColorKind]=p,this._effectBase=this._scene.getEngine().createEffect("sprites",[e.VertexBuffer.PositionKind,"options","cellInfo",e.VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],""),this._effectFog=this._scene.getEngine().createEffect("sprites",[e.VertexBuffer.PositionKind,"options","cellInfo",e.VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],"#define FOG")}return Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"texture",{get:function(){return this._spriteTexture},set:function(e){this._spriteTexture=e},enumerable:!0,configurable:!0}),t.prototype._appendSpriteVertex=function(e,t,i,r,n){var o=16*e;0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._vertexData[o+6]=i,this._vertexData[o+7]=r,this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0;var s=t.cellIndex/n>>0;this._vertexData[o+10]=t.cellIndex-s*n,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},t.prototype.intersects=function(t,i,r,n){for(var o,s=Math.min(this._capacity,this.sprites.length),a=e.Vector3.Zero(),h=e.Vector3.Zero(),c=Number.MAX_VALUE,l=e.Vector3.Zero(),u=i.getViewMatrix(),d=0;d<s;d++){var f=this.sprites[d];if(f){if(r){if(!r(f))continue}else if(!f.isPickable)continue;if(e.Vector3.TransformCoordinatesToRef(f.position,u,l),a.copyFromFloats(l.x-f.width/2,l.y-f.height/2,l.z),h.copyFromFloats(l.x+f.width/2,l.y+f.height/2,l.z),t.intersectsBoxMinMax(a,h)){var p=e.Vector3.Distance(l,t.origin);if(c>p&&(c=p,o=f,n))break}}}if(o){var _=new e.PickingInfo;return _.hit=!0,_.pickedSprite=o,_.distance=c,_}return null},t.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()){for(var t=this._scene.getEngine(),i=this._spriteTexture.getBaseSize(),r=t.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),o=i.width/this.cellWidth,s=0,a=0;a<n;a++){var h=this.sprites[a];h&&(h._animate(r),this._appendSpriteVertex(s++,h,0,0,o),this._appendSpriteVertex(s++,h,1,0,o),this._appendSpriteVertex(s++,h,1,1,o),this._appendSpriteVertex(s++,h,0,1,o))}this._buffer.update(this._vertexData);var c=this._effectBase;this._scene.fogEnabled&&this._scene.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(c=this._effectFog),t.enableEffect(c);var l=this._scene.getViewMatrix();c.setTexture("diffuseSampler",this._spriteTexture),c.setMatrix("view",l),c.setMatrix("projection",this._scene.getProjectionMatrix()),c.setFloat2("textureInfos",this.cellWidth/i.width,this.cellHeight/i.height),this._scene.fogEnabled&&this._scene.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(c.setFloat4("vFogInfos",this._scene.fogMode,this._scene.fogStart,this._scene.fogEnd,this._scene.fogDensity),c.setColor3("vFogColor",this._scene.fogColor)),t.bindBuffers(this._vertexBuffers,this._indexBuffer,c),t.setDepthFunctionToLessOrEqual(),c.setBool("alphaTest",!0),t.setColorWrite(!1),t.draw(!0,0,6*n),t.setColorWrite(!0),c.setBool("alphaTest",!1),t.setAlphaMode(e.Engine.ALPHA_COMBINE),t.draw(!0,0,6*n),t.setAlphaMode(e.Engine.ALPHA_DISABLE)}},t.prototype.dispose=function(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._spriteTexture&&(this._spriteTexture.dispose(),this._spriteTexture=null);var e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t})();e.SpriteManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){this.name=t,this.color=new e.Color4(1,1,1,1),this.width=1,this.height=1,this.angle=0,this.cellIndex=0,this.invertU=0,this.invertV=0,this.animations=new Array,this.isPickable=!1,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._frameCount=0,this._time=0,this._manager=i,this._manager.sprites.push(this),this.position=e.Vector3.Zero()}return Object.defineProperty(t.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!0,configurable:!0}),t.prototype.playAnimation=function(e,t,i,r,n){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r,this._animationStarted=!0,this._direction=e<t?1:-1,this.cellIndex=e,this._time=0,this._onAnimationEnd=n},t.prototype.stopAnimation=function(){this._animationStarted=!1},t.prototype._animate=function(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,this.cellIndex===this._toIndex&&(this._loopAnimation?this.cellIndex=this._fromIndex:(this._animationStarted=!1,this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},t.prototype.dispose=function(){for(var e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1)},t})();e.Sprite=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.name=t,this.scale=new e.Vector2(1,1),this.offset=new e.Vector2(0,0),this.alphaBlendingMode=e.Engine.ALPHA_COMBINE,this._vertexBuffers={},this.onDisposeObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,this.texture=i?new e.Texture(i,r,(!0)):null,this.isBackground=void 0===n||n,this.color=void 0===o?new e.Color4(1,1,1,1):o,this._scene=r,this._scene.layers.push(this);var s=r.getEngine(),a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);var h=new e.VertexBuffer(s,a,e.VertexBuffer.PositionKind,(!1),(!1),2);this._vertexBuffers[e.VertexBuffer.PositionKind]=h;var c=[];c.push(0),c.push(1),c.push(2),c.push(0),c.push(2),c.push(3),this._indexBuffer=s.createIndexBuffer(c),this._effect=s.createEffect("layer",[e.VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],""),this._alphaTestEffect=s.createEffect("layer",[e.VertexBuffer.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],"#define ALPHATEST")}return Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.render=function(){var t=this.alphaTest?this._alphaTestEffect:this._effect;if(t.isReady()&&this.texture&&this.texture.isReady()){var i=this._scene.getEngine();this.onBeforeRenderObservable.notifyObservers(this),i.enableEffect(t),i.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?i.draw(!0,0,6):(i.setAlphaMode(this.alphaBlendingMode),i.draw(!0,0,6),i.setAlphaMode(e.Engine.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this)}},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null);var i=this._scene.layers.indexOf(this);this._scene.layers.splice(i,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},t})();e.Layer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.position=e.Vector3.Zero(),this.direction=e.Vector3.Zero(),this.color=new e.Color4(0,0,0,0),this.colorStep=new e.Color4(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.angle=0,this.angularSpeed=0}return t.prototype.copyTo=function(e){e.position.copyFrom(this.position),e.direction.copyFrom(this.direction),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e.size=this.size,e.angle=this.angle,e.angularSpeed=this.angularSpeed},t})();e.Particle=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=function(e,t){if(e===t)return e;var i=Math.random();return i*(t-e)+e},i=(function(){function i(r,n,o,s){var a=this;this.name=r,this.animations=[],this.renderingGroupId=0,this.emitter=null,this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.onDisposeObservable=new e.Observable,this.blendMode=i.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.gravity=e.Vector3.Zero(),this.direction1=new e.Vector3(0,1,0),this.direction2=new e.Vector3(0,1,0),this.minEmitBox=new e.Vector3((-.5),(-.5),(-.5)),this.maxEmitBox=new e.Vector3(.5,.5,.5),this.color1=new e.Color4(1,1,1,1),this.color2=new e.Color4(1,1,1,1),this.colorDead=new e.Color4(0,0,0,1),this.textureMask=new e.Color4(1,1,1,1),this.particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new e.Color4(0,0,0,0),this._colorDiff=new e.Color4(0,0,0,0),this._scaledDirection=e.Vector3.Zero(),this._scaledGravity=e.Vector3.Zero(),this._currentRenderId=-1,this._started=!1,this._stopped=!1,this._actualFrame=0,this.id=r,this._capacity=n,this._scene=o,this._customEffect=s,o.particleSystems.push(this);for(var h=[],c=0,l=0;l<n;l++)h.push(c),h.push(c+1),h.push(c+2),h.push(c),h.push(c+2),h.push(c+3),c+=4;this._indexBuffer=o.getEngine().createIndexBuffer(h),this._vertexData=new Float32Array(11*n*4),this._vertexBuffer=new e.Buffer(o.getEngine(),this._vertexData,(!0),11);var u=this._vertexBuffer.createVertexBuffer(e.VertexBuffer.PositionKind,0,3),d=this._vertexBuffer.createVertexBuffer(e.VertexBuffer.ColorKind,3,4),f=this._vertexBuffer.createVertexBuffer("options",7,4);this._vertexBuffers[e.VertexBuffer.PositionKind]=u,this._vertexBuffers[e.VertexBuffer.ColorKind]=d,this._vertexBuffers.options=f,this.startDirectionFunction=function(i,r,n,o){var s=t(a.direction1.x,a.direction2.x),h=t(a.direction1.y,a.direction2.y),c=t(a.direction1.z,a.direction2.z);e.Vector3.TransformNormalFromFloatsToRef(s*i,h*i,c*i,r,n)},this.startPositionFunction=function(i,r,n){var o=t(a.minEmitBox.x,a.maxEmitBox.x),s=t(a.minEmitBox.y,a.maxEmitBox.y),h=t(a.minEmitBox.z,a.maxEmitBox.z);e.Vector3.TransformCoordinatesFromFloatsToRef(o,s,h,i,r);
},this.updateFunction=function(e){for(var t=0;t<e.length;t++){var i=e[t];i.age+=a._scaledUpdateSpeed,i.age>=i.lifeTime?(a.recycleParticle(i),t--):(i.colorStep.scaleToRef(a._scaledUpdateSpeed,a._scaledColorStep),i.color.addInPlace(a._scaledColorStep),i.color.a<0&&(i.color.a=0),i.angle+=i.angularSpeed*a._scaledUpdateSpeed,i.direction.scaleToRef(a._scaledUpdateSpeed,a._scaledDirection),i.position.addInPlace(a._scaledDirection),a.gravity.scaleToRef(a._scaledUpdateSpeed,a._scaledGravity),i.direction.addInPlace(a._scaledGravity))}}}return Object.defineProperty(i.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),i.prototype.recycleParticle=function(e){var t=this.particles.pop();t!==e&&(t.copyTo(e),this._stockParticles.push(t))},i.prototype.getCapacity=function(){return this._capacity},i.prototype.isAlive=function(){return this._alive},i.prototype.isStarted=function(){return this._started},i.prototype.start=function(){this._started=!0,this._stopped=!1,this._actualFrame=0},i.prototype.stop=function(){this._stopped=!0},i.prototype._appendParticleVertex=function(e,t,i,r){var n=11*e;this._vertexData[n]=t.position.x,this._vertexData[n+1]=t.position.y,this._vertexData[n+2]=t.position.z,this._vertexData[n+3]=t.color.r,this._vertexData[n+4]=t.color.g,this._vertexData[n+5]=t.color.b,this._vertexData[n+6]=t.color.a,this._vertexData[n+7]=t.angle,this._vertexData[n+8]=t.size,this._vertexData[n+9]=i,this._vertexData[n+10]=r},i.prototype._update=function(i){this._alive=this.particles.length>0,this.updateFunction(this.particles);var r;r=this.emitter.position?this.emitter.getWorldMatrix():e.Matrix.Translation(this.emitter.x,this.emitter.y,this.emitter.z);for(var n,o=0;o<i&&this.particles.length!==this._capacity;o++){0!==this._stockParticles.length?(n=this._stockParticles.pop(),n.age=0):n=new e.Particle,this.particles.push(n);var s=t(this.minEmitPower,this.maxEmitPower);this.startDirectionFunction(s,r,n.direction,n),n.lifeTime=t(this.minLifeTime,this.maxLifeTime),n.size=t(this.minSize,this.maxSize),n.angularSpeed=t(this.minAngularSpeed,this.maxAngularSpeed),this.startPositionFunction(r,n.position,n);var a=t(0,1);e.Color4.LerpToRef(this.color1,this.color2,a,n.color),this.colorDead.subtractToRef(n.color,this._colorDiff),this._colorDiff.scaleToRef(1/n.lifeTime,n.colorStep)}},i.prototype._getEffect=function(){if(this._customEffect)return this._customEffect;var t=[];this._scene.clipPlane&&t.push("#define CLIPPLANE");var i=t.join("\n");return this._cachedDefines!==i&&(this._cachedDefines=i,this._effect=this._scene.getEngine().createEffect("particles",[e.VertexBuffer.PositionKind,e.VertexBuffer.ColorKind,"options"],["invView","view","projection","vClipPlane","textureMask"],["diffuseSampler"],i)),this._effect},i.prototype.animate=function(){if(this._started){var e=this._getEffect();if(this.emitter&&e.isReady()&&this.particleTexture&&this.particleTexture.isReady()&&this._currentRenderId!==this._scene.getRenderId()){this._currentRenderId=this._scene.getRenderId(),this._scaledUpdateSpeed=this.updateSpeed*this._scene.getAnimationRatio();var t;this.manualEmitCount>-1?(t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0):(t=this.emitRate*this._scaledUpdateSpeed>>0,this._newPartsExcess+=this.emitRate*this._scaledUpdateSpeed-t),this._newPartsExcess>1&&(t+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.disposeOnStop&&this._scene._toBeDisposed.push(this)));for(var i=0,r=0;r<this.particles.length;r++){var n=this.particles[r];this._appendParticleVertex(i++,n,0,0),this._appendParticleVertex(i++,n,1,0),this._appendParticleVertex(i++,n,1,1),this._appendParticleVertex(i++,n,0,1)}this._vertexBuffer.update(this._vertexData)}}},i.prototype.render=function(){var t=this._getEffect();if(!(this.emitter&&t.isReady()&&this.particleTexture&&this.particleTexture.isReady()&&this.particles.length))return 0;var r=this._scene.getEngine();r.enableEffect(t),r.setState(!1);var n=this._scene.getViewMatrix();if(t.setTexture("diffuseSampler",this.particleTexture),t.setMatrix("view",n),t.setMatrix("projection",this._scene.getProjectionMatrix()),t.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._scene.clipPlane){var o=this._scene.clipPlane,s=n.clone();s.invert(),t.setMatrix("invView",s),t.setFloat4("vClipPlane",o.normal.x,o.normal.y,o.normal.z,o.d)}return r.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.blendMode===i.BLENDMODE_ONEONE?r.setAlphaMode(e.Engine.ALPHA_ONEONE):r.setAlphaMode(e.Engine.ALPHA_COMBINE),this.forceDepthWrite&&r.setDepthWrite(!0),r.draw(!0,0,6*this.particles.length),r.setAlphaMode(e.Engine.ALPHA_DISABLE),this.particles.length},i.prototype.dispose=function(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null);var e=this._scene.particleSystems.indexOf(this);this._scene.particleSystems.splice(e,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},i.prototype.clone=function(t,r){var n=new i(t,this._capacity,this._scene);return e.Tools.DeepCopy(this,n,["particles"]),void 0===r&&(r=this.emitter),n.emitter=r,this.particleTexture&&(n.particleTexture=new e.Texture(this.particleTexture.url,this._scene)),n.start(),n},i.prototype.serialize=function(){var t={};return t.name=this.name,t.id=this.id,this.emitter.position?t.emitterId=this.emitter.id:t.emitter=this.emitter.asArray(),t.capacity=this.getCapacity(),this.particleTexture&&(t.textureName=this.particleTexture.name),e.Animation.AppendSerializedAnimations(this,t),t.minAngularSpeed=this.minAngularSpeed,t.maxAngularSpeed=this.maxAngularSpeed,t.minSize=this.minSize,t.maxSize=this.maxSize,t.minEmitPower=this.minEmitPower,t.maxEmitPower=this.maxEmitPower,t.minLifeTime=this.minLifeTime,t.maxLifeTime=this.maxLifeTime,t.emitRate=this.emitRate,t.minEmitBox=this.minEmitBox.asArray(),t.maxEmitBox=this.maxEmitBox.asArray(),t.gravity=this.gravity.asArray(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.color1=this.color1.asArray(),t.color2=this.color2.asArray(),t.colorDead=this.colorDead.asArray(),t.updateSpeed=this.updateSpeed,t.targetStopDuration=this.targetStopDuration,t.textureMask=this.textureMask.asArray(),t.blendMode=this.blendMode,t},i.Parse=function(t,r,n){var o=t.name,s=new i(o,t.capacity,r);if(t.id&&(s.id=t.id),t.textureName&&(s.particleTexture=new e.Texture(n+t.textureName,r),s.particleTexture.name=t.textureName),t.emitterId?s.emitter=r.getLastMeshByID(t.emitterId):s.emitter=e.Vector3.FromArray(t.emitter),t.animations)for(var a=0;a<t.animations.length;a++){var h=t.animations[a];s.animations.push(e.Animation.Parse(h))}return t.autoAnimate&&r.beginAnimation(s,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1),s.minAngularSpeed=t.minAngularSpeed,s.maxAngularSpeed=t.maxAngularSpeed,s.minSize=t.minSize,s.maxSize=t.maxSize,s.minLifeTime=t.minLifeTime,s.maxLifeTime=t.maxLifeTime,s.minEmitPower=t.minEmitPower,s.maxEmitPower=t.maxEmitPower,s.emitRate=t.emitRate,s.minEmitBox=e.Vector3.FromArray(t.minEmitBox),s.maxEmitBox=e.Vector3.FromArray(t.maxEmitBox),s.gravity=e.Vector3.FromArray(t.gravity),s.direction1=e.Vector3.FromArray(t.direction1),s.direction2=e.Vector3.FromArray(t.direction2),s.color1=e.Color4.FromArray(t.color1),s.color2=e.Color4.FromArray(t.color2),s.colorDead=e.Color4.FromArray(t.colorDead),s.updateSpeed=t.updateSpeed,s.targetStopDuration=t.targetStopDuration,s.textureMask=e.Color4.FromArray(t.textureMask),s.blendMode=t.blendMode,t.preventAutoStart||s.start(),s},i.BLENDMODE_ONEONE=0,i.BLENDMODE_STANDARD=1,i})();e.ParticleSystem=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e})();e.AnimationRange=t;var i=(function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e})();e.AnimationEvent=i;var r=(function(){function t(e){this.path=e,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e.Vector3(t.x,0,t.y)},t.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},t.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},t.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(e){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},t.prototype.onchange=function(e){return this._onchange.push(e),this},t})();e.PathCursor=r;var n=(function(){function i(e,t,r,n,o,s){this.name=e,this.targetProperty=t,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=s,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._events=new Array,this.allowMatricesInterpolation=!1,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=n,this.loopMode=void 0===o?i.ANIMATIONLOOPMODE_CYCLE:o}return i._PrepareAnimation=function(t,r,n,o,s,a,h,c){var l=void 0;if(!isNaN(parseFloat(s))&&isFinite(s)?l=i.ANIMATIONTYPE_FLOAT:s instanceof e.Quaternion?l=i.ANIMATIONTYPE_QUATERNION:s instanceof e.Vector3?l=i.ANIMATIONTYPE_VECTOR3:s instanceof e.Vector2?l=i.ANIMATIONTYPE_VECTOR2:s instanceof e.Color3?l=i.ANIMATIONTYPE_COLOR3:s instanceof e.Size&&(l=i.ANIMATIONTYPE_SIZE),void 0==l)return null;var u=new i(t,r,n,l,h),d=[{frame:0,value:s},{frame:o,value:a}];return u.setKeys(d),void 0!==c&&u.setEasingFunction(c),u},i.CreateAndStartAnimation=function(e,t,r,n,o,s,a,h,c,l){var u=i._PrepareAnimation(e,r,n,o,s,a,h,c);return t.getScene().beginDirectAnimation(t,[u],0,o,1===u.loopMode,1,l)},i.CreateMergeAndStartAnimation=function(e,t,r,n,o,s,a,h,c,l){var u=i._PrepareAnimation(e,r,n,o,s,a,h,c);return t.animations.push(u),t.getScene().beginAnimation(t,0,o,1===u.loopMode,1,l)},i.prototype.toString=function(e){var t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},i.prototype.addEvent=function(e){this._events.push(e)},i.prototype.removeEvents=function(e){for(var t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)},i.prototype.createRange=function(e,i,r){this._ranges[e]||(this._ranges[e]=new t(e,i,r))},i.prototype.deleteRange=function(e,t){if(void 0===t&&(t=!0),this._ranges[e]){if(t)for(var i=this._ranges[e].from,r=this._ranges[e].to,n=this._keys.length-1;n>=0;n--)this._keys[n].frame>=i&&this._keys[n].frame<=r&&this._keys.splice(n,1);this._ranges[e]=void 0}},i.prototype.getRange=function(e){return this._ranges[e]},i.prototype.reset=function(){this._offsetsCache={},this._highLimitsCache={},this.currentFrame=0,this._blendingFactor=0,this._originalBlendValue=null},i.prototype.isStopped=function(){return this._stopped},i.prototype.getKeys=function(){return this._keys},i.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e},i.prototype.getEasingFunction=function(){return this._easingFunction},i.prototype.setEasingFunction=function(e){this._easingFunction=e},i.prototype.floatInterpolateFunction=function(e,t,i){return e+(t-e)*i},i.prototype.quaternionInterpolateFunction=function(t,i,r){return e.Quaternion.Slerp(t,i,r)},i.prototype.vector3InterpolateFunction=function(t,i,r){return e.Vector3.Lerp(t,i,r)},i.prototype.vector2InterpolateFunction=function(t,i,r){return e.Vector2.Lerp(t,i,r)},i.prototype.sizeInterpolateFunction=function(t,i,r){return e.Size.Lerp(t,i,r)},i.prototype.color3InterpolateFunction=function(t,i,r){return e.Color3.Lerp(t,i,r)},i.prototype.matrixInterpolateFunction=function(t,i,r){return e.Matrix.Lerp(t,i,r)},i.prototype.clone=function(){var e=new i(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(var t in this._ranges)e._ranges[t]=this._ranges[t].clone()}return e},i.prototype.setKeys=function(e){this._keys=e.slice(0),this._offsetsCache={},this._highLimitsCache={}},i.prototype._getKeyValue=function(e){return"function"==typeof e?e():e},i.prototype._interpolate=function(e,t,r,n,o){if(r===i.ANIMATIONLOOPMODE_CONSTANT&&t>0)return o.clone?o.clone():o;this.currentFrame=e;var s=Math.max(0,Math.min(this._keys.length-1,Math.floor(this._keys.length*(e-this._keys[0].frame)/(this._keys[this._keys.length-1].frame-this._keys[0].frame))-1));if(this._keys[s].frame>=e)for(;s-1>=0&&this._keys[s].frame>=e;)s--;for(var a=s;a<this._keys.length;a++)if(this._keys[a+1].frame>=e){var h=this._getKeyValue(this._keys[a].value),c=this._getKeyValue(this._keys[a+1].value),l=(e-this._keys[a].frame)/(this._keys[a+1].frame-this._keys[a].frame);switch(null!=this._easingFunction&&(l=this._easingFunction.ease(l)),this.dataType){case i.ANIMATIONTYPE_FLOAT:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.floatInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return n*t+this.floatInterpolateFunction(h,c,l)}break;case i.ANIMATIONTYPE_QUATERNION:var u=null;switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:u=this.quaternionInterpolateFunction(h,c,l);break;case i.ANIMATIONLOOPMODE_RELATIVE:u=this.quaternionInterpolateFunction(h,c,l).add(n.scale(t))}return u;case i.ANIMATIONTYPE_VECTOR3:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.vector3InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.vector3InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_VECTOR2:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.vector2InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.vector2InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_SIZE:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_COLOR3:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(h,c,l).add(n.scale(t))}case i.ANIMATIONTYPE_MATRIX:switch(r){case i.ANIMATIONLOOPMODE_CYCLE:case i.ANIMATIONLOOPMODE_CONSTANT:if(this.allowMatricesInterpolation)return this.matrixInterpolateFunction(h,c,l);case i.ANIMATIONLOOPMODE_RELATIVE:return h}}break}return this._getKeyValue(this._keys[this._keys.length-1].value)},i.prototype.setValue=function(t,i){void 0===i&&(i=!1);var r,n;if(this.targetPropertyPath.length>1){for(var o=this._target[this.targetPropertyPath[0]],s=1;s<this.targetPropertyPath.length-1;s++)o=o[this.targetPropertyPath[s]];r=this.targetPropertyPath[this.targetPropertyPath.length-1],n=o}else r=this.targetPropertyPath[0],n=this._target;this.enableBlending&&this._blendingFactor<=1?(this._originalBlendValue||(n[r].clone?this._originalBlendValue=n[r].clone():this._originalBlendValue=n[r]),this._originalBlendValue.prototype?this._originalBlendValue.prototype.Lerp?n[r]=this._originalBlendValue.construtor.prototype.Lerp(t,this._originalBlendValue,this._blendingFactor):n[r]=t:this._originalBlendValue.m?n[r]=e.Matrix.Lerp(this._originalBlendValue,t,this._blendingFactor):n[r]=this._originalBlendValue*(1-this._blendingFactor)+this._blendingFactor*t,this._blendingFactor+=this.blendingSpeed):n[r]=t,this._target.markAsDirty&&this._target.markAsDirty(this.targetProperty)},i.prototype.goToFrame=function(e){e<this._keys[0].frame?e=this._keys[0].frame:e>this._keys[this._keys.length-1].frame&&(e=this._keys[this._keys.length-1].frame);var t=this._interpolate(e,0,this.loopMode);this.setValue(t)},i.prototype.animate=function(t,r,n,o,s,a){if(void 0===a&&(a=!1),!this.targetPropertyPath||this.targetPropertyPath.length<1)return this._stopped=!0,!1;var h=!0;if(0!==this._keys[0].frame){var c={frame:0,value:this._keys[0].value};this._keys.splice(0,0,c)}(r<this._keys[0].frame||r>this._keys[this._keys.length-1].frame)&&(r=this._keys[0].frame),(n<this._keys[0].frame||n>this._keys[this._keys.length-1].frame)&&(n=this._keys[this._keys.length-1].frame),r===n&&r++;var l,u=n-r,d=t*(this.framePerSecond*s)/1e3,f=0;if(d>u&&!o)h=!1,f=this._getKeyValue(this._keys[this._keys.length-1].value);else if(this.loopMode!==i.ANIMATIONLOOPMODE_CYCLE){var p=n.toString()+r.toString();if(!this._offsetsCache[p]){var _=this._interpolate(r,0,i.ANIMATIONLOOPMODE_CYCLE),m=this._interpolate(n,0,i.ANIMATIONLOOPMODE_CYCLE);switch(this.dataType){case i.ANIMATIONTYPE_FLOAT:this._offsetsCache[p]=m-_;break;case i.ANIMATIONTYPE_QUATERNION:this._offsetsCache[p]=m.subtract(_);break;case i.ANIMATIONTYPE_VECTOR3:this._offsetsCache[p]=m.subtract(_);case i.ANIMATIONTYPE_VECTOR2:this._offsetsCache[p]=m.subtract(_);case i.ANIMATIONTYPE_SIZE:this._offsetsCache[p]=m.subtract(_);case i.ANIMATIONTYPE_COLOR3:this._offsetsCache[p]=m.subtract(_)}this._highLimitsCache[p]=m}f=this._highLimitsCache[p],l=this._offsetsCache[p]}if(void 0===l)switch(this.dataType){case i.ANIMATIONTYPE_FLOAT:l=0;break;case i.ANIMATIONTYPE_QUATERNION:l=new e.Quaternion(0,0,0,0);break;case i.ANIMATIONTYPE_VECTOR3:l=e.Vector3.Zero();break;case i.ANIMATIONTYPE_VECTOR2:l=e.Vector2.Zero();break;case i.ANIMATIONTYPE_SIZE:l=e.Size.Zero();break;case i.ANIMATIONTYPE_COLOR3:l=e.Color3.Black()}var g=d/u>>0,v=h?r+d%u:n,y=this._interpolate(v,g,this.loopMode,l,f);this.setValue(y);for(var x=0;x<this._events.length;x++)if(v>=this._events[x].frame){var b=this._events[x];b.isDone||(b.onlyOnce&&(this._events.splice(x,1),x--),b.isDone=!0,b.action())}else this._events[x].isDone&&!this._events[x].onlyOnce&&(this._events[x].isDone=!1);return h||(this._stopped=!0),h},i.prototype.serialize=function(){var e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode;var t=this.dataType;e.keys=[];for(var r=this.getKeys(),n=0;n<r.length;n++){var o=r[n],s={};switch(s.frame=o.frame,t){case i.ANIMATIONTYPE_FLOAT:s.values=[o.value];break;case i.ANIMATIONTYPE_QUATERNION:case i.ANIMATIONTYPE_MATRIX:case i.ANIMATIONTYPE_VECTOR3:case i.ANIMATIONTYPE_COLOR3:s.values=o.value.asArray()}e.keys.push(s)}e.ranges=[];for(var a in this._ranges){var h={};h.name=a,h.from=this._ranges[a].from,h.to=this._ranges[a].to,e.ranges.push(h)}return e},Object.defineProperty(i,"ANIMATIONTYPE_FLOAT",{get:function(){return i._ANIMATIONTYPE_FLOAT},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_VECTOR3",{get:function(){return i._ANIMATIONTYPE_VECTOR3},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_VECTOR2",{get:function(){return i._ANIMATIONTYPE_VECTOR2},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_SIZE",{get:function(){return i._ANIMATIONTYPE_SIZE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_QUATERNION",{get:function(){return i._ANIMATIONTYPE_QUATERNION},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_MATRIX",{get:function(){return i._ANIMATIONTYPE_MATRIX},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONTYPE_COLOR3",{get:function(){return i._ANIMATIONTYPE_COLOR3},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_RELATIVE",{get:function(){return i._ANIMATIONLOOPMODE_RELATIVE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_CYCLE",{get:function(){return i._ANIMATIONLOOPMODE_CYCLE},enumerable:!0,configurable:!0}),Object.defineProperty(i,"ANIMATIONLOOPMODE_CONSTANT",{get:function(){return i._ANIMATIONLOOPMODE_CONSTANT},enumerable:!0,configurable:!0}),i.Parse=function(t){var r,n,o=new i(t.name,t.property,t.framePerSecond,t.dataType,t.loopBehavior),s=t.dataType,a=[];for(n=0;n<t.keys.length;n++){var h=t.keys[n];switch(s){case i.ANIMATIONTYPE_FLOAT:r=h.values[0];break;case i.ANIMATIONTYPE_QUATERNION:r=e.Quaternion.FromArray(h.values);break;case i.ANIMATIONTYPE_MATRIX:r=e.Matrix.FromArray(h.values);break;case i.ANIMATIONTYPE_COLOR3:r=e.Color3.FromArray(h.values);break;case i.ANIMATIONTYPE_VECTOR3:default:r=e.Vector3.FromArray(h.values)}a.push({frame:h.frame,value:r})}if(o.setKeys(a),t.ranges)for(n=0;n<t.ranges.length;n++)r=t.ranges[n],o.createRange(r.name,r.from,r.to);return o},i.AppendSerializedAnimations=function(e,t){if(e.animations){t.animations=[];for(var i=0;i<e.animations.length;i++){var r=e.animations[i];t.animations.push(r.serialize())}}},i._ANIMATIONTYPE_FLOAT=0,i._ANIMATIONTYPE_VECTOR3=1,i._ANIMATIONTYPE_QUATERNION=2,i._ANIMATIONTYPE_MATRIX=3,i._ANIMATIONTYPE_COLOR3=4,i._ANIMATIONTYPE_VECTOR2=5,i._ANIMATIONTYPE_SIZE=6,i._ANIMATIONLOOPMODE_RELATIVE=0,i._ANIMATIONLOOPMODE_CYCLE=1,i._ANIMATIONLOOPMODE_CONSTANT=2,i})();e.Animation=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i,r,n,o,s,a){void 0===i&&(i=0),void 0===r&&(r=100),void 0===n&&(n=!1),void 0===o&&(o=1),this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=n,this.speedRatio=o,this.onAnimationEnd=s,this._animations=new Array,this._paused=!1,this.animationStarted=!1,a&&this.appendAnimations(t,a),this._scene=e,e._activeAnimatables.push(this)}return e.prototype.getAnimations=function(){return this._animations},e.prototype.appendAnimations=function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r._target=e,this._animations.push(r)}},e.prototype.getAnimationByTargetProperty=function(e){for(var t=this._animations,i=0;i<t.length;i++)if(t[i].targetProperty===e)return t[i];return null},e.prototype.reset=function(){for(var e=this._animations,t=0;t<e.length;t++)e[t].reset();this._localDelayOffset=null,this._pausedDelay=null},e.prototype.enableBlending=function(e){for(var t=this._animations,i=0;i<t.length;i++)t[i].enableBlending=!0,t[i].blendingSpeed=e},e.prototype.disableBlending=function(){for(var e=this._animations,t=0;t<e.length;t++)e[t].enableBlending=!1},e.prototype.goToFrame=function(e){var t=this._animations;if(t[0]){var i=t[0].framePerSecond,r=t[0].currentFrame,n=e-r,o=1e3*n/i;this._localDelayOffset-=o}for(var s=0;s<t.length;s++)t[s].goToFrame(e)},e.prototype.pause=function(){this._paused||(this._paused=!0)},e.prototype.restart=function(){this._paused=!1},e.prototype.stop=function(e){var t=this._scene._activeAnimatables.indexOf(this);if(t>-1){for(var i=this._animations,r=0,t=i.length-1;t>=0;t--)"string"==typeof e&&i[t].name!=e||(i[t].reset(),i.splice(t,1),r++);i.length==r&&(this._scene._activeAnimatables.splice(t,1),this.onAnimationEnd&&this.onAnimationEnd())}},e.prototype._animate=function(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay||(this._pausedDelay=e),!0;this._localDelayOffset?this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null):this._localDelayOffset=e;var t,i=!1,r=this._animations;for(t=0;t<r.length;t++){var n=r[t],o=n.animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this.speedRatio);i=i||o}return this.animationStarted=i,i||(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1)),!i&&this.onAnimationEnd&&(this.onAnimationEnd(),this.onAnimationEnd=null),i},e})();e.Animatable=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._easingMode=e.EASINGMODE_EASEIN}return Object.defineProperty(e,"EASINGMODE_EASEIN",{get:function(){return e._EASINGMODE_EASEIN},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EASINGMODE_EASEOUT",{get:function(){return e._EASINGMODE_EASEOUT},enumerable:!0,configurable:!0}),Object.defineProperty(e,"EASINGMODE_EASEINOUT",{get:function(){return e._EASINGMODE_EASEINOUT},enumerable:!0,configurable:!0}),e.prototype.setEasingMode=function(e){var t=Math.min(Math.max(e,0),2);this._easingMode=t},e.prototype.getEasingMode=function(){return this._easingMode},e.prototype.easeInCore=function(e){throw new Error("You must implement this method")},e.prototype.ease=function(t){switch(this._easingMode){case e.EASINGMODE_EASEIN:return this.easeInCore(t);case e.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-t)}return t>=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e._EASINGMODE_EASEIN=0,e._EASINGMODE_EASEOUT=1,e._EASINGMODE_EASEINOUT=2,e})();e.EasingFunction=t;var i=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t})(t);e.CircleEase=i;var r=(function(e){function t(t){void 0===t&&(t=1),e.call(this),this.amplitude=t}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t})(t);e.BackEase=r;var n=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2),e.call(this),this.bounces=t,this.bounciness=i}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),h=Math.floor(a),c=h+1,l=(1-Math.pow(i,h))/(n*o),u=(1-Math.pow(i,c))/(n*o),d=.5*(l+u),f=e-d,p=d-l;return-Math.pow(1/i,t-h)/(p*p)*(f-p)*(f+p)},t})(t);e.BounceEase=n;var o=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e},t})(t);e.CubicEase=o;var s=(function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3),e.call(this),this.oscillations=t,this.springiness=i}return __extends(t,e),t.prototype.easeInCore=function(e){var t,i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return t=0==r?e:(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)},t})(t);e.ElasticEase=s;var a=(function(e){function t(t){void 0===t&&(t=2),e.call(this),this.exponent=t}return __extends(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t})(t);e.ExponentialEase=a;var h=(function(e){function t(t){void 0===t&&(t=2),e.call(this),this.power=t}return __extends(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t})(t);e.PowerEase=h;var c=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e},t})(t);e.QuadraticEase=c;var l=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t})(t);e.QuarticEase=l;var u=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t})(t);e.QuinticEase=u;var d=(function(e){function t(){e.apply(this,arguments)}return __extends(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t})(t);e.SineEase=d;var f=(function(t){function i(e,i,r,n){void 0===e&&(e=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1),t.call(this),this.x1=e,this.y1=i,this.x2=r,this.y2=n}return __extends(i,t),i.prototype.easeInCore=function(t){return e.BezierCurve.interpolate(t,this.x1,this.y1,this.x2,this.y2)},i})(t);e.BezierCurveEase=f})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){t.call(this,i,r.getScene()),this.name=i,this.children=new Array,this.animations=new Array,this._worldTransform=new e.Matrix,this._absoluteTransform=new e.Matrix,this._invertedAbsoluteTransform=new e.Matrix,this._scaleMatrix=e.Matrix.Identity(),this._scaleVector=new e.Vector3(1,1,1),this._negateScaleChildren=new e.Vector3(1,1,1),this._scalingDeterminant=1,this._syncScaleVector=function(){var t=this.getLocalMatrix(),i=t.m[0]*t.m[0]+t.m[1]*t.m[1]+t.m[2]*t.m[2],r=t.m[4]*t.m[4]+t.m[5]*t.m[5]+t.m[6]*t.m[6],n=t.m[8]*t.m[8]+t.m[9]*t.m[9]+t.m[10]*t.m[10],o=t.m[0]*t.m[1]*t.m[2]*t.m[3]<0?-1:1,s=t.m[4]*t.m[5]*t.m[6]*t.m[7]<0?-1:1,a=t.m[8]*t.m[9]*t.m[10]*t.m[11]<0?-1:1;this._scaleVector.x=o*Math.sqrt(i),this._scaleVector.y=s*Math.sqrt(r),this._scaleVector.z=a*Math.sqrt(n),this._parent&&(this._scaleVector.x/=this._parent._negateScaleChildren.x,this._scaleVector.y/=this._parent._negateScaleChildren.y,this._scaleVector.z/=this._parent._negateScaleChildren.z),e.Matrix.FromValuesToRef(this._scaleVector.x,0,0,0,0,this._scaleVector.y,0,0,0,0,this._scaleVector.z,0,0,0,0,1,this._scaleMatrix)},this._skeleton=r,this._matrix=o,this._baseMatrix=o,this._restPose=s?s:o.clone(),r.bones.push(this),n?(this._parent=n,n.children.push(this)):this._parent=null,this._updateDifferenceMatrix(),this.getAbsoluteTransform().determinant()<0&&(this._scalingDeterminant*=-1)}return __extends(i,t),i.prototype.getParent=function(){return this._parent},i.prototype.getLocalMatrix=function(){return this._matrix},i.prototype.getBaseMatrix=function(){return this._baseMatrix},i.prototype.getRestPose=function(){return this._restPose},i.prototype.returnToRest=function(){this.updateMatrix(this._restPose.clone())},i.prototype.getWorldMatrix=function(){return this._worldTransform},i.prototype.getInvertedAbsoluteTransform=function(){return this._invertedAbsoluteTransform},i.prototype.getAbsoluteTransform=function(){return this._absoluteTransform},i.prototype.updateMatrix=function(e,t){void 0===t&&(t=!0),this._baseMatrix=e.clone(),this._matrix=e.clone(),this._skeleton._markAsDirty(),t&&this._updateDifferenceMatrix()},i.prototype._updateDifferenceMatrix=function(e){e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);for(var t=0;t<this.children.length;t++)this.children[t]._updateDifferenceMatrix()},i.prototype.markAsDirty=function(){this._currentRenderId++,this._skeleton._markAsDirty()},i.prototype.copyAnimationRange=function(t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=null),0===this.animations.length&&(this.animations.push(new e.Animation(this.name,"_matrix",t.animations[0].framePerSecond,e.Animation.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));var s=t.animations[0].getRange(i);if(!s)return!1;for(var a,h,c,l=s.from,u=s.to,d=t.animations[0].getKeys(),f=t.length,p=t.getParent(),_=this.getParent(),m=n&&p&&f&&this.length&&f!==this.length,g=m?_.length/p.length:null,v=n&&!_&&o&&(1!==o.x||1!==o.y||1!==o.z),y=this.animations[0].getKeys(),x=0,b=d.length;x<b;x++)a=d[x],a.frame>=l&&a.frame<=u&&(n?(c=a.value.clone(),m?(h=c.getTranslation(),c.setTranslation(h.scaleInPlace(g))):v?(h=c.getTranslation(),c.setTranslation(h.multiplyInPlace(o))):c=a.value):c=a.value,y.push({frame:a.frame+r,value:c}));return this.animations[0].createRange(i,l+r,u+r),!0},i.prototype.translate=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix();if(i==e.Space.LOCAL)n.m[12]+=t.x,n.m[13]+=t.y,n.m[14]+=t.z;else{this._skeleton.computeAbsoluteTransforms();
var o=e.Tmp.Matrix[0],s=e.Tmp.Vector3[0];r?(o.copyFrom(this._parent.getAbsoluteTransform()),o.multiplyToRef(r.getWorldMatrix(),o)):o.copyFrom(this._parent.getAbsoluteTransform()),o.m[12]=0,o.m[13]=0,o.m[14]=0,o.invert(),e.Vector3.TransformCoordinatesToRef(t,o,s),n.m[12]+=s.x,n.m[13]+=s.y,n.m[14]+=s.z}this.markAsDirty()},i.prototype.setPosition=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix();if(i==e.Space.LOCAL)n.m[12]=t.x,n.m[13]=t.y,n.m[14]=t.z;else{this._skeleton.computeAbsoluteTransforms();var o=e.Tmp.Matrix[0],s=e.Tmp.Vector3[0];r?(o.copyFrom(this._parent.getAbsoluteTransform()),o.multiplyToRef(r.getWorldMatrix(),o)):o.copyFrom(this._parent.getAbsoluteTransform()),o.invert(),e.Vector3.TransformCoordinatesToRef(t,o,s),n.m[12]=s.x,n.m[13]=s.y,n.m[14]=s.z}this.markAsDirty()},i.prototype.setAbsolutePosition=function(t,i){this.setPosition(t,e.Space.WORLD,i)},i.prototype.setScale=function(e,t,i,r){void 0===r&&(r=!1),this.animations[0]&&!this.animations[0].isStopped()&&(r||(this._negateScaleChildren.x=1/e,this._negateScaleChildren.y=1/t,this._negateScaleChildren.z=1/i),this._syncScaleVector()),this.scale(e/this._scaleVector.x,t/this._scaleVector.y,i/this._scaleVector.z,r)},i.prototype.scale=function(t,i,r,n){void 0===n&&(n=!1);var o=this.getLocalMatrix(),s=e.Tmp.Matrix[0];s.copyFrom(o);var a=e.Tmp.Matrix[1];a.copyFrom(s),a.invert();var h=e.Tmp.Matrix[2];e.Matrix.FromValuesToRef(t,0,0,0,0,i,0,0,0,0,r,0,0,0,0,1,h),this._scaleMatrix.multiplyToRef(h,this._scaleMatrix),this._scaleVector.x*=t,this._scaleVector.y*=i,this._scaleVector.z*=r,o.multiplyToRef(a,o),o.multiplyToRef(h,o),o.multiplyToRef(s,o);var c=this.getParent();c?o.multiplyToRef(c.getAbsoluteTransform(),this.getAbsoluteTransform()):this.getAbsoluteTransform().copyFrom(o);var l=this.children.length;h.invert();for(var u=0;u<l;u++){var d=this.children[u],f=d.getLocalMatrix();f.multiplyToRef(h,f);var p=d.getLocalMatrix();p.m[12]*=t,p.m[13]*=i,p.m[14]*=r}if(this.computeAbsoluteTransforms(),n)for(var u=0;u<l;u++)this.children[u].scale(t,i,r,n);this.markAsDirty()},i.prototype.setYawPitchRoll=function(t,i,r,n,o){void 0===n&&(n=e.Space.LOCAL);var s=e.Tmp.Matrix[0];e.Matrix.RotationYawPitchRollToRef(t,i,r,s);var a=e.Tmp.Matrix[1];this._getNegativeRotationToRef(a,n,o),a.multiplyToRef(s,s),this._rotateWithMatrix(s,n,o)},i.prototype.rotate=function(t,i,r,n){void 0===r&&(r=e.Space.LOCAL);var o=e.Tmp.Matrix[0];o.m[12]=0,o.m[13]=0,o.m[14]=0,e.Matrix.RotationAxisToRef(t,i,o),this._rotateWithMatrix(o,r,n)},i.prototype.setAxisAngle=function(t,i,r,n){void 0===r&&(r=e.Space.LOCAL);var o=e.Tmp.Matrix[0];e.Matrix.RotationAxisToRef(t,i,o);var s=e.Tmp.Matrix[1];this._getNegativeRotationToRef(s,r,n),s.multiplyToRef(o,o),this._rotateWithMatrix(o,r,n)},i.prototype.setRotation=function(t,i,r){void 0===i&&(i=e.Space.LOCAL),this.setYawPitchRoll(t.y,t.x,t.z,i,r)},i.prototype.setRotationQuaternion=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=e.Tmp.Matrix[0];this._getNegativeRotationToRef(n,i,r);var o=e.Tmp.Matrix[1];e.Matrix.FromQuaternionToRef(t,o),n.multiplyToRef(o,o),this._rotateWithMatrix(o,i,r)},i.prototype.setRotationMatrix=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=e.Tmp.Matrix[0];this._getNegativeRotationToRef(n,i,r);var o=e.Tmp.Matrix[1];o.copyFrom(t),n.multiplyToRef(t,o),this._rotateWithMatrix(o,i,r)},i.prototype._rotateWithMatrix=function(t,i,r){void 0===i&&(i=e.Space.LOCAL);var n=this.getLocalMatrix(),o=n.m[12],s=n.m[13],a=n.m[14],h=this.getParent(),c=e.Tmp.Matrix[3],l=e.Tmp.Matrix[4];h?(i==e.Space.WORLD?r?(c.copyFrom(r.getWorldMatrix()),h.getAbsoluteTransform().multiplyToRef(c,c)):c.copyFrom(h.getAbsoluteTransform()):c=h._scaleMatrix,l.copyFrom(c),l.invert(),n.multiplyToRef(c,n),n.multiplyToRef(t,n),n.multiplyToRef(l,n)):i==e.Space.WORLD&&r?(c.copyFrom(r.getWorldMatrix()),l.copyFrom(c),l.invert(),n.multiplyToRef(c,n),n.multiplyToRef(t,n),n.multiplyToRef(l,n)):n.multiplyToRef(t,n),n.m[12]=o,n.m[13]=s,n.m[14]=a,this.computeAbsoluteTransforms(),this.markAsDirty()},i.prototype._getNegativeRotationToRef=function(t,i,r){if(void 0===i&&(i=e.Space.LOCAL),i==e.Space.WORLD){var n=e.Tmp.Matrix[2];if(n.copyFrom(this._scaleMatrix),t.copyFrom(this.getAbsoluteTransform()),r){t.multiplyToRef(r.getWorldMatrix(),t);var o=e.Tmp.Matrix[3];e.Matrix.ScalingToRef(r.scaling.x,r.scaling.y,r.scaling.z,o),n.multiplyToRef(o,n)}t.invert(),n.m[0]*=this._scalingDeterminant,t.multiplyToRef(n,t)}else{t.copyFrom(this.getLocalMatrix()),t.invert();var n=e.Tmp.Matrix[2];if(n.copyFrom(this._scaleMatrix),this._parent){var s=e.Tmp.Matrix[3];s.copyFrom(this._parent._scaleMatrix),s.invert(),s.multiplyToRef(t,t)}else n.m[0]*=this._scalingDeterminant;t.multiplyToRef(n,t)}},i.prototype.getScale=function(){return this._scaleVector.clone()},i.prototype.getScaleToRef=function(e){e.copyFrom(this._scaleVector)},i.prototype.getPosition=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Vector3.Zero();return this.getPositionToRef(t,i,r),r},i.prototype.getPositionToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL){var n=this.getLocalMatrix();r.x=n.m[12],r.y=n.m[13],r.z=n.m[14]}else{this._skeleton.computeAbsoluteTransforms();var o=e.Tmp.Matrix[0];i?(o.copyFrom(this.getAbsoluteTransform()),o.multiplyToRef(i.getWorldMatrix(),o)):o=this.getAbsoluteTransform(),r.x=o.m[12],r.y=o.m[13],r.z=o.m[14]}},i.prototype.getAbsolutePosition=function(t){var i=e.Vector3.Zero();return this.getPositionToRef(e.Space.WORLD,t,i),i},i.prototype.getAbsolutePositionToRef=function(t,i){this.getPositionToRef(e.Space.WORLD,t,i)},i.prototype.computeAbsoluteTransforms=function(){if(this._parent)this._matrix.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform);else{this._absoluteTransform.copyFrom(this._matrix);var e=this._skeleton.getPoseMatrix();e&&this._absoluteTransform.multiplyToRef(e,this._absoluteTransform)}for(var t=this.children,i=t.length,r=0;r<i;r++)t[r].computeAbsoluteTransforms()},i.prototype.getDirection=function(t,i){var r=e.Vector3.Zero();return this.getDirectionToRef(t,i,r),r},i.prototype.getDirectionToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];n.copyFrom(this.getAbsoluteTransform()),i&&n.multiplyToRef(i.getWorldMatrix(),n),e.Vector3.TransformNormalToRef(t,n,r),r.normalize()},i.prototype.getRotation=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Vector3.Zero();return this.getRotationToRef(t,i,r),r},i.prototype.getRotationToRef=function(t,i,r){void 0===t&&(t=e.Space.LOCAL);var n=e.Tmp.Quaternion[0];this.getRotationQuaternionToRef(t,i,n),n.toEulerAnglesToRef(r)},i.prototype.getRotationQuaternion=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Quaternion.Identity();return this.getRotationQuaternionToRef(t,i,r),r},i.prototype.getRotationQuaternionToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL)this.getLocalMatrix().decompose(e.Tmp.Vector3[0],r,e.Tmp.Vector3[1]);else{var n=e.Tmp.Matrix[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.m[0]*=this._scalingDeterminant,n.m[1]*=this._scalingDeterminant,n.m[2]*=this._scalingDeterminant,n.decompose(e.Tmp.Vector3[0],r,e.Tmp.Vector3[1])}},i.prototype.getRotationMatrix=function(t,i){void 0===t&&(t=e.Space.LOCAL);var r=e.Matrix.Identity();return this.getRotationMatrixToRef(t,i,r),r},i.prototype.getRotationMatrixToRef=function(t,i,r){if(void 0===t&&(t=e.Space.LOCAL),t==e.Space.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(r);else{var n=e.Tmp.Matrix[0],o=this.getAbsoluteTransform();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.m[0]*=this._scalingDeterminant,n.m[1]*=this._scalingDeterminant,n.m[2]*=this._scalingDeterminant,n.getRotationMatrixToRef(r)}},i.prototype.getAbsolutePositionFromLocal=function(t,i){var r=e.Vector3.Zero();return this.getAbsolutePositionFromLocalToRef(t,i,r),r},i.prototype.getAbsolutePositionFromLocalToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];i?(n.copyFrom(this.getAbsoluteTransform()),n.multiplyToRef(i.getWorldMatrix(),n)):n=this.getAbsoluteTransform(),e.Vector3.TransformCoordinatesToRef(t,n,r)},i.prototype.getLocalPositionFromAbsolute=function(t,i){var r=e.Vector3.Zero();return this.getLocalPositionFromAbsoluteToRef(t,i,r),r},i.prototype.getLocalPositionFromAbsoluteToRef=function(t,i,r){this._skeleton.computeAbsoluteTransforms();var n=e.Tmp.Matrix[0];n.copyFrom(this.getAbsoluteTransform()),i&&n.multiplyToRef(i.getWorldMatrix(),n),n.invert(),e.Vector3.TransformCoordinatesToRef(t,n,r)},i})(e.Node);e.Bone=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){if(this.targetPosition=e.Vector3.Zero(),this.poleTargetPosition=e.Vector3.Zero(),this.poleTargetLocalOffset=e.Vector3.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=e.Quaternion.Identity(),this._bone1Mat=e.Matrix.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._tmpVec1=e.Vector3.Zero(),this._tmpVec2=e.Vector3.Zero(),this._tmpVec3=e.Vector3.Zero(),this._tmpVec4=e.Vector3.Zero(),this._tmpVec5=e.Vector3.Zero(),this._tmpMat1=e.Matrix.Identity(),this._tmpMat2=e.Matrix.Identity(),this._tmpQuat1=e.Quaternion.Identity(),this._rightHandedSystem=!1,this._bendAxis=e.Vector3.Right(),this._slerping=!1,this._bone2=i,this._bone1=i.getParent(),this.mesh=t,i.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=1),this._bone1.length){var n=this._bone1.getScale(),o=this._bone2.getScale();this._bone1Length=this._bone1.length*n.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*o.y*this.mesh.scaling.y}else if(this._bone1.children[0]){t.computeWorldMatrix(!0);var s=this._bone2.children[0].getAbsolutePosition(t),a=this._bone2.getAbsolutePosition(t),h=this._bone1.getAbsolutePosition(t);this._bone1Length=e.Vector3.Distance(s,a),this._bone2Length=e.Vector3.Distance(a,h)}this._bone1.getRotationMatrixToRef(e.Space.WORLD,t,this._bone1Mat),this.maxAngle=Math.PI,r&&(r.targetMesh&&(this.targetMesh=r.targetMesh,this.targetMesh.computeWorldMatrix(!0)),r.poleTargetMesh?(this.poleTargetMesh=r.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):r.poleTargetBone?this.poleTargetBone=r.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),r.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(r.poleTargetLocalOffset),r.poleAngle&&(this.poleAngle=r.poleAngle),r.bendAxis&&this._bendAxis.copyFrom(r.bendAxis),r.maxAngle&&(this.maxAngle=r.maxAngle),r.slerpAmount&&(this.slerpAmount=r.slerpAmount))}return Object.defineProperty(t.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),t.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},t.prototype.update=function(){var t=this._bone1,i=this.targetPosition,r=this.poleTargetPosition,n=this._tmpMat1,o=this._tmpMat2;this.targetMesh&&i.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,r):this.poleTargetMesh&&e.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),r);var s=this._tmpVec1,a=this._tmpVec2,h=this._tmpVec3,c=this._tmpVec4,l=this._tmpVec5;t.getAbsolutePositionToRef(this.mesh,s),r.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),i.subtractToRef(s,c),c.normalize(),e.Vector3.CrossToRef(c,l,a),a.normalize(),e.Vector3.CrossToRef(c,a,h),h.normalize(),e.Matrix.FromXYZAxesToRef(h,c,a,n);var u=this._bone1Length,d=this._bone2Length,f=e.Vector3.Distance(s,i);this._maxReach>0&&(f=Math.min(this._maxReach,f));var p=(d*d+f*f-u*u)/(2*d*f),_=(f*f+u*u-d*d)/(2*f*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);var m=Math.acos(p),g=Math.acos(_),v=-m-g;this._rightHandedSystem?(e.Matrix.RotationYawPitchRollToRef(0,0,.5*Math.PI,o),o.multiplyToRef(n,n),e.Matrix.RotationAxisToRef(this._bendAxis,g,o),o.multiplyToRef(n,n)):(this._tmpVec1.copyFrom(this._bendAxis),this._tmpVec1.x*=-1,e.Matrix.RotationAxisToRef(this._tmpVec1,-g,o),o.multiplyToRef(n,n)),this.poleAngle&&(e.Matrix.RotationAxisToRef(c,this.poleAngle,o),n.multiplyToRef(o,n)),this.slerpAmount<1?(this._slerping||e.Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),e.Quaternion.FromRotationMatrixToRef(n,this._tmpQuat1),e.Quaternion.SlerpToRef(this._bone1Quat,this._tmpQuat1,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,e.Space.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(n,e.Space.WORLD,this.mesh),this._bone1Mat.copyFrom(n),this._slerping=!1),this._bone2.setAxisAngle(this._bendAxis,v,e.Space.LOCAL),this._bone2Ang=v},t})();e.BoneIKController=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){this.upAxis=e.Vector3.Up(),this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this._tmpVec1=e.Vector3.Zero(),this._tmpVec2=e.Vector3.Zero(),this._tmpVec3=e.Vector3.Zero(),this._tmpVec4=e.Vector3.Zero(),this._tmpMat1=e.Matrix.Identity(),this._tmpMat2=e.Matrix.Identity(),this.mesh=t,this.bone=i,this.target=r,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll))}return t.prototype.update=function(){var t=this.bone,i=this.target,r=this._tmpVec1,n=this._tmpVec2,o=this._tmpVec3,s=this._tmpVec4,a=this._tmpMat1,h=this._tmpMat2;t.getAbsolutePositionToRef(this.mesh,r),i.subtractToRef(r,n),n.normalize(),e.Vector3.CrossToRef(this.upAxis,n,o),o.normalize(),e.Vector3.CrossToRef(n,o,s),s.normalize(),e.Matrix.FromXYZAxesToRef(o,s,n,a),(this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(e.Matrix.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,h),h.multiplyToRef(a,a)),this.bone.setRotationMatrix(a,e.Space.WORLD,this.mesh)},t})();e.BoneLookController=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.id=i,this.bones=new Array,this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=e.Matrix.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this.bones=[],this._scene=r,r.skeletons.push(this),this._isDirty=!0}return t.prototype.getTransformMatrices=function(e){return this.needInitialSkinMatrix&&e._bonesTransformMatrices?e._bonesTransformMatrices:this._transformMatrices},t.prototype.getScene=function(){return this._scene},t.prototype.toString=function(e){var t="Name: "+this.name+", nBones: "+this.bones.length;if(t+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},t.prototype.getBoneIndexByName=function(e){for(var t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1},t.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=new e.AnimationRange(t,i,r);for(var n=0,o=this.bones.length;n<o;n++)this.bones[n].animations[0]&&this.bones[n].animations[0].createRange(t,i,r)}},t.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=void 0},t.prototype.getAnimationRange=function(e){return this._ranges[e]},t.prototype.getAnimationRanges=function(){var e,t=[],i=0;for(e in this._ranges)t[i]=this._ranges[e],i++;return t},t.prototype.copyAnimationRange=function(t,i,r){if(void 0===r&&(r=!1),this._ranges[i]||!t.getAnimationRange(i))return!1;var n,o,s=!0,a=this._getHighestAnimationFrame()+1,h={},c=t.bones;for(o=0,n=c.length;o<n;o++)h[c[o].name]=c[o];this.bones.length!==c.length&&(e.Tools.Warn("copyAnimationRange: this rig has "+this.bones.length+" bones, while source as "+c.length),s=!1);var l=r&&this.dimensionsAtRest&&t.dimensionsAtRest?this.dimensionsAtRest.divide(t.dimensionsAtRest):null;for(o=0,n=this.bones.length;o<n;o++){var u=this.bones[o].name,d=h[u];d?s=s&&this.bones[o].copyAnimationRange(d,i,a,r,l):(e.Tools.Warn("copyAnimationRange: not same rig, missing source bone "+u),s=!1)}var f=t.getAnimationRange(i);return this._ranges[i]=new e.AnimationRange(i,f.from+a,f.to+a),s},t.prototype.returnToRest=function(){for(var e=0;e<this.bones.length;e++)this.bones[e].returnToRest()},t.prototype._getHighestAnimationFrame=function(){for(var e=0,t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){var r=this.bones[t].animations[0].getHighestFrame();e<r&&(e=r)}return e},t.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},t.prototype._markAsDirty=function(){this._isDirty=!0},t.prototype._registerMeshWithPoseMatrix=function(e){this._meshesWithPoseMatrix.push(e)},t.prototype._unregisterMeshWithPoseMatrix=function(e){var t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)},t.prototype._computeTransformMatrices=function(e,t){for(var i=0;i<this.bones.length;i++){var r=this.bones[i],n=r.getParent();n?r.getLocalMatrix().multiplyToRef(n.getWorldMatrix(),r.getWorldMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getWorldMatrix()):r.getWorldMatrix().copyFrom(r.getLocalMatrix()),r.getInvertedAbsoluteTransform().multiplyToArray(r.getWorldMatrix(),e,16*i)}this._identity.copyToArray(e,16*this.bones.length)},t.prototype.prepare=function(){if(this._isDirty){if(this.needInitialSkinMatrix)for(var t=0;t<this._meshesWithPoseMatrix.length;t++){var i=this._meshesWithPoseMatrix[t];i._bonesTransformMatrices&&i._bonesTransformMatrices.length===16*(this.bones.length+1)||(i._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)));for(var r=i.getPoseMatrix(),n=0;n<this.bones.length;n++){var o=this.bones[n];if(!o.getParent()){var s=o.getBaseMatrix();s.multiplyToRef(r,e.Tmp.Matrix[0]),o._updateDifferenceMatrix(e.Tmp.Matrix[0])}}this._computeTransformMatrices(i._bonesTransformMatrices,r)}else this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1))),this._computeTransformMatrices(this._transformMatrices,null);this._isDirty=!1,this._scene._activeBones.addCount(this.bones.length,!1)}},t.prototype.getAnimatables=function(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(var e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables},t.prototype.clone=function(i,r){var n=new t(i,r||i,this._scene);n.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var o=0;o<this.bones.length;o++){var s=this.bones[o],a=null;if(s.getParent()){var h=this.bones.indexOf(s.getParent());a=n.bones[h]}var c=new e.Bone(s.name,n,a,s.getBaseMatrix().clone(),s.getRestPose().clone());e.Tools.DeepCopy(s.animations,c.animations)}if(this._ranges){n._ranges={};for(var l in this._ranges)n._ranges[l]=this._ranges[l].clone()}return this._isDirty=!0,n},t.prototype.enableBlending=function(e){void 0===e&&(e=.01),this.bones.forEach((function(t){t.animations.forEach((function(t){t.enableBlending=!0,t.blendingSpeed=e}))}))},t.prototype.dispose=function(){this._meshesWithPoseMatrix=[],this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this)},t.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,e.dimensionsAtRest=this.dimensionsAtRest,e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var t=0;t<this.bones.length;t++){var i=this.bones[t],r={parentBoneIndex:i.getParent()?this.bones.indexOf(i.getParent()):-1,name:i.name,matrix:i.getLocalMatrix().toArray(),rest:i.getRestPose().toArray()};e.bones.push(r),i.length&&(r.length=i.length),i.animations&&i.animations.length>0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(var n in this._ranges){var o={};o.name=n,o.from=this._ranges[n].from,o.to=this._ranges[n].to,e.ranges.push(o)}}return e},t.Parse=function(i,r){var n=new t(i.name,i.id,r);i.dimensionsAtRest&&(n.dimensionsAtRest=e.Vector3.FromArray(i.dimensionsAtRest)),n.needInitialSkinMatrix=i.needInitialSkinMatrix;var o;for(o=0;o<i.bones.length;o++){var s=i.bones[o],a=null;s.parentBoneIndex>-1&&(a=n.bones[s.parentBoneIndex]);var h=s.rest?e.Matrix.FromArray(s.rest):null,c=new e.Bone(s.name,n,a,e.Matrix.FromArray(s.matrix),h);s.length&&(c.length=s.length),s.animation&&c.animations.push(e.Animation.Parse(s.animation))}if(i.ranges)for(o=0;o<i.ranges.length;o++){var l=i.ranges[o];n.createAnimationRange(l.name,l.from,l.to)}return n},t.prototype.computeAbsoluteTransforms=function(e){void 0===e&&(e=!1);var t=this._scene.getRenderId();(this._lastAbsoluteTransformsUpdateId!=t||e)&&(this.bones[0].computeAbsoluteTransforms(),this._lastAbsoluteTransformsUpdateId=t)},t.prototype.getPoseMatrix=function(){var e;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},t})();e.Skeleton=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a,h,c,l,u){void 0===a&&(a=e.Texture.NEAREST_SAMPLINGMODE),void 0===u&&(u=e.Engine.TEXTURETYPE_UNSIGNED_INT),this.name=t,this.width=-1,this.height=-1,this.enablePixelPerfectMode=!1,this._reusable=!1,this._textures=new e.SmartArray(2),this._currentRenderTextureInd=0,this._scaleRatio=new e.Vector2(1,1),this.onActivateObservable=new e.Observable,this.onSizeChangedObservable=new e.Observable,this.onApplyObservable=new e.Observable,this.onBeforeRenderObservable=new e.Observable,this.onAfterRenderObservable=new e.Observable,null!=s?(this._camera=s,this._scene=s.getScene(),s.attachPostProcess(this),this._engine=this._scene.getEngine()):this._engine=h,this._options=o,this.renderTargetSamplingMode=a?a:e.Texture.NEAREST_SAMPLINGMODE,this._reusable=c||!1,this._textureType=u,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=i,this._parameters=r||[],this._parameters.push("scale"),this.updateEffect(l)}return Object.defineProperty(t.prototype,"onActivate",{set:function(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),this._onActivateObserver=this.onActivateObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onSizeChanged",{set:function(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onApply",{set:function(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),t.prototype.updateEffect=function(e){this._effect=this._engine.createEffect({vertex:"postprocess",fragment:this._fragmentUrl},["position"],this._parameters,this._samplers,void 0!==e?e:"")},t.prototype.isReusable=function(){return this._reusable},t.prototype.markTextureDirty=function(){this.width=-1},t.prototype.activate=function(t,i){t=t||this._camera;var r=t.getScene(),n=t.getEngine().getCaps().maxTextureSize,o=(i?i._width:this._engine.getRenderingCanvas().width)*this._options|0,s=(i?i._height:this._engine.getRenderingCanvas().height)*this._options|0,a=this._options.width||o,h=this._options.height||s;if(this.renderTargetSamplingMode!==e.Texture.NEAREST_SAMPLINGMODE&&(this._options.width||(a=e.Tools.GetExponentOfTwo(a,n)),this._options.height||(h=e.Tools.GetExponentOfTwo(h,n))),this.width!==a||this.height!==h){if(this._textures.length>0){for(var c=0;c<this._textures.length;c++)this._engine._releaseTexture(this._textures.data[c]);this._textures.reset()}this.width=a,this.height=h;var l={width:this.width,height:this.height},u={generateMipMaps:!1,generateDepthBuffer:0===t._postProcesses.indexOf(this),generateStencilBuffer:0===t._postProcesses.indexOf(this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType};this._textures.push(this._engine.createRenderTargetTexture(l,u)),this._reusable&&this._textures.push(this._engine.createRenderTargetTexture(l,u)),this.onSizeChangedObservable.notifyObservers(this)}this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/a,s/h),this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd],0,o,s)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd])),this.onActivateObservable.notifyObservers(t),this.clearColor?this._engine.clear(this.clearColor,!0,!0,!0):this._engine.clear(r.clearColor,r.autoClear||r.forceWireframe,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2)},Object.defineProperty(t.prototype,"isSupported",{get:function(){return this._effect.isSupported},enumerable:!0,configurable:!0}),t.prototype.apply=function(){return this._effect.isReady()?(this._engine.enableEffect(this._effect),this._engine.setState(!1),this._engine.setAlphaMode(e.Engine.ALPHA_DISABLE),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._effect._bindTexture("textureSampler",this._textures.data[this._currentRenderTextureInd]),this._effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effect),this._effect):null},t.prototype.dispose=function(e){if(e=e||this._camera,this._textures.length>0){for(var t=0;t<this._textures.length;t++)this._engine._releaseTexture(this._textures.data[t]);this._textures.reset()}if(e){e.detachPostProcess(this);var i=e._postProcesses.indexOf(this);0===i&&e._postProcesses.length>0&&this._camera._postProcesses[0].markTextureDirty(),this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},t})();e.PostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._vertexBuffers={},this._scene=e}return t.prototype._prepareBuffers=function(){if(!this._vertexBuffers[e.VertexBuffer.PositionKind]){var t=[];t.push(1,1),t.push(-1,1),t.push(-1,-1),t.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(this._scene.getEngine(),t,e.VertexBuffer.PositionKind,(!1),(!1),2);var i=[];i.push(0),i.push(1),i.push(2),i.push(0),i.push(2),i.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(i)}},t.prototype._prepareFrame=function(e){var t=this._scene.activeCamera._postProcesses;return!(0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(this._scene.activeCamera,e),!0)},t.prototype.directRender=function(e,t){for(var i=this._scene.getEngine(),r=0;r<e.length;r++){r<e.length-1?e[r+1].activate(this._scene.activeCamera,t):t?i.bindFramebuffer(t):i.restoreDefaultFramebuffer();var n=e[r],o=n.apply();o&&(n.onBeforeRenderObservable.notifyObservers(o),this._prepareBuffers(),i.bindBuffers(this._vertexBuffers,this._indexBuffer,o),i.draw(!0,0,6),n.onAfterRenderObservable.notifyObservers(o))}i.setDepthBuffer(!0),i.setDepthWrite(!0)},t.prototype._finalizeFrame=function(e,t,i,r){if(r=r||this._scene.activeCamera._postProcesses,0!==r.length&&this._scene.postProcessesEnabled){for(var n=this._scene.getEngine(),o=0,s=r.length;o<s&&(o<s-1?r[o+1].activate(this._scene.activeCamera,t):t?n.bindFramebuffer(t,i):n.restoreDefaultFramebuffer(),!e);o++){var a=r[o],h=a.apply();h&&(a.onBeforeRenderObservable.notifyObservers(h),this._prepareBuffers(),n.bindBuffers(this._vertexBuffers,this._indexBuffer,h),n.draw(!0,0,6),a.onAfterRenderObservable.notifyObservers(h))}n.setDepthBuffer(!0),n.setDepthWrite(!0)}},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)},t})();e.PostProcessManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"pass",null,null,i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.PassPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}return Object.defineProperty(e.prototype,"physicsJoint",{get:function(){return this._physicsJoint},set:function(e){this._physicsJoint,this._physicsJoint=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"physicsPlugin",{set:function(e){this._physicsPlugin=e},enumerable:!0,configurable:!0}),e.prototype.executeNativeFunction=function(e){e(this._physicsPlugin.world,this._physicsJoint)},e.DistanceJoint=0,e.HingeJoint=1,e.BallAndSocketJoint=2,e.WheelJoint=3,e.SliderJoint=4,e.PrismaticJoint=5,e.UniversalJoint=6,e.Hinge2Joint=e.WheelJoint,e.PointToPointJoint=8,e.SpringJoint=9,e.LockJoint=10,e})();e.PhysicsJoint=t;var i=(function(e){function i(i){e.call(this,t.DistanceJoint,i)}return __extends(i,e),i.prototype.updateDistance=function(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)},i})(t);e.DistanceJoint=i;var r=(function(e){function t(t,i){e.call(this,t,i)}return __extends(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t})(t);e.MotorEnabledJoint=r;var n=(function(e){function i(i){e.call(this,t.HingeJoint,i)}return __extends(i,e),i.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e,t)},i.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},i})(r);e.HingeJoint=n;var o=(function(e){function i(i){e.call(this,t.Hinge2Joint,i)}return __extends(i,e),i.prototype.setMotor=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setMotor(this,e,t,i)},i.prototype.setLimit=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setLimit(this,e,t,i)},i})(r);e.Hinge2Joint=o})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){var o=this;return void 0===r&&(r={mass:0}),this.object=t,this.type=i,this._options=r,this._scene=n,this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=e.Vector3.Zero(),this._tmpPositionWithDelta=e.Vector3.Zero(),this._tmpRotationWithDelta=new e.Quaternion,this.beforeStep=function(){o.object.position.subtractToRef(o._deltaPosition,o._tmpPositionWithDelta),o._deltaRotationConjugated?o.object.rotationQuaternion.multiplyToRef(o._deltaRotationConjugated,o._tmpRotationWithDelta):o._tmpRotationWithDelta.copyFrom(o.object.rotationQuaternion),o._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(o,o._tmpPositionWithDelta,o._tmpRotationWithDelta),o._onBeforePhysicsStepCallbacks.forEach((function(e){e(o)}))},this.afterStep=function(){o._onAfterPhysicsStepCallbacks.forEach((function(e){e(o)})),o._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(o),o.object.position.addInPlace(o._deltaPosition),o._deltaRotation&&o.object.rotationQuaternion.multiplyInPlace(o._deltaRotation)},this.onCollide=function(e){if(o._onPhysicsCollideCallbacks.length){var t=o._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&o._onPhysicsCollideCallbacks.filter((function(e){return e.otherImpostors.indexOf(t)!==-1})).forEach((function(e){
e.callback(o,t)}))}},this.object?(!this._scene&&t.getScene&&(this._scene=t.getScene()),this._physicsEngine=this._scene.getPhysicsEngine(),void(this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=e.Quaternion.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new e.Quaternion),this._options.mass=void 0===r.mass?0:r.mass,this._options.friction=void 0===r.friction?.2:r.friction,this._options.restitution=void 0===r.restitution?.2:r.restitution,this._joints=[],this.object.parent||this._init()):e.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):void e.Tools.Error("No object was provided. A physics object is obligatory")}return t.prototype._init=function(){this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this.parent||this._physicsEngine.addImpostor(this)},t.prototype._getPhysicsParent=function(){if(this.object.parent instanceof e.AbstractMesh){var t=this.object.parent;return t.physicsImpostor}},t.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},t.prototype.setScalingUpdated=function(e){this.forceUpdate()},t.prototype.forceUpdate=function(){this._init(),this.parent&&this.parent.forceUpdate()},Object.defineProperty(t.prototype,"physicsBody",{get:function(){return this._parent?this._parent.physicsBody:this._physicsBody},set:function(e){this._physicsBody&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},set:function(e){this._parent=e},enumerable:!0,configurable:!0}),t.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},t.prototype.getObjectExtendSize=function(){return this.object.getBoundingInfo?(this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling)):t.DEFAULT_OBJECT_SIZE},t.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.center:this.object.position},t.prototype.getParam=function(e){return this._options[e]},t.prototype.setParam=function(e,t){this._options[e]=t,this._bodyUpdateRequired=!0},t.prototype.setMass=function(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)},t.prototype.getLinearVelocity=function(){return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this)},t.prototype.setLinearVelocity=function(e){this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)},t.prototype.getAngularVelocity=function(){return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this)},t.prototype.setAngularVelocity=function(e){this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)},t.prototype.executeNativeFunction=function(e){e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},t.prototype.registerBeforePhysicsStep=function(e){this._onBeforePhysicsStepCallbacks.push(e)},t.prototype.unregisterBeforePhysicsStep=function(t){var i=this._onBeforePhysicsStepCallbacks.indexOf(t);i>-1?this._onBeforePhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},t.prototype.unregisterAfterPhysicsStep=function(t){var i=this._onAfterPhysicsStepCallbacks.indexOf(t);i>-1?this._onAfterPhysicsStepCallbacks.splice(i,1):e.Tools.Warn("Function to remove was not found")},t.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},t.prototype.unregisterOnPhysicsCollide=function(t,i){var r=t instanceof Array?t:[t],n=this._onPhysicsCollideCallbacks.indexOf({callback:i,otherImpostors:r});n>-1?this._onPhysicsCollideCallbacks.splice(n,1):e.Tools.Warn("Function to remove was not found")},t.prototype.applyForce=function(e,t){this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t)},t.prototype.applyImpulse=function(e,t){this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t)},t.prototype.createJoint=function(t,i,r){var n=new e.PhysicsJoint(i,r);this.addJoint(t,n)},t.prototype.addJoint=function(e,t){this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine.addJoint(this,e,t)},t.prototype.sleep=function(){this._physicsEngine.getPhysicsPlugin().sleepBody(this)},t.prototype.wakeUp=function(){this._physicsEngine.getPhysicsPlugin().wakeUpBody(this)},t.prototype.clone=function(e){return e?new t(e,this.type,this._options,this._scene):null},t.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate())},t.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},t.prototype.setDeltaRotation=function(t){this._deltaRotation||(this._deltaRotation=new e.Quaternion),this._deltaRotation.copyFrom(t),this._deltaRotationConjugated=this._deltaRotation.conjugate()},t.DEFAULT_OBJECT_SIZE=new e.Vector3(1,1,1),t.NoImpostor=0,t.SphereImpostor=1,t.BoxImpostor=2,t.PlaneImpostor=3,t.MeshImpostor=4,t.CylinderImpostor=7,t.ParticleImpostor=8,t.HeightmapImpostor=9,t})();e.PhysicsImpostor=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){if(void 0===i&&(i=new e.CannonJSPlugin),this._physicsPlugin=i,this._impostors=[],this._joints=[],!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new e.Vector3(0,(-9.807),0),this.setGravity(t),this.setTimeStep()}return t.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},t.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},t.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},t.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},t.prototype.addImpostor=function(e){e.uniqueId=this._impostors.push(e),e.parent||this._physicsPlugin.generatePhysicsBody(e)},t.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);if(t>-1){var i=this._impostors.splice(t,1);i.length&&(i[0].physicsBody=null)}},t.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},t.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},t.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},t.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},t.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t]},t.prototype.getImpostorWithPhysicsBody=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t]},t.NoImpostor=e.PhysicsImpostor.NoImpostor,t.SphereImpostor=e.PhysicsImpostor.SphereImpostor,t.BoxImpostor=e.PhysicsImpostor.BoxImpostor,t.PlaneImpostor=e.PhysicsImpostor.PlaneImpostor,t.MeshImpostor=e.PhysicsImpostor.MeshImpostor,t.CylinderImpostor=e.PhysicsImpostor.CylinderImpostor,t.HeightmapImpostor=e.PhysicsImpostor.HeightmapImpostor,t.CapsuleImpostor=-1,t.ConeImpostor=-1,t.ConvexHullImpostor=-1,t.Epsilon=.001,t})();e.PhysicsEngine=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.prototype.set=function(t,i){switch(i){case e.VertexBuffer.PositionKind:this.positions=t;break;case e.VertexBuffer.NormalKind:this.normals=t;break;case e.VertexBuffer.UVKind:this.uvs=t;break;case e.VertexBuffer.UV2Kind:this.uvs2=t;break;case e.VertexBuffer.UV3Kind:this.uvs3=t;break;case e.VertexBuffer.UV4Kind:this.uvs4=t;break;case e.VertexBuffer.UV5Kind:this.uvs5=t;break;case e.VertexBuffer.UV6Kind:this.uvs6=t;break;case e.VertexBuffer.ColorKind:this.colors=t;break;case e.VertexBuffer.MatricesIndicesKind:this.matricesIndices=t;break;case e.VertexBuffer.MatricesWeightsKind:this.matricesWeights=t;break;case e.VertexBuffer.MatricesIndicesExtraKind:this.matricesIndicesExtra=t;break;case e.VertexBuffer.MatricesWeightsExtraKind:this.matricesWeightsExtra=t}},t.prototype.applyToMesh=function(e,t){this._applyTo(e,t)},t.prototype.applyToGeometry=function(e,t){this._applyTo(e,t)},t.prototype.updateMesh=function(e,t,i){this._update(e)},t.prototype.updateGeometry=function(e,t,i){this._update(e)},t.prototype._applyTo=function(t,i){this.positions&&t.setVerticesData(e.VertexBuffer.PositionKind,this.positions,i),this.normals&&t.setVerticesData(e.VertexBuffer.NormalKind,this.normals,i),this.uvs&&t.setVerticesData(e.VertexBuffer.UVKind,this.uvs,i),this.uvs2&&t.setVerticesData(e.VertexBuffer.UV2Kind,this.uvs2,i),this.uvs3&&t.setVerticesData(e.VertexBuffer.UV3Kind,this.uvs3,i),this.uvs4&&t.setVerticesData(e.VertexBuffer.UV4Kind,this.uvs4,i),this.uvs5&&t.setVerticesData(e.VertexBuffer.UV5Kind,this.uvs5,i),this.uvs6&&t.setVerticesData(e.VertexBuffer.UV6Kind,this.uvs6,i),this.colors&&t.setVerticesData(e.VertexBuffer.ColorKind,this.colors,i),this.matricesIndices&&t.setVerticesData(e.VertexBuffer.MatricesIndicesKind,this.matricesIndices,i),this.matricesWeights&&t.setVerticesData(e.VertexBuffer.MatricesWeightsKind,this.matricesWeights,i),this.matricesIndicesExtra&&t.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,i),this.matricesWeightsExtra&&t.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,i),this.indices&&t.setIndices(this.indices)},t.prototype._update=function(t,i,r){this.positions&&t.updateVerticesData(e.VertexBuffer.PositionKind,this.positions,i,r),this.normals&&t.updateVerticesData(e.VertexBuffer.NormalKind,this.normals,i,r),this.uvs&&t.updateVerticesData(e.VertexBuffer.UVKind,this.uvs,i,r),this.uvs2&&t.updateVerticesData(e.VertexBuffer.UV2Kind,this.uvs2,i,r),this.uvs3&&t.updateVerticesData(e.VertexBuffer.UV3Kind,this.uvs3,i,r),this.uvs4&&t.updateVerticesData(e.VertexBuffer.UV4Kind,this.uvs4,i,r),this.uvs5&&t.updateVerticesData(e.VertexBuffer.UV5Kind,this.uvs5,i,r),this.uvs6&&t.updateVerticesData(e.VertexBuffer.UV6Kind,this.uvs6,i,r),this.colors&&t.updateVerticesData(e.VertexBuffer.ColorKind,this.colors,i,r),this.matricesIndices&&t.updateVerticesData(e.VertexBuffer.MatricesIndicesKind,this.matricesIndices,i,r),this.matricesWeights&&t.updateVerticesData(e.VertexBuffer.MatricesWeightsKind,this.matricesWeights,i,r),this.matricesIndicesExtra&&t.updateVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,i,r),this.matricesWeightsExtra&&t.updateVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,i,r),this.indices&&t.setIndices(this.indices)},t.prototype.transform=function(t){var i,r=e.Vector3.Zero();if(this.positions){var n=e.Vector3.Zero();for(i=0;i<this.positions.length;i+=3)e.Vector3.FromArrayToRef(this.positions,i,n),e.Vector3.TransformCoordinatesToRef(n,t,r),this.positions[i]=r.x,this.positions[i+1]=r.y,this.positions[i+2]=r.z}if(this.normals){var o=e.Vector3.Zero();for(i=0;i<this.normals.length;i+=3)e.Vector3.FromArrayToRef(this.normals,i,o),e.Vector3.TransformNormalToRef(o,t,r),this.normals[i]=r.x,this.normals[i+1]=r.y,this.normals[i+2]=r.z}},t.prototype.merge=function(e){if(e.indices){this.indices||(this.indices=[]);for(var t=this.positions?this.positions.length/3:0,i=0;i<e.indices.length;i++)this.indices.push(e.indices[i]+t)}this.positions=this._mergeElement(this.positions,e.positions),this.normals=this._mergeElement(this.normals,e.normals),this.uvs=this._mergeElement(this.uvs,e.uvs),this.uvs2=this._mergeElement(this.uvs2,e.uvs2),this.uvs3=this._mergeElement(this.uvs3,e.uvs3),this.uvs4=this._mergeElement(this.uvs4,e.uvs4),this.uvs5=this._mergeElement(this.uvs5,e.uvs5),this.uvs6=this._mergeElement(this.uvs6,e.uvs6),this.colors=this._mergeElement(this.colors,e.colors),this.matricesIndices=this._mergeElement(this.matricesIndices,e.matricesIndices),this.matricesWeights=this._mergeElement(this.matricesWeights,e.matricesWeights),this.matricesIndicesExtra=this._mergeElement(this.matricesIndicesExtra,e.matricesIndicesExtra),this.matricesWeightsExtra=this._mergeElement(this.matricesWeightsExtra,e.matricesWeightsExtra)},t.prototype._mergeElement=function(e,t){if(!t)return e;if(!e)return t;var i=t.length+e.length,r=e instanceof Float32Array,n=t instanceof Float32Array;if(r){var o=new Float32Array(i);return o.set(e),o.set(t,e.length),o}if(n){for(var s=e.slice(0),a=0,i=t.length;a<i;a++)s.push(t[a]);return s}return e.concat(t)},t.prototype.serialize=function(){var e=this.serialize();return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e},t.ExtractFromMesh=function(e,i){return t._ExtractFrom(e,i)},t.ExtractFromGeometry=function(e,i){return t._ExtractFrom(e,i)},t._ExtractFrom=function(i,r){var n=new t;return i.isVerticesDataPresent(e.VertexBuffer.PositionKind)&&(n.positions=i.getVerticesData(e.VertexBuffer.PositionKind,r)),i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(n.normals=i.getVerticesData(e.VertexBuffer.NormalKind,r)),i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.uvs=i.getVerticesData(e.VertexBuffer.UVKind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(n.uvs2=i.getVerticesData(e.VertexBuffer.UV2Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV3Kind)&&(n.uvs3=i.getVerticesData(e.VertexBuffer.UV3Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV4Kind)&&(n.uvs4=i.getVerticesData(e.VertexBuffer.UV4Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV5Kind)&&(n.uvs5=i.getVerticesData(e.VertexBuffer.UV5Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.UV6Kind)&&(n.uvs6=i.getVerticesData(e.VertexBuffer.UV6Kind,r)),i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(n.colors=i.getVerticesData(e.VertexBuffer.ColorKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&(n.matricesIndices=i.getVerticesData(e.VertexBuffer.MatricesIndicesKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)&&(n.matricesWeights=i.getVerticesData(e.VertexBuffer.MatricesWeightsKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=i.getVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,r)),i.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=i.getVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,r)),n.indices=i.getIndices(r),n},t.CreateRibbon=function(i){var r=i.pathArray,n=i.closeArray||!1,o=i.closePath||!1,s=i.invertUV||!1,a=Math.floor(r[0].length/2),h=i.offset||a;h=h>a?a:Math.floor(h);var c,l,u,d,f=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,p=[],_=[],m=[],g=[],v=[],y=[],x=[],b=[],A=[],T=[];if(r.length<2){var E=[],P=[];for(u=0;u<r[0].length-h;u++)E.push(r[0][u]),P.push(r[0][u+h]);r=[E,P]}var S,M,C=0,R=o?1:0;c=r[0].length;var O,D;for(l=0;l<r.length;l++){for(x[l]=0,v[l]=[0],S=r[l],M=S.length,c=c<M?c:M,d=0;d<M;)p.push(S[d].x,S[d].y,S[d].z),d>0&&(O=S[d].subtract(S[d-1]).length(),D=O+x[l],v[l].push(D),x[l]=D),d++;o&&(d--,p.push(S[0].x,S[0].y,S[0].z),O=S[d].subtract(S[0]).length(),D=O+x[l],v[l].push(D),x[l]=D),A[l]=M+R,T[l]=C,C+=M+R}var I,L,w,B;for(u=0;u<c+R;u++){for(b[u]=0,y[u]=[0],l=0;l<r.length-1;l++)I=r[l],L=r[l+1],u===c?(w=I[0],B=L[0]):(w=I[u],B=L[u]),O=B.subtract(w).length(),D=O+b[u],y[u].push(D),b[u]=D;n&&(I=r[l],L=r[0],u===c&&(B=L[0]),O=B.subtract(w).length(),D=O+b[u],b[u]=D)}var F,V;for(l=0;l<r.length;l++)for(u=0;u<c+R;u++)F=v[l][u]/x[l],V=y[u][l]/b[u],s?g.push(V,F):g.push(F,V);l=0;for(var N=0,U=A[l]-1,z=A[l+1]-1,k=U<z?U:z,G=T[1]-T[0],W=n?A.length:A.length-1;N<=k&&l<W;)_.push(N,N+G,N+1),_.push(N+G+1,N+1,N+G),N+=1,N===k&&(l++,l===A.length-1?(G=T[0]-T[l],U=A[l]-1,z=A[0]-1):(G=T[l+1]-T[l],U=A[l]-1,z=A[l+1]-1),N=T[l],k=U<z?U+N:z+N);if(t.ComputeNormals(p,_,m),o){var Y=0,H=0;for(l=0;l<r.length;l++)Y=3*T[l],H=l+1<r.length?3*(T[l+1]-1):m.length-3,m[Y]=.5*(m[Y]+m[H]),m[Y+1]=.5*(m[Y+1]+m[H+1]),m[Y+2]=.5*(m[Y+2]+m[H+2]),m[H]=m[Y],m[H+1]=m[Y+1],m[H+2]=m[Y+2]}t._ComputeSides(f,p,_,m,g);var X=new t;return X.indices=_,X.positions=p,X.normals=m,X.uvs=g,o&&(X._idx=T),X},t.CreateBox=function(i){for(var r=[new e.Vector3(0,0,1),new e.Vector3(0,0,(-1)),new e.Vector3(1,0,0),new e.Vector3((-1),0,0),new e.Vector3(0,1,0),new e.Vector3(0,(-1),0)],n=[],o=[],s=[],a=[],h=i.width||i.size||1,c=i.height||i.size||1,l=i.depth||i.size||1,u=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,d=i.faceUV||new Array(6),f=i.faceColors,p=[],_=0;_<6;_++)void 0===d[_]&&(d[_]=new e.Vector4(0,0,1,1)),f&&void 0===f[_]&&(f[_]=new e.Color4(1,1,1,1));for(var m=new e.Vector3(h/2,c/2,l/2),g=0;g<r.length;g++){var v=r[g],y=new e.Vector3(v.y,v.z,v.x),x=e.Vector3.Cross(v,y),b=o.length/3;n.push(b),n.push(b+1),n.push(b+2),n.push(b),n.push(b+2),n.push(b+3);var A=v.subtract(y).subtract(x).multiply(m);o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(d[g].z,d[g].w),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a),A=v.subtract(y).add(x).multiply(m),o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(d[g].x,d[g].w),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a),A=v.add(y).add(x).multiply(m),o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(d[g].x,d[g].y),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a),A=v.add(y).subtract(x).multiply(m),o.push(A.x,A.y,A.z),s.push(v.x,v.y,v.z),a.push(d[g].z,d[g].y),f&&p.push(f[g].r,f[g].g,f[g].b,f[g].a)}t._ComputeSides(u,o,n,s,a);var T=new t;if(T.indices=n,T.positions=o,T.normals=s,T.uvs=a,f){var E=u===e.Mesh.DOUBLESIDE?p.concat(p):p;T.colors=E}return T},t.CreateSphere=function(i){for(var r=i.segments||32,n=i.diameterX||i.diameter||1,o=i.diameterY||i.diameter||1,s=i.diameterZ||i.diameter||1,a=i.arc<=0||i.arc>1?1:i.arc||1,h=i.slice<=0?1:i.slice||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,l=new e.Vector3(n/2,o/2,s/2),u=2+r,d=2*u,f=[],p=[],_=[],m=[],g=0;g<=u;g++){for(var v=g/u,y=v*Math.PI*h,x=0;x<=d;x++){var b=x/d,A=b*Math.PI*2*a,T=e.Matrix.RotationZ(-y),E=e.Matrix.RotationY(A),P=e.Vector3.TransformCoordinates(e.Vector3.Up(),T),S=e.Vector3.TransformCoordinates(P,E),M=S.multiply(l),C=S.divide(l).normalize();p.push(M.x,M.y,M.z),_.push(C.x,C.y,C.z),m.push(b,v)}if(g>0)for(var R=p.length/3,O=R-2*(d+1);O+d+2<R;O++)f.push(O),f.push(O+1),f.push(O+d+1),f.push(O+d+1),f.push(O+1),f.push(O+d+2)}t._ComputeSides(c,p,f,_,m);var D=new t;return D.indices=f,D.positions=p,D.normals=_,D.uvs=m,D},t.CreateCylinder=function(i){var r,n=i.height||2,o=0===i.diameterTop?0:i.diameterTop||i.diameter||1,s=0===i.diameterBottom?0:i.diameterBottom||i.diameter||1,a=i.tessellation||24,h=i.subdivisions||1,c=i.hasRings,l=i.enclose,u=i.arc<=0||i.arc>1?1:i.arc||1,d=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,f=i.faceUV||new Array(3),p=i.faceColors,_=1!==u&&l?2:0,m=c?h:1,g=2+(1+_)*m;for(r=0;r<g;r++)p&&void 0===p[r]&&(p[r]=new e.Color4(1,1,1,1));for(r=0;r<g;r++)f&&void 0===f[r]&&(f[r]=new e.Vector4(0,0,1,1));var v,y,x,b,A,T,E=[],P=[],S=[],M=[],C=[],R=2*Math.PI*u/a,O=(s-o)/2/n,D=e.Vector3.Zero(),I=e.Vector3.Zero(),L=e.Vector3.Zero(),w=e.Vector3.Zero(),B=e.Vector3.Zero(),F=e.Axis.Y,V=1,N=1,U=0,z=0;for(b=0;b<=h;b++)for(y=b/h,x=(y*(o-s)+s)/2,V=c&&0!==b&&b!==h?2:1,T=0;T<V;T++){for(c&&(N+=T),l&&(N+=2*T),A=0;A<=a;A++)v=A*R,D.x=Math.cos(-v)*x,D.y=-n/2+y*n,D.z=Math.sin(-v)*x,0===o&&b===h?(I.x=S[S.length-3*(a+1)],I.y=S[S.length-3*(a+1)+1],I.z=S[S.length-3*(a+1)+2]):(I.x=D.x,I.z=D.z,I.y=Math.sqrt(I.x*I.x+I.z*I.z)*O,I.normalize()),0===A&&(L.copyFrom(D),w.copyFrom(I)),P.push(D.x,D.y,D.z),S.push(I.x,I.y,I.z),z=c?U!==N?f[N].y:f[N].w:f[N].y+(f[N].w-f[N].y)*y,M.push(f[N].x+(f[N].z-f[N].x)*A/a,z),p&&C.push(p[N].r,p[N].g,p[N].b,p[N].a);1!==u&&l&&(P.push(D.x,D.y,D.z),P.push(0,D.y,0),P.push(0,D.y,0),P.push(L.x,L.y,L.z),e.Vector3.CrossToRef(F,I,B),B.normalize(),S.push(B.x,B.y,B.z,B.x,B.y,B.z),e.Vector3.CrossToRef(w,F,B),B.normalize(),S.push(B.x,B.y,B.z,B.x,B.y,B.z),z=c?U!==N?f[N+1].y:f[N+1].w:f[N+1].y+(f[N+1].w-f[N+1].y)*y,M.push(f[N+1].x,z),M.push(f[N+1].z,z),z=c?U!==N?f[N+2].y:f[N+2].w:f[N+2].y+(f[N+2].w-f[N+2].y)*y,M.push(f[N+2].x,z),M.push(f[N+2].z,z),p&&(C.push(p[N+1].r,p[N+1].g,p[N+1].b,p[N+1].a),C.push(p[N+1].r,p[N+1].g,p[N+1].b,p[N+1].a),C.push(p[N+2].r,p[N+2].g,p[N+2].b,p[N+2].a),C.push(p[N+2].r,p[N+2].g,p[N+2].b,p[N+2].a))),U!==N&&(U=N)}var N,k=1!==u&&l?a+4:a;for(b=0,N=0;N<h;N++){for(A=0;A<a;A++){var G=b*(k+1)+A,W=(b+1)*(k+1)+A,Y=b*(k+1)+(A+1),H=(b+1)*(k+1)+(A+1);E.push(G,W,Y),E.push(H,Y,W)}1!==u&&l&&(E.push(G+2,W+2,Y+2),E.push(H+2,Y+2,W+2),E.push(G+4,W+4,Y+4),E.push(H+4,Y+4,W+4)),b=c?b+2:b+1}var X=function(t){var i=t?o/2:s/2;if(0!==i){var r,h,c,l,d=t?f[g-1]:f[0];p&&(l=t?p[g-1]:p[0]);var _=P.length/3,m=t?n/2:-n/2,v=new e.Vector3(0,m,0);P.push(v.x,v.y,v.z),S.push(0,t?1:-1,0),M.push(d.x+.5*(d.z-d.x),d.y+.5*(d.w-d.y)),p&&C.push(l.r,l.g,l.b,l.a);var y=new e.Vector2(.5,.5);for(c=0;c<=a;c++){r=2*Math.PI*c*u/a;var x=Math.cos(-r),b=Math.sin(-r);h=new e.Vector3(x*i,m,b*i);var A=new e.Vector2(x*y.x+.5,b*y.y+.5);P.push(h.x,h.y,h.z),S.push(0,t?1:-1,0),M.push(d.x+(d.z-d.x)*A.x,d.y+(d.w-d.y)*A.y),p&&C.push(l.r,l.g,l.b,l.a)}for(c=0;c<a;c++)t?(E.push(_),E.push(_+(c+2)),E.push(_+(c+1))):(E.push(_),E.push(_+(c+1)),E.push(_+(c+2)))}};X(!1),X(!0),t._ComputeSides(d,P,E,S,M);var j=new t;return j.indices=E,j.positions=P,j.normals=S,j.uvs=M,p&&(j.colors=C),j},t.CreateTorus=function(i){for(var r=[],n=[],o=[],s=[],a=i.diameter||1,h=i.thickness||.5,c=i.tessellation||16,l=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,u=c+1,d=0;d<=c;d++)for(var f=d/c,p=d*Math.PI*2/c-Math.PI/2,_=e.Matrix.Translation(a/2,0,0).multiply(e.Matrix.RotationY(p)),m=0;m<=c;m++){var g=1-m/c,v=m*Math.PI*2/c+Math.PI,y=Math.cos(v),x=Math.sin(v),b=new e.Vector3(y,x,0),A=b.scale(h/2),T=new e.Vector2(f,g);A=e.Vector3.TransformCoordinates(A,_),b=e.Vector3.TransformNormal(b,_),n.push(A.x,A.y,A.z),o.push(b.x,b.y,b.z),s.push(T.x,T.y);var E=(d+1)%u,P=(m+1)%u;r.push(d*u+m),r.push(d*u+P),r.push(E*u+m),r.push(d*u+P),r.push(E*u+P),r.push(E*u+m)}t._ComputeSides(l,n,r,o,s);var S=new t;return S.indices=r,S.positions=n,S.normals=o,S.uvs=s,S},t.CreateLineSystem=function(e){for(var i=[],r=[],n=e.lines,o=0,s=0;s<n.length;s++)for(var a=n[s],h=0;h<a.length;h++)r.push(a[h].x,a[h].y,a[h].z),h>0&&(i.push(o-1),i.push(o)),o++;var c=new t;return c.indices=i,c.positions=r,c},t.CreateDashedLines=function(i){var r=i.dashSize||3,n=i.gapSize||1,o=i.dashNb||200,s=i.points,a=new Array,h=new Array,c=e.Vector3.Zero(),l=0,u=0,d=0,f=0,p=0,_=0,m=0;for(m=0;m<s.length-1;m++)s[m+1].subtractToRef(s[m],c),l+=c.length();for(d=l/o,f=r*d/(r+n),m=0;m<s.length-1;m++){s[m+1].subtractToRef(s[m],c),u=Math.floor(c.length()/d),c.normalize();for(var g=0;g<u;g++)p=d*g,a.push(s[m].x+p*c.x,s[m].y+p*c.y,s[m].z+p*c.z),a.push(s[m].x+(p+f)*c.x,s[m].y+(p+f)*c.y,s[m].z+(p+f)*c.z),h.push(_,_+1),_+=2}var v=new t;return v.positions=a,v.indices=h,v},t.CreateGround=function(i){var r,n,o=[],s=[],a=[],h=[],c=i.width||1,l=i.height||1,u=i.subdivisionsX||i.subdivisions||1,d=i.subdivisionsY||i.subdivisions||1;for(r=0;r<=d;r++)for(n=0;n<=u;n++){var f=new e.Vector3(n*c/u-c/2,0,(d-r)*l/d-l/2),p=new e.Vector3(0,1,0);s.push(f.x,f.y,f.z),a.push(p.x,p.y,p.z),h.push(n/u,1-r/u)}for(r=0;r<d;r++)for(n=0;n<u;n++)o.push(n+1+(r+1)*(u+1)),o.push(n+1+r*(u+1)),o.push(n+r*(u+1)),o.push(n+(r+1)*(u+1)),o.push(n+1+(r+1)*(u+1)),o.push(n+r*(u+1));var _=new t;return _.indices=o,_.positions=s,_.normals=a,_.uvs=h,_},t.CreateTiledGround=function(i){function r(t,i,r,s){var a=_.length/3,h=f.w+1;for(n=0;n<f.h;n++)for(o=0;o<f.w;o++){var c=[a+o+n*h,a+(o+1)+n*h,a+(o+1)+(n+1)*h,a+o+(n+1)*h];p.push(c[1]),p.push(c[2]),p.push(c[3]),p.push(c[0]),p.push(c[1]),p.push(c[3])}var l=e.Vector3.Zero(),u=new e.Vector3(0,1,0);for(n=0;n<=f.h;n++)for(l.z=n*(s-i)/f.h+i,o=0;o<=f.w;o++)l.x=o*(r-t)/f.w+t,l.y=0,_.push(l.x,l.y,l.z),m.push(u.x,u.y,u.z),g.push(o/f.w,n/f.h)}var n,o,s,a,h=i.xmin||-1,c=i.zmin||-1,l=i.xmax||1,u=i.zmax||1,d=i.subdivisions||{w:1,h:1},f=i.precision||{w:1,h:1},p=[],_=[],m=[],g=[];d.h=d.h<1?1:d.h,d.w=d.w<1?1:d.w,f.w=f.w<1?1:f.w,f.h=f.h<1?1:f.h;var v={w:(l-h)/d.w,h:(u-c)/d.h};for(s=0;s<d.h;s++)for(a=0;a<d.w;a++)r(h+a*v.w,c+s*v.h,h+(a+1)*v.w,c+(s+1)*v.h);var y=new t;return y.indices=p,y.positions=_,y.normals=m,y.uvs=g,y},t.CreateGroundFromHeightMap=function(i){var r,n,o=[],s=[],a=[],h=[];for(r=0;r<=i.subdivisions;r++)for(n=0;n<=i.subdivisions;n++){var c=new e.Vector3(n*i.width/i.subdivisions-i.width/2,0,(i.subdivisions-r)*i.height/i.subdivisions-i.height/2),l=(c.x+i.width/2)/i.width*(i.bufferWidth-1)|0,u=(1-(c.z+i.height/2)/i.height)*(i.bufferHeight-1)|0,d=4*(l+u*i.bufferWidth),f=i.buffer[d]/255,p=i.buffer[d+1]/255,_=i.buffer[d+2]/255,m=.3*f+.59*p+.11*_;c.y=i.minHeight+(i.maxHeight-i.minHeight)*m,s.push(c.x,c.y,c.z),a.push(0,0,0),h.push(n/i.subdivisions,1-r/i.subdivisions)}for(r=0;r<i.subdivisions;r++)for(n=0;n<i.subdivisions;n++)o.push(n+1+(r+1)*(i.subdivisions+1)),o.push(n+1+r*(i.subdivisions+1)),o.push(n+r*(i.subdivisions+1)),o.push(n+(r+1)*(i.subdivisions+1)),o.push(n+1+(r+1)*(i.subdivisions+1)),o.push(n+r*(i.subdivisions+1));t.ComputeNormals(s,o,a);var g=new t;return g.indices=o,g.positions=s,g.normals=a,g.uvs=h,g},t.CreatePlane=function(i){var r=[],n=[],o=[],s=[],a=i.width||i.size||1,h=i.height||i.size||1,c=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,l=a/2,u=h/2;n.push(-l,-u,0),o.push(0,0,-1),s.push(0,0),n.push(l,-u,0),o.push(0,0,-1),s.push(1,0),n.push(l,u,0),o.push(0,0,-1),s.push(1,1),n.push(-l,u,0),o.push(0,0,-1),s.push(0,1),r.push(0),r.push(1),r.push(2),r.push(0),r.push(2),r.push(3),t._ComputeSides(c,n,r,o,s);var d=new t;return d.indices=r,d.positions=n,d.normals=o,d.uvs=s,d},t.CreateDisc=function(i){var r=[],n=[],o=[],s=[],a=i.radius||.5,h=i.tessellation||64,c=i.arc<=0||i.arc>1?1:i.arc||1,l=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE;r.push(0,0,0),s.push(.5,.5);for(var u=2*Math.PI*c,d=u/h,f=0;f<u;f+=d){var p=Math.cos(f),_=Math.sin(f),m=(p+1)/2,g=(1-_)/2;r.push(a*p,a*_,0),s.push(m,g)}1===c&&(r.push(r[3],r[4],r[5]),s.push(s[2],s[3]));for(var v=r.length/3,y=1;y<v-1;y++)n.push(y+1,0,y);t.ComputeNormals(r,n,o),t._ComputeSides(l,r,n,o,s);var x=new t;return x.indices=n,x.positions=r,x.normals=o,x.uvs=s,x},t.CreateIcoSphere=function(i){var r,n=i.sideOrientation||e.Mesh.DEFAULTSIDE,o=i.radius||1,s=void 0===i.flat||i.flat,a=i.subdivisions||4,h=i.radiusX||o,c=i.radiusY||o,l=i.radiusZ||o,u=(1+Math.sqrt(5))/2,d=[-1,u,-0,1,u,0,-1,-u,0,1,-u,0,0,-1,-u,0,1,-u,0,-1,u,0,1,u,u,0,1,u,0,-1,-u,0,1,-u,0,-1],f=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],p=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],_=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],m=138/1024,g=239/1024,v=60/1024,y=26/1024,x=-40/1024,b=20/1024,A=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],T=[],E=[],P=[],S=[],M=0,C=new Array(3),R=new Array(3);for(r=0;r<3;r++)C[r]=e.Vector3.Zero(),R[r]=e.Vector2.Zero();for(var O=0;O<20;O++){for(r=0;r<3;r++){var D=f[3*O+r];C[r].copyFromFloats(d[3*p[D]],d[3*p[D]+1],d[3*p[D]+2]),C[r].normalize().scaleInPlace(o),R[r].copyFromFloats(_[2*D]*m+v+A[O]*x,_[2*D+1]*g+y+A[O]*b)}for(var I=function(t,i,r,n){var o=e.Vector3.Lerp(C[0],C[2],i/a),u=e.Vector3.Lerp(C[1],C[2],i/a),d=a===i?C[2]:e.Vector3.Lerp(o,u,t/(a-i));d.normalize();var f;if(s){var p=e.Vector3.Lerp(C[0],C[2],n/a),_=e.Vector3.Lerp(C[1],C[2],n/a);f=e.Vector3.Lerp(p,_,r/(a-n))}else f=new e.Vector3(d.x,d.y,d.z);f.x/=h,f.y/=c,f.z/=l,f.normalize();var m=e.Vector2.Lerp(R[0],R[2],i/a),g=e.Vector2.Lerp(R[1],R[2],i/a),v=a===i?R[2]:e.Vector2.Lerp(m,g,t/(a-i));E.push(d.x*h,d.y*c,d.z*l),P.push(f.x,f.y,f.z),S.push(v.x,v.y),T.push(M),M++},L=0;L<a;L++)for(var w=0;w+L<a;w++)I(w,L,w+1/3,L+1/3),I(w+1,L,w+1/3,L+1/3),I(w,L+1,w+1/3,L+1/3),w+L+1<a&&(I(w+1,L,w+2/3,L+2/3),I(w+1,L+1,w+2/3,L+2/3),I(w,L+1,w+2/3,L+2/3))}t._ComputeSides(n,E,T,P,S);var B=new t;return B.indices=T,B.positions=E,B.normals=P,B.uvs=S,B},t.CreatePolyhedron=function(i){var r=[];r[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},r[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},r[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},r[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},r[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},r[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},r[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],
face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},r[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},r[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},r[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},r[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},r[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},r[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},r[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},r[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};var n,o,s,a,h,c,l=i.type<0||i.type>=r.length?0:i.type||0,u=i.size,d=i.sizeX||u||1,f=i.sizeY||u||1,p=i.sizeZ||u||1,_=i.custom||r[l],m=_.face.length,g=i.faceUV||new Array(m),v=i.faceColors,y=void 0===i.flat||i.flat,x=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,b=[],A=[],T=[],E=[],P=[],S=0,M=0,C=[],R=0,O=0;if(y)for(O=0;O<m;O++)v&&void 0===v[O]&&(v[O]=new e.Color4(1,1,1,1)),g&&void 0===g[O]&&(g[O]=new e.Vector4(0,0,1,1));if(y)for(O=0;O<m;O++){var D=_.face[O].length;for(s=2*Math.PI/D,a=.5*Math.tan(s/2),h=.5,R=0;R<D;R++)b.push(_.vertex[_.face[O][R]][0]*d,_.vertex[_.face[O][R]][1]*f,_.vertex[_.face[O][R]][2]*p),C.push(S),S++,n=g[O].x+(g[O].z-g[O].x)*(.5+a),o=g[O].y+(g[O].w-g[O].y)*(h-.5),E.push(n,o),c=a*Math.cos(s)-h*Math.sin(s),h=a*Math.sin(s)+h*Math.cos(s),a=c,v&&P.push(v[O].r,v[O].g,v[O].b,v[O].a);for(R=0;R<D-2;R++)A.push(C[0+M],C[R+2+M],C[R+1+M]);M+=D}else{for(R=0;R<_.vertex.length;R++)b.push(_.vertex[R][0]*d,_.vertex[R][1]*f,_.vertex[R][2]*p),E.push(0,0);for(O=0;O<m;O++)for(R=0;R<_.face[O].length-2;R++)A.push(_.face[O][0],_.face[O][R+2],_.face[O][R+1])}t.ComputeNormals(b,A,T),t._ComputeSides(x,b,A,T,E);var I=new t;return I.positions=b,I.indices=A,I.normals=T,I.uvs=E,v&&y&&(I.colors=P),I},t.CreateTorusKnot=function(i){var r,n,o=[],s=[],a=[],h=[],c=i.radius||2,l=i.tube||.5,u=i.radialSegments||32,d=i.tubularSegments||32,f=i.p||2,p=i.q||3,_=0===i.sideOrientation?0:i.sideOrientation||e.Mesh.DEFAULTSIDE,m=function(t){var i=Math.cos(t),r=Math.sin(t),n=p/f*t,o=Math.cos(n),s=c*(2+o)*.5*i,a=c*(2+o)*r*.5,h=c*Math.sin(n)*.5;return new e.Vector3(s,a,h)};for(r=0;r<=u;r++){var g=r%u,v=g/u*2*f*Math.PI,y=m(v),x=m(v+.01),b=x.subtract(y),A=x.add(y),T=e.Vector3.Cross(b,A);for(A=e.Vector3.Cross(T,b),T.normalize(),A.normalize(),n=0;n<d;n++){var E=n%d,P=E/d*2*Math.PI,S=-l*Math.cos(P),M=l*Math.sin(P);s.push(y.x+S*A.x+M*T.x),s.push(y.y+S*A.y+M*T.y),s.push(y.z+S*A.z+M*T.z),h.push(r/u),h.push(n/d)}}for(r=0;r<u;r++)for(n=0;n<d;n++){var C=(n+1)%d,R=r*d+n,O=(r+1)*d+n,D=(r+1)*d+C,I=r*d+C;o.push(I),o.push(O),o.push(R),o.push(I),o.push(D),o.push(O)}t.ComputeNormals(s,o,a),t._ComputeSides(_,s,o,a,h);var L=new t;return L.indices=o,L.positions=s,L.normals=a,L.uvs=h,L},t.ComputeNormals=function(e,t,i){var r=0,n=0,o=0,s=0,a=0,h=0,c=0,l=0,u=0,d=0,f=0,p=0,_=0,m=0;for(r=0;r<e.length;r++)i[r]=0;var g=t.length/3;for(r=0;r<g;r++)p=t[3*r],_=t[3*r+1],m=t[3*r+2],n=e[3*p]-e[3*_],o=e[3*p+1]-e[3*_+1],s=e[3*p+2]-e[3*_+2],a=e[3*m]-e[3*_],h=e[3*m+1]-e[3*_+1],c=e[3*m+2]-e[3*_+2],l=o*c-s*h,u=s*a-n*c,d=n*h-o*a,f=Math.sqrt(l*l+u*u+d*d),f=0===f?1:f,l/=f,u/=f,d/=f,i[3*p]+=l,i[3*p+1]+=u,i[3*p+2]+=d,i[3*_]+=l,i[3*_+1]+=u,i[3*_+2]+=d,i[3*m]+=l,i[3*m+1]+=u,i[3*m+2]+=d;for(r=0;r<i.length/3;r++)l=i[3*r],u=i[3*r+1],d=i[3*r+2],f=Math.sqrt(l*l+u*u+d*d),f=0===f?1:f,l/=f,u/=f,d/=f,i[3*r]=l,i[3*r+1]=u,i[3*r+2]=d},t._ComputeSides=function(t,i,r,n,o){var s,a,h=r.length,c=n.length;switch(t=t||e.Mesh.DEFAULTSIDE){case e.Mesh.FRONTSIDE:break;case e.Mesh.BACKSIDE:var l;for(s=0;s<h;s+=3)l=r[s],r[s]=r[s+2],r[s+2]=l;for(a=0;a<c;a++)n[a]=-n[a];break;case e.Mesh.DOUBLESIDE:for(var u=i.length,d=u/3,f=0;f<u;f++)i[u+f]=i[f];for(s=0;s<h;s+=3)r[s+h]=r[s+2]+d,r[s+1+h]=r[s+1]+d,r[s+2+h]=r[s]+d;for(a=0;a<c;a++)n[c+a]=-n[a];for(var p=o.length,_=0;_<p;_++)o[_+p]=o[_]}},t.ImportVertexData=function(i,r){var n=new t,o=i.positions;o&&n.set(o,e.VertexBuffer.PositionKind);var s=i.normals;s&&n.set(s,e.VertexBuffer.NormalKind);var a=i.uvs;a&&n.set(a,e.VertexBuffer.UVKind);var h=i.uv2s;h&&n.set(h,e.VertexBuffer.UV2Kind);var c=i.uv3s;c&&n.set(c,e.VertexBuffer.UV3Kind);var l=i.uv4s;l&&n.set(l,e.VertexBuffer.UV4Kind);var u=i.uv5s;u&&n.set(u,e.VertexBuffer.UV5Kind);var d=i.uv6s;d&&n.set(d,e.VertexBuffer.UV6Kind);var f=i.colors;f&&n.set(e.Color4.CheckColors4(f,o.length/3),e.VertexBuffer.ColorKind);var p=i.matricesIndices;p&&n.set(p,e.VertexBuffer.MatricesIndicesKind);var _=i.matricesWeights;_&&n.set(_,e.VertexBuffer.MatricesWeightsKind);var m=i.indices;m&&(n.indices=m),r.setAllVerticesData(n,i.updatable)},t})();e.VertexData=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.EnableFor=function(e){e._tags=e._tags||{},e.hasTags=function(){return t.HasTags(e)},e.addTags=function(i){return t.AddTagsTo(e,i)},e.removeTags=function(i){return t.RemoveTagsFrom(e,i)},e.matchesTagsQuery=function(i){return t.MatchesQuery(e,i)}},t.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},t.HasTags=function(t){return!!t._tags&&!e.Tools.IsEmpty(t._tags)},t.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)e._tags.hasOwnProperty(r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}return e._tags},t.AddTagsTo=function(e,i){if(i&&"string"==typeof i){var r=i.split(" ");r.forEach((function(i,r,n){t._AddTagTo(e,i)}))}},t._AddTagTo=function(e,i){i=i.trim(),""!==i&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(t.EnableFor(e),e._tags[i]=!0))},t.RemoveTagsFrom=function(e,i){if(t.HasTags(e)){var r=i.split(" ");for(var n in r)t._RemoveTagFrom(e,r[n])}},t._RemoveTagFrom=function(e,t){delete e._tags[t]},t.MatchesQuery=function(i,r){return void 0===r||(""===r?t.HasTags(i):e.Internals.AndOrNotEvaluator.Eval(r,(function(e){return t.HasTags(i)&&i._tags[e]})))},t})();e.Tags=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(){}return e.Eval=function(t,i){return t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i),"true"===t||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){i=i||function(e){return"true"===e};var r,n=t.split("||");for(var o in n)if(n.hasOwnProperty(o)){var s=e._SimplifyNegation(n[o].trim()),a=s.split("&&");if(a.length>1)for(var h=0;h<a.length;++h){var c=e._SimplifyNegation(a[h].trim());if(r="true"!==c&&"false"!==c?"!"===c[0]?!i(c.substring(1)):i(c):"true"===c,!r){s="false";break}}if(r||"true"===s){r=!0;break}r="true"!==s&&"false"!==s?"!"===s[0]?!i(s.substring(1)):i(s):"true"===s}return r?"true":"false"},e._SimplifyNegation=function(e){return e=e.replace(/^[\s!]+/,(function(e){return e=e.replace(/[\s]/g,(function(){return""})),e.length%2?"!":""})),e=e.trim(),"!true"===e?e="false":"!false"===e&&(e="true"),e},e})();e.AndOrNotEvaluator=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s){this._enabled=!0,this._refCount=0,this._name=i,this._renderTexture=new e.RenderTargetTexture(i,r,t),this.setRenderList(n),this._renderTexture.onBeforeRenderObservable.add(o),this._renderTexture.onAfterRenderObservable.add(s),this._scene=t,this._renderList=n}return t.prototype._incRefCount=function(){return 0===this._refCount&&this._scene.customRenderTargets.push(this._renderTexture),++this._refCount},t.prototype._decRefCount=function(){return this._refCount--,this._refCount<=0&&this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture),1),this._refCount},t.prototype._update=function(){this.setRenderList(this._renderList)},t.prototype.setRenderList=function(e){this._renderTexture.renderList=e},t.prototype.getRenderTexture=function(){return this._renderTexture},t})();e.PostProcessRenderPass=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this._engine=e,this._name=t,this._singleInstance=r||!0,this._getPostProcess=i,this._cameras=[],this._indicesForCamera=[],this._postProcesses={},this._renderPasses={},this._renderEffectAsPasses={}}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(!this._postProcesses[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype._update=function(){for(var e in this._renderPasses)this._renderPasses[e]._update()},t.prototype.addPass=function(e){this._renderPasses[e._name]=e,this._linkParameters()},t.prototype.removePass=function(e){delete this._renderPasses[e._name],this._linkParameters()},t.prototype.addRenderEffectAsPass=function(e){this._renderEffectAsPasses[e._name]=e,this._linkParameters()},t.prototype.getPass=function(e){for(var t in this._renderPasses)if(t===e)return this._renderPasses[e]},t.prototype.emptyPasses=function(){this._renderPasses={},this._linkParameters()},t.prototype._attachCameras=function(t){for(var i,r=e.Tools.MakeArray(t||this._cameras),n=0;n<r.length;n++){var o=r[n],s=o.name;i=this._singleInstance?0:s,this._postProcesses[i]=this._postProcesses[i]||this._getPostProcess();var a=o.attachPostProcess(this._postProcesses[i]);this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._indicesForCamera[s].push(a),this._cameras.indexOf(o)===-1&&(this._cameras[s]=o);for(var h in this._renderPasses)this._renderPasses[h]._incRefCount()}this._linkParameters()},t.prototype._detachCameras=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){var n=i[r],o=n.name;n.detachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o]);var s=this._cameras.indexOf(o);this._indicesForCamera.splice(s,1),this._cameras.splice(s,1);for(var a in this._renderPasses)this._renderPasses[a]._decRefCount()}},t.prototype._enable=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){for(var n=i[r],o=n.name,s=0;s<this._indicesForCamera[o].length;s++)void 0===n._postProcesses[this._indicesForCamera[o][s]]&&t[r].attachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o][s]);for(var a in this._renderPasses)this._renderPasses[a]._incRefCount()}},t.prototype._disable=function(t){for(var i=e.Tools.MakeArray(t||this._cameras),r=0;r<i.length;r++){var n=i[r],o=n.Name;n.detachPostProcess(this._postProcesses[this._singleInstance?0:o],this._indicesForCamera[o]);for(var s in this._renderPasses)this._renderPasses[s]._decRefCount()}},t.prototype.getPostProcess=function(e){return this._singleInstance?this._postProcesses[0]:this._postProcesses[e.name]},t.prototype._linkParameters=function(){var e=this;for(var t in this._postProcesses)this.applyParameters&&this.applyParameters(this._postProcesses[t]),this._postProcesses[t].onBeforeRenderObservable.add((function(t){e._linkTextures(t)}))},t.prototype._linkTextures=function(e){for(var t in this._renderPasses)e.setTexture(t,this._renderPasses[t].getRenderTexture());for(var i in this._renderEffectAsPasses)e.setTextureFromPostProcess(i+"Sampler",this._renderEffectAsPasses[i].getPostProcess())},t})();e.PostProcessRenderEffect=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass={},this._cameras=[]}return Object.defineProperty(t.prototype,"isSupported",{get:function(){for(var e in this._renderEffects)if(!this._renderEffects[e].isSupported)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype.addEffect=function(e){this._renderEffects[e._name]=e},t.prototype._enableEffect=function(t,i){var r=this._renderEffects[t];r&&r._enable(e.Tools.MakeArray(i||this._cameras))},t.prototype._disableEffect=function(t,i){var r=this._renderEffects[t];r&&r._disable(e.Tools.MakeArray(i||this._cameras))},t.prototype._attachCameras=function(t,i){var r,n=e.Tools.MakeArray(t||this._cameras),o=[];for(r=0;r<n.length;r++){var s=n[r],a=s.name;this._cameras.indexOf(s)===-1?this._cameras[a]=s:i&&o.push(r)}for(r=0;r<o.length;r++)t.splice(o[r],1);for(var h in this._renderEffects)this._renderEffects[h]._attachCameras(n)},t.prototype._detachCameras=function(t){var i=e.Tools.MakeArray(t||this._cameras);for(var r in this._renderEffects)this._renderEffects[r]._detachCameras(i);for(var n=0;n<i.length;n++)this._cameras.splice(this._cameras.indexOf(i[n]),1)},t.prototype._enableDisplayOnlyPass=function(i,r){var n,o=this,s=e.Tools.MakeArray(r||this._cameras),a=null;for(n in this._renderEffects)if(a=this._renderEffects[n].getPass(i),null!=a)break;if(null!==a){for(n in this._renderEffects)this._renderEffects[n]._disable(s);a._name=t.PASS_SAMPLER_NAME;for(var h=0;h<s.length;h++){var c=s[h],l=c.name;this._renderEffectsForIsolatedPass[l]=this._renderEffectsForIsolatedPass[l]||new e.PostProcessRenderEffect(this._engine,t.PASS_EFFECT_NAME,function(){return new e.DisplayPassPostProcess(t.PASS_EFFECT_NAME,1,null,null,o._engine,(!0))}),this._renderEffectsForIsolatedPass[l].emptyPasses(),this._renderEffectsForIsolatedPass[l].addPass(a),this._renderEffectsForIsolatedPass[l]._attachCameras(c)}}},t.prototype._disableDisplayOnlyPass=function(i){for(var r=this,n=e.Tools.MakeArray(i||this._cameras),o=0;o<n.length;o++){var s=n[o],a=s.name;this._renderEffectsForIsolatedPass[a]=this._renderEffectsForIsolatedPass[a]||new e.PostProcessRenderEffect(this._engine,t.PASS_EFFECT_NAME,function(){return new e.DisplayPassPostProcess(t.PASS_EFFECT_NAME,1,null,null,r._engine,(!0))}),this._renderEffectsForIsolatedPass[a]._disable(s)}for(var h in this._renderEffects)this._renderEffects[h]._enable(n)},t.prototype._update=function(){for(var e in this._renderEffects)this._renderEffects[e]._update();for(var t=0;t<this._cameras.length;t++){var i=this._cameras[t].name;this._renderEffectsForIsolatedPass[i]&&this._renderEffectsForIsolatedPass[i]._update()}},t.prototype.dispose=function(){},t.PASS_EFFECT_NAME="passEffect",t.PASS_SAMPLER_NAME="passSampler",t})();e.PostProcessRenderPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this._renderPipelines={}}return e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.enableDisplayOnlyPassInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableDisplayOnlyPass(t,i)},e.prototype.disableDisplayOnlyPassInPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._disableDisplayOnlyPass(t)},e.prototype.update=function(){for(var e in this._renderPipelines){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e})();e.PostProcessRenderPipelineManager=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.frontColor=new e.Color3(1,1,1),this.backColor=new e.Color3(.1,.1,.1),this.showBackLines=!0,this.renderList=new e.SmartArray(32),this._vertexBuffers={},this._scene=t}return t.prototype._prepareRessources=function(){if(!this._colorShader){this._colorShader=new e.ShaderMaterial("colorShader",this._scene,"color",{attributes:[e.VertexBuffer.PositionKind],uniforms:["worldViewProjection","color"]});var t=this._scene.getEngine(),i=e.VertexData.CreateBox(1);this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(t,i.positions,e.VertexBuffer.PositionKind,(!1)),this._indexBuffer=t.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}},t.prototype.reset=function(){this.renderList.reset()},t.prototype.render=function(){if(0!==this.renderList.length&&(this._prepareRessources(),this._colorShader.isReady())){var t=this._scene.getEngine();t.setDepthWrite(!1),this._colorShader._preBind();for(var i=0;i<this.renderList.length;i++){var r=this.renderList.data[i],n=r.minimum,o=r.maximum,s=o.subtract(n),a=n.add(s.scale(.5)),h=e.Matrix.Scaling(s.x,s.y,s.z).multiply(e.Matrix.Translation(a.x,a.y,a.z)).multiply(r.getWorldMatrix());t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),this.showBackLines&&(t.setDepthFunctionToGreaterOrEqual(),this._scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.backColor.toColor4()),this._colorShader.bind(h),t.draw(!1,0,24)),t.setDepthFunctionToLess(),this._scene.resetCachedMaterial(),this._colorShader.setColor4("color",this.frontColor.toColor4()),this._colorShader.bind(h),t.draw(!1,0,24)}this._colorShader.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0)}},t.prototype.dispose=function(){if(this._colorShader){this._colorShader.dispose();var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._scene.getEngine()._releaseBuffer(this._indexBuffer)}},t})();e.BoundingBoxRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e})();e.Condition=t;var i=(function(t){function i(e,r,n,o,s){void 0===s&&(s=i.IsEqual),t.call(this,e),this.propertyPath=n,this.value=o,this.operator=s,this._target=r,this._effectiveTarget=this._getEffectiveTarget(r,this.propertyPath),this._property=this._getProperty(this.propertyPath)}return __extends(i,t),Object.defineProperty(i,"IsEqual",{get:function(){return i._IsEqual},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsDifferent",{get:function(){return i._IsDifferent},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsGreater",{get:function(){return i._IsGreater},enumerable:!0,configurable:!0}),Object.defineProperty(i,"IsLesser",{get:function(){return i._IsLesser},enumerable:!0,configurable:!0}),i.prototype.isValid=function(){switch(this.operator){case i.IsGreater:return this._effectiveTarget[this._property]>this.value;case i.IsLesser:return this._effectiveTarget[this._property]<this.value;case i.IsEqual:case i.IsDifferent:var e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===i.IsEqual?e:!e}return!1},i.prototype.serialize=function(){return this._serialize({name:"ValueCondition",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)},{name:"operator",value:i.GetOperatorName(this.operator)}]})},i.GetOperatorName=function(e){switch(e){case i._IsEqual:return"IsEqual";case i._IsDifferent:return"IsDifferent";case i._IsGreater:return"IsGreater";case i._IsLesser:return"IsLesser";default:return""}},i._IsEqual=0,i._IsDifferent=1,i._IsGreater=2,i._IsLesser=3,i})(t);e.ValueCondition=i;var r=(function(e){function t(t,i){e.call(this,t),this.predicate=i}return __extends(t,e),t.prototype.isValid=function(){return this.predicate()},t})(t);e.PredicateCondition=r;var n=(function(t){function i(e,i,r){t.call(this,e),this.value=r,this._target=i}return __extends(i,t),i.prototype.isValid=function(){return this._target.state===this.value},i.prototype.serialize=function(){return this._serialize({name:"StateCondition",properties:[e.Action._GetTargetProperty(this._target),{name:"value",value:this.value}]})},i})(t);e.StateCondition=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this.triggerOptions=e,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):this.trigger=e,this._nextActiveAction=this,this._condition=t}return t.prototype._prepare=function(){},t.prototype.getTriggerParameter=function(){return this._triggerParameter},t.prototype._executeCurrent=function(e){if(this._nextActiveAction._condition){var t=this._nextActiveAction._condition,i=this._actionManager.getScene().getRenderId();if(t._evaluationId===i){if(!t._currentResult)return}else{if(t._evaluationId=i,!t.isValid())return void(t._currentResult=!1);t._currentResult=!0}}this._nextActiveAction.execute(e),this.skipToNextActiveAction()},t.prototype.execute=function(e){},t.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},t.prototype.then=function(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e},t.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},t.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},t.prototype.serialize=function(e){},t.prototype._serialize=function(e,t){var i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){var r=this._condition.serialize();return r.children.push(i),t&&t.children.push(r),r}return t&&t.children.push(i),i},t._SerializeValueAsString=function(t){return"number"==typeof t?t.toString():"boolean"==typeof t?t?"true":"false":t instanceof e.Vector2?t.x+", "+t.y:t instanceof e.Vector3?t.x+", "+t.y+", "+t.z:t instanceof e.Color3?t.r+", "+t.g+", "+t.b:t instanceof e.Color4?t.r+", "+t.g+", "+t.b+", "+t.a:t},t._GetTargetProperty=function(t){return{name:"target",targetType:t instanceof e.Mesh?"MeshProperties":t instanceof e.Light?"LightProperties":t instanceof e.Camera?"CameraProperties":"SceneProperties",value:t instanceof e.Scene?"Scene":t.name}},t})();e.Action=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i,r,n,o){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=n,this.additionalData=o}return e.CreateNew=function(t,i,r){var n=t.getScene();return new e(t,n.pointerX,n.pointerY,n.meshUnderPointer,i,r)},e.CreateNewFromSprite=function(t,i,r,n){return new e(t,i.pointerX,i.pointerY,i.meshUnderPointer,r,n)},e.CreateNewFromScene=function(t,i){return new e(null,t.pointerX,t.pointerY,t.meshUnderPointer,i)},e.CreateNewFromPrimitive=function(t,i,r,n){return new e(t,i.x,i.y,null,r,n)},e})();e.ActionEvent=t;var i=(function(){function t(e){this.actions=new Array,this.hoverCursor="",this._scene=e,e._actionManagers.push(this)}return Object.defineProperty(t,"NothingTrigger",{get:function(){return t._NothingTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickTrigger",{get:function(){return t._OnPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnLeftPickTrigger",{get:function(){return t._OnLeftPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnRightPickTrigger",{get:function(){return t._OnRightPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnCenterPickTrigger",{get:function(){return t._OnCenterPickTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickDownTrigger",{get:function(){return t._OnPickDownTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickUpTrigger",{get:function(){return t._OnPickUpTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPickOutTrigger",{get:function(){return t._OnPickOutTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnLongPressTrigger",{get:function(){return t._OnLongPressTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPointerOverTrigger",{get:function(){return t._OnPointerOverTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnPointerOutTrigger",{get:function(){return t._OnPointerOutTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnEveryFrameTrigger",{get:function(){return t._OnEveryFrameTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnIntersectionEnterTrigger",{get:function(){return t._OnIntersectionEnterTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnIntersectionExitTrigger",{get:function(){return t._OnIntersectionExitTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnKeyDownTrigger",{get:function(){return t._OnKeyDownTrigger},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OnKeyUpTrigger",{get:function(){return t._OnKeyUpTrigger},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var e=this._scene._actionManagers.indexOf(this);e>-1&&this._scene._actionManagers.splice(e,1)},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1},t.prototype.hasSpecificTrigger=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(i.trigger===e)return!0}return!1},Object.defineProperty(t.prototype,"hasPointerTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t._OnPickTrigger&&i.trigger<=t._OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t._OnPickTrigger&&i.trigger<=t._OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.registerAction=function(i){return i.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(e.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(i),i._actionManager=this,i._prepare(),i)},t.prototype.processTrigger=function(e,i){for(var r=0;r<this.actions.length;r++){var n=this.actions[r];if(n.trigger===e){if(e===t.OnKeyUpTrigger||e===t.OnKeyDownTrigger){var o=n.getTriggerParameter();if(o){var s=i.sourceEvent.charCode?i.sourceEvent.charCode:i.sourceEvent.keyCode,a=String.fromCharCode(s).toLowerCase();if(a!==o.toLowerCase())continue}}n._executeCurrent(i)}}},t.prototype._getEffectiveTarget=function(e,t){for(var i=t.split("."),r=0;r<i.length-1;r++)e=e[i[r]];return e},t.prototype._getProperty=function(e){var t=e.split(".");return t[t.length-1]},t.prototype.serialize=function(i){for(var r={children:[],name:i,type:3,properties:[]},n=0;n<this.actions.length;n++){var o={type:0,children:[],name:t.GetTriggerName(this.actions[n].trigger),properties:[]},s=this.actions[n].triggerOptions;if(s&&"number"!=typeof s)if(s.parameter instanceof e.Node)o.properties.push(e.Action._GetTargetProperty(s.parameter));else{var a={};e.Tools.DeepCopy(s.parameter,a,["mesh"]),s.parameter.mesh&&(a._meshId=s.parameter.mesh.id),o.properties.push({name:"parameter",targetType:null,value:a})}this.actions[n].serialize(o),r.children.push(o)}return r},t.Parse=function(i,r,n){var o=new e.ActionManager(n);null===r?n.actionManager=o:r.actionManager=o;for(var s=function(t,i){var r=Object.create(e[t].prototype);return r.constructor.apply(r,i),r},a=function(t,i,r,n){if(null===n){var o=parseFloat(i);return"true"===i||"false"===i?"true"===i:isNaN(o)?i:o}for(var s=n.split("."),a=i.split(","),h=0;h<s.length;h++)r=r[s[h]];if("boolean"==typeof r)return"true"===a[0];if("string"==typeof r)return a[0];for(var c=new Array,h=0;h<a.length;h++)c.push(parseFloat(a[h]));return r instanceof e.Vector3?e.Vector3.FromArray(c):r instanceof e.Vector4?e.Vector4.FromArray(c):r instanceof e.Color3?e.Color3.FromArray(c):r instanceof e.Color4?e.Color4.FromArray(c):parseFloat(a[0])},h=function(i,r,c,l,u){if(void 0===u&&(u=null),!i.detached){var d=new Array,f=null,p=null,_=i.combine&&i.combine.length>0;if(2===i.type?d.push(o):d.push(r),_){for(var m=new Array,g=0;g<i.combine.length;g++)h(i.combine[g],t.NothingTrigger,c,l,m);d.push(m)}else for(var v=0;v<i.properties.length;v++){var y=i.properties[v].value,x=i.properties[v].name,b=i.properties[v].targetType;"target"===x?y=f=null!==b&&"SceneProperties"===b?n:n.getNodeByName(y):"parent"===x?y=n.getNodeByName(y):"sound"===x?y=n.getSoundByName(y):"propertyPath"!==x?y=2===i.type&&"operator"===x?e.ValueCondition[y]:a(x,y,f,"value"===x?p:null):p=y,d.push(y)}if(null===u?d.push(c):d.push(null),"InterpolateValueAction"===i.name){var A=d[d.length-2];d[d.length-1]=A,d[d.length-2]=c}var T=s(i.name,d);if(T instanceof e.Condition&&null!==c){var E=new e.DoNothingAction(r,c);l?l.then(E):o.registerAction(E),l=E}null===u?T instanceof e.Condition?(c=T,T=l):(c=null,l?l.then(T):o.registerAction(T)):u.push(T);for(var v=0;v<i.children.length;v++)h(i.children[v],r,c,T,null)}},c=0;c<i.children.length;c++){var l,u=i.children[c];if(u.properties.length>0){var d=u.properties[0].value,f=null===u.properties[0].targetType?d:n.getMeshByName(d);f._meshId&&(f.mesh=n.getMeshByID(f._meshId)),l={trigger:e.ActionManager[u.name],parameter:f}}else l=e.ActionManager[u.name];for(var p=0;p<u.children.length;p++)u.detached||h(u.children[p],l,null,null);
}},t.GetTriggerName=function(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnPickUpTrigger";case 7:return"OnLongPressTrigger";case 8:return"OnPointerOverTrigger";case 9:return"OnPointerOutTrigger";case 10:return"OnEveryFrameTrigger";case 11:return"OnIntersectionEnterTrigger";case 12:return"OnIntersectionExitTrigger";case 13:return"OnKeyDownTrigger";case 14:return"OnKeyUpTrigger";case 15:return"OnPickOutTrigger";default:return""}},t._NothingTrigger=0,t._OnPickTrigger=1,t._OnLeftPickTrigger=2,t._OnRightPickTrigger=3,t._OnCenterPickTrigger=4,t._OnPickDownTrigger=5,t._OnPickUpTrigger=6,t._OnLongPressTrigger=7,t._OnPointerOverTrigger=8,t._OnPointerOutTrigger=9,t._OnEveryFrameTrigger=10,t._OnIntersectionEnterTrigger=11,t._OnIntersectionExitTrigger=12,t._OnKeyDownTrigger=13,t._OnKeyUpTrigger=14,t._OnPickOutTrigger=15,t.DragMovementThreshold=10,t.LongPressDelay=500,t})();e.ActionManager=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n,o,s,a,h){void 0===o&&(o=1e3),t.call(this,e,s),this.propertyPath=r,this.value=n,this.duration=o,this.stopOtherAnimations=a,this.onInterpolationDone=h,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){var t,i=this._actionManager.getScene(),r=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)t=e.Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof e.Color3)t=e.Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof e.Vector3)t=e.Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof e.Matrix)t=e.Animation.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof e.Quaternion))return void e.Tools.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");t=e.Animation.ANIMATIONTYPE_QUATERNION}var n=new e.Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),t,e.Animation.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(r),this.stopOtherAnimations&&i.stopAnimation(this._effectiveTarget),i.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,this.onInterpolationDone)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"InterpolateValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)},{name:"duration",value:e.Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:e.Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},i)},i})(e.Action);e.InterpolateValueAction=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(e,i,r,n){t.call(this,e,n),this.propertyPath=r,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SwitchBooleanAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},i)},i})(e.Action);e.SwitchBooleanAction=t;var i=(function(t){function i(e,i,r,n){t.call(this,e,n),this.value=r,this._target=i}return __extends(i,t),i.prototype.execute=function(){this._target.state=this.value},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetStateAction",properties:[e.Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},i)},i})(e.Action);e.SetStateAction=i;var r=(function(t){function i(e,i,r,n,o){t.call(this,e,o),this.propertyPath=r,this.value=n,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},i.prototype.execute=function(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)}]},i)},i})(e.Action);e.SetValueAction=r;var n=(function(t){function i(e,i,r,n,o){t.call(this,e,o),this.propertyPath=r,this.value=n,this._target=this._effectiveTarget=i}return __extends(i,t),i.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&e.Tools.Warn("Warning: IncrementValueAction can only be used with number values")},i.prototype.execute=function(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"IncrementValueAction",properties:[e.Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:e.Action._SerializeValueAsString(this.value)}]},i)},i})(e.Action);e.IncrementValueAction=n;var o=(function(t){function i(e,i,r,n,o,s){t.call(this,e,s),this.from=r,this.to=n,this.loop=o,this._target=i}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"PlayAnimationAction",properties:[e.Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:e.Action._SerializeValueAsString(this.loop)||!1}]},i)},i})(e.Action);e.PlayAnimationAction=o;var s=(function(t){function i(e,i,r){t.call(this,e,r),this._target=i}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){var e=this._actionManager.getScene();e.stopAnimation(this._target)},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"StopAnimationAction",properties:[e.Action._GetTargetProperty(this._target)]},i)},i})(e.Action);e.StopAnimationAction=s;var a=(function(t){function i(i,r){void 0===i&&(i=e.ActionManager.NothingTrigger),t.call(this,i,r)}return __extends(i,t),i.prototype.execute=function(){},i.prototype.serialize=function(e){return t.prototype._serialize.call(this,{name:"DoNothingAction",properties:[]},e)},i})(e.Action);e.DoNothingAction=a;var h=(function(e){function t(t,i,r){e.call(this,t,r),this.children=i}return __extends(t,e),t.prototype._prepare=function(){for(var e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()},t.prototype.execute=function(e){for(var t=0;t<this.children.length;t++)this.children[t].execute(e)},t.prototype.serialize=function(t){for(var i=e.prototype._serialize.call(this,{name:"CombineAction",properties:[],combine:[]},t),r=0;r<this.children.length;r++)i.combine.push(this.children[r].serialize(null));return i},t})(e.Action);e.CombineAction=h;var c=(function(e){function t(t,i,r){e.call(this,t,r),this.func=i}return __extends(t,e),t.prototype.execute=function(e){this.func(e)},t})(e.Action);e.ExecuteCodeAction=c;var l=(function(t){function i(e,i,r,n){t.call(this,e,n),this._target=i,this._parent=r}return __extends(i,t),i.prototype._prepare=function(){},i.prototype.execute=function(){if(this._target.parent!==this._parent){var t=this._parent.getWorldMatrix().clone();t.invert(),this._target.position=e.Vector3.TransformCoordinates(this._target.position,t),this._target.parent=this._parent}},i.prototype.serialize=function(i){return t.prototype._serialize.call(this,{name:"SetParentAction",properties:[e.Action._GetTargetProperty(this._target),e.Action._GetTargetProperty(this._parent)]},i)},i})(e.Action);e.SetParentAction=l;var u=(function(e){function t(t,i,r){e.call(this,t,r),this._sound=i}return __extends(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.play()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t})(e.Action);e.PlaySoundAction=u;var d=(function(e){function t(t,i,r){e.call(this,t,r),this._sound=i}return __extends(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.stop()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t})(e.Action);e.StopSoundAction=d})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this.id=t,this._engine=i.getEngine(),this._meshes=[],this._scene=i,this._vertexBuffers={},this._indices=[],r?this.setAllVerticesData(r,n):(this._totalVertices=0,this._indices=[]),o&&(o instanceof e.LinesMesh&&(this.boundingBias=new e.Vector2(0,o.intersectionThreshold),this.updateExtend()),this.applyToMesh(o),o.computeWorldMatrix(!0))}return Object.defineProperty(t.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(e){this._boundingBias&&this._boundingBias.equals(e)||(this._boundingBias=e.clone(),this.updateBoundingInfo(!0,null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extend",{get:function(){return this._extend},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEngine=function(){return this._engine},t.prototype.isReady=function(){return this.delayLoadState===e.Engine.DELAYLOADSTATE_LOADED||this.delayLoadState===e.Engine.DELAYLOADSTATE_NONE},Object.defineProperty(t.prototype,"doNotSerialize",{get:function(){for(var e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0},enumerable:!0,configurable:!0}),t.prototype.setAllVerticesData=function(e,t){e.applyToGeometry(this,t),this.notifyUpdate()},t.prototype.setVerticesData=function(t,i,r,n){var o=new e.VertexBuffer(this._engine,i,t,r,0===this._meshes.length,n);this.setVerticesBuffer(o)},t.prototype.setVerticesBuffer=function(t){var i=t.getKind();if(this._vertexBuffers[i]&&this._vertexBuffers[i].dispose(),this._vertexBuffers[i]=t,i===e.VertexBuffer.PositionKind){var r=t.getData(),n=t.getStrideSize();this._totalVertices=r.length/n,this.updateExtend(r,n);for(var o=this._meshes,s=o.length,a=0;a<s;a++){var h=o[a];h._resetPointsArrayCache(),h._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),h._createGlobalSubMesh(),h.computeWorldMatrix(!0)}}this.notifyUpdate(i)},t.prototype.updateVerticesDataDirectly=function(e,t,i){var r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,i),this.notifyUpdate(e))},t.prototype.updateVerticesData=function(t,i,r){var n=this.getVertexBuffer(t);if(n){if(n.update(i),t===e.VertexBuffer.PositionKind){var o=n.getStrideSize();this._totalVertices=i.length/o,this.updateBoundingInfo(r,i)}this.notifyUpdate(t)}},t.prototype.updateBoundingInfo=function(t,i){t&&this.updateExtend(i);for(var r=this._meshes,n=r.length,o=0;o<n;o++){var s=r[o];if(s._resetPointsArrayCache(),t){s._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum);for(var a=0;a<s.subMeshes.length;a++){var h=s.subMeshes[a];h.refreshBoundingInfo()}}}},t.prototype.getTotalVertices=function(){return this.isReady()?this._totalVertices:0},t.prototype.getVerticesData=function(e,t){var i=this.getVertexBuffer(e);if(!i)return null;var r=i.getData();if(t&&1!==this._meshes.length){for(var n=r.length,o=[],s=0;s<n;s++)o.push(r[s]);return o}return r},t.prototype.getVertexBuffer=function(e){return this.isReady()?this._vertexBuffers[e]:null},t.prototype.getVertexBuffers=function(){return this.isReady()?this._vertexBuffers:null},t.prototype.isVerticesDataPresent=function(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&this._delayInfo.indexOf(e)!==-1},t.prototype.getVerticesDataKinds=function(){var e,t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t},t.prototype.setIndices=function(e,t){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),void 0!==t&&(this._totalVertices=t);for(var i=this._meshes,r=i.length,n=0;n<r;n++)i[n]._createGlobalSubMesh();this.notifyUpdate()},t.prototype.getTotalIndices=function(){return this.isReady()?this._indices.length:0},t.prototype.getIndices=function(e){if(!this.isReady())return null;var t=this._indices;if(e&&1!==this._meshes.length){for(var i=t.length,r=[],n=0;n<i;n++)r.push(t[n]);return r}return t},t.prototype.getIndexBuffer=function(){return this.isReady()?this._indexBuffer:null},t.prototype.releaseForMesh=function(e,t){var i=this._meshes,r=i.indexOf(e);if(r!==-1){for(var n in this._vertexBuffers)this._vertexBuffers[n].dispose();this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),i.splice(r,1),e._geometry=null,0===i.length&&t&&this.dispose()}},t.prototype.applyToMesh=function(e){if(e._geometry!==this){var t=e._geometry;t&&t.releaseForMesh(e);var i=this._meshes;e._geometry=this,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):e._boundingInfo=this._boundingInfo}},t.prototype.updateExtend=function(t,i){void 0===t&&(t=null),t||(t=this._vertexBuffers[e.VertexBuffer.PositionKind].getData()),this._extend=e.Tools.ExtractMinAndMax(t,0,this._totalVertices,this.boundingBias,i)},t.prototype._applyToMesh=function(t){var i=this._meshes.length;for(var r in this._vertexBuffers)1===i&&this._vertexBuffers[r].create(),this._vertexBuffers[r].getBuffer().references=i,r===e.VertexBuffer.PositionKind&&(t._resetPointsArrayCache(),this._extend||this.updateExtend(this._vertexBuffers[r].getData()),t._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),t._createGlobalSubMesh(),t._updateBoundingInfo());1===i&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=i)},t.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e)},t.prototype.load=function(t,i){if(this.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADING){if(this.isReady())return void(i&&i());this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADING,this._queueLoad(t,i)}},t.prototype._queueLoad=function(t,i){var r=this;t._addPendingData(this),e.Tools.LoadFile(this.delayLoadingFile,(function(n){r._delayLoadingFunction(JSON.parse(n),r),r.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,r._delayInfo=[],t._removePendingData(r);for(var o=r._meshes,s=o.length,a=0;a<s;a++)r._applyToMesh(o[a]);i&&i()}),(function(){}),t.database)},t.prototype.toLeftHanded=function(){var t=this.getIndices(!1);if(null!=t&&t.length>0){for(var i=0;i<t.length;i+=3){var r=t[i+0];t[i+0]=t[i+2],t[i+2]=r}this.setIndices(t)}var n=this.getVerticesData(e.VertexBuffer.PositionKind,!1);if(null!=n&&n.length>0){for(var i=0;i<n.length;i+=3)n[i+2]=-n[i+2];this.setVerticesData(e.VertexBuffer.PositionKind,n,!1)}var o=this.getVerticesData(e.VertexBuffer.NormalKind,!1);if(null!=o&&o.length>0){for(var i=0;i<o.length;i+=3)o[i+2]=-o[i+2];this.setVerticesData(e.VertexBuffer.NormalKind,o,!1)}},t.prototype.isDisposed=function(){return this._isDisposed},t.prototype.dispose=function(){var t,i=this._meshes,r=i.length;for(t=0;t<r;t++)this.releaseForMesh(i[t]);this._meshes=[];for(var n in this._vertexBuffers)this._vertexBuffers[n].dispose();this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=e.Engine.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._isDisposed=!0},t.prototype.copy=function(i){var r=new e.VertexData;r.indices=[];for(var n=this.getIndices(),o=0;o<n.length;o++)r.indices.push(n[o]);var s,a=!1,h=!1;for(s in this._vertexBuffers){var c=this.getVerticesData(s);c instanceof Float32Array?r.set(new Float32Array(c),s):r.set(c.slice(0),s),h||(a=this.getVertexBuffer(s).isUpdatable(),h=!a)}var l=new t(i,this._scene,r,a,null);l.delayLoadState=this.delayLoadState,l.delayLoadingFile=this.delayLoadingFile,l._delayLoadingFunction=this._delayLoadingFunction;for(s in this._delayInfo)l._delayInfo=l._delayInfo||[],l._delayInfo.push(s);return l._boundingInfo=new e.BoundingInfo(this._extend.minimum,this._extend.maximum),l},t.prototype.serialize=function(){var t={};return t.id=this.id,e.Tags.HasTags(this)&&(t.tags=e.Tags.GetTags(this)),t},t.prototype.serializeVerticeData=function(){var t=this.serialize();return this.isVerticesDataPresent(e.VertexBuffer.PositionKind)&&(t.positions=this.getVerticesData(e.VertexBuffer.PositionKind)),this.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(t.normals=this.getVerticesData(e.VertexBuffer.NormalKind)),this.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(t.uvs=this.getVerticesData(e.VertexBuffer.UVKind)),this.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(t.uv2s=this.getVerticesData(e.VertexBuffer.UV2Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV3Kind)&&(t.uv3s=this.getVerticesData(e.VertexBuffer.UV3Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV4Kind)&&(t.uv4s=this.getVerticesData(e.VertexBuffer.UV4Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV5Kind)&&(t.uv5s=this.getVerticesData(e.VertexBuffer.UV5Kind)),this.isVerticesDataPresent(e.VertexBuffer.UV6Kind)&&(t.uv6s=this.getVerticesData(e.VertexBuffer.UV6Kind)),this.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(t.colors=this.getVerticesData(e.VertexBuffer.ColorKind)),this.isVerticesDataPresent(e.VertexBuffer.MatricesIndicesKind)&&(t.matricesIndices=this.getVerticesData(e.VertexBuffer.MatricesIndicesKind),t.matricesIndices._isExpanded=!0),this.isVerticesDataPresent(e.VertexBuffer.MatricesWeightsKind)&&(t.matricesWeights=this.getVerticesData(e.VertexBuffer.MatricesWeightsKind)),t.indices=this.getIndices(),t},t.ExtractFromMesh=function(e,t){var i=e._geometry;return i?i.copy(t):null},t.RandomId=function(){return e.Tools.RandomId()},t.ImportGeometry=function(t,i){var r=i.getScene(),n=t.geometryId;if(n){var o=r.getGeometryByID(n);o&&o.applyToMesh(i)}else if(t instanceof ArrayBuffer){var s=i._binaryInfo;if(s.positionsAttrDesc&&s.positionsAttrDesc.count>0){var a=new Float32Array(t,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);i.setVerticesData(e.VertexBuffer.PositionKind,a,!1)}if(s.normalsAttrDesc&&s.normalsAttrDesc.count>0){var h=new Float32Array(t,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);i.setVerticesData(e.VertexBuffer.NormalKind,h,!1)}if(s.uvsAttrDesc&&s.uvsAttrDesc.count>0){var c=new Float32Array(t,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);i.setVerticesData(e.VertexBuffer.UVKind,c,!1)}if(s.uvs2AttrDesc&&s.uvs2AttrDesc.count>0){var l=new Float32Array(t,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV2Kind,l,!1)}if(s.uvs3AttrDesc&&s.uvs3AttrDesc.count>0){var u=new Float32Array(t,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV3Kind,u,!1)}if(s.uvs4AttrDesc&&s.uvs4AttrDesc.count>0){var d=new Float32Array(t,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV4Kind,d,!1)}if(s.uvs5AttrDesc&&s.uvs5AttrDesc.count>0){var f=new Float32Array(t,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV5Kind,f,!1)}if(s.uvs6AttrDesc&&s.uvs6AttrDesc.count>0){var p=new Float32Array(t,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);i.setVerticesData(e.VertexBuffer.UV6Kind,p,!1)}if(s.colorsAttrDesc&&s.colorsAttrDesc.count>0){var _=new Float32Array(t,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);i.setVerticesData(e.VertexBuffer.ColorKind,_,!1,s.colorsAttrDesc.stride)}if(s.matricesIndicesAttrDesc&&s.matricesIndicesAttrDesc.count>0){var m=new Int32Array(t,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count);i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,m,!1)}if(s.matricesWeightsAttrDesc&&s.matricesWeightsAttrDesc.count>0){var g=new Float32Array(t,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);i.setVerticesData(e.VertexBuffer.MatricesWeightsKind,g,!1)}if(s.indicesAttrDesc&&s.indicesAttrDesc.count>0){var v=new Int32Array(t,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);i.setIndices(v)}if(s.subMeshesAttrDesc&&s.subMeshesAttrDesc.count>0){var y=new Int32Array(t,s.subMeshesAttrDesc.offset,5*s.subMeshesAttrDesc.count);i.subMeshes=[];for(var x=0;x<s.subMeshesAttrDesc.count;x++){var b=y[5*x+0],A=y[5*x+1],T=y[5*x+2],E=y[5*x+3],P=y[5*x+4];new e.SubMesh(b,A,T,E,P,i)}}}else if(t.positions&&t.normals&&t.indices){if(i.setVerticesData(e.VertexBuffer.PositionKind,t.positions,!1),i.setVerticesData(e.VertexBuffer.NormalKind,t.normals,!1),t.uvs&&i.setVerticesData(e.VertexBuffer.UVKind,t.uvs,!1),t.uvs2&&i.setVerticesData(e.VertexBuffer.UV2Kind,t.uvs2,!1),t.uvs3&&i.setVerticesData(e.VertexBuffer.UV3Kind,t.uvs3,!1),t.uvs4&&i.setVerticesData(e.VertexBuffer.UV4Kind,t.uvs4,!1),t.uvs5&&i.setVerticesData(e.VertexBuffer.UV5Kind,t.uvs5,!1),t.uvs6&&i.setVerticesData(e.VertexBuffer.UV6Kind,t.uvs6,!1),t.colors&&i.setVerticesData(e.VertexBuffer.ColorKind,e.Color4.CheckColors4(t.colors,t.positions.length/3),!1),t.matricesIndices)if(t.matricesIndices._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,t.matricesIndices,!1);else{for(var S=[],x=0;x<t.matricesIndices.length;x++){var M=t.matricesIndices[x];S.push(255&M),S.push((65280&M)>>8),S.push((16711680&M)>>16),S.push(M>>24)}i.setVerticesData(e.VertexBuffer.MatricesIndicesKind,S,!1)}if(t.matricesIndicesExtra)if(t.matricesIndicesExtra._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,t.matricesIndicesExtra,!1);else{for(var S=[],x=0;x<t.matricesIndicesExtra.length;x++){var M=t.matricesIndicesExtra[x];S.push(255&M),S.push((65280&M)>>8),S.push((16711680&M)>>16),S.push(M>>24)}i.setVerticesData(e.VertexBuffer.MatricesIndicesExtraKind,S,!1)}t.matricesWeights&&i.setVerticesData(e.VertexBuffer.MatricesWeightsKind,t.matricesWeights,!1),t.matricesWeightsExtra&&i.setVerticesData(e.VertexBuffer.MatricesWeightsExtraKind,t.matricesWeightsExtra,!1),i.setIndices(t.indices)}if(t.subMeshes){i.subMeshes=[];for(var C=0;C<t.subMeshes.length;C++){var R=t.subMeshes[C];new e.SubMesh(R.materialIndex,R.verticesStart,R.verticesCount,R.indexStart,R.indexCount,i)}}i._shouldGenerateFlatShading&&(i.convertToFlatShadedMesh(),delete i._shouldGenerateFlatShading),i.computeWorldMatrix(!0),r._selectionOctree&&r._selectionOctree.addMesh(i)},t.Parse=function(i,r,n){if(r.getGeometryByID(i.id))return null;var o=new t(i.id,r);return e.Tags.AddTagsTo(o,i.tags),i.delayLoadingFile?(o.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED,o.delayLoadingFile=n+i.delayLoadingFile,o._boundingInfo=new e.BoundingInfo(e.Vector3.FromArray(i.boundingBoxMinimum),e.Vector3.FromArray(i.boundingBoxMaximum)),o._delayInfo=[],i.hasUVs&&o._delayInfo.push(e.VertexBuffer.UVKind),i.hasUVs2&&o._delayInfo.push(e.VertexBuffer.UV2Kind),i.hasUVs3&&o._delayInfo.push(e.VertexBuffer.UV3Kind),i.hasUVs4&&o._delayInfo.push(e.VertexBuffer.UV4Kind),i.hasUVs5&&o._delayInfo.push(e.VertexBuffer.UV5Kind),i.hasUVs6&&o._delayInfo.push(e.VertexBuffer.UV6Kind),i.hasColors&&o._delayInfo.push(e.VertexBuffer.ColorKind),i.hasMatricesIndices&&o._delayInfo.push(e.VertexBuffer.MatricesIndicesKind),i.hasMatricesWeights&&o._delayInfo.push(e.VertexBuffer.MatricesWeightsKind),o._delayLoadingFunction=e.VertexData.ImportVertexData):e.VertexData.ImportVertexData(i,o),r.pushGeometry(o,!0),o},t})();e.Geometry=t;var t;!(function(t){var i;!(function(i){var r=(function(e){function t(t,i,r,n){e.call(this,t,i,null,!1,n),this._canBeRegenerated=r,this._beingRegenerated=!0,this.regenerate(),this._beingRegenerated=!1}return __extends(t,e),t.prototype.canBeRegenerated=function(){return this._canBeRegenerated},t.prototype.regenerate=function(){this._canBeRegenerated&&(this._beingRegenerated=!0,this.setAllVerticesData(this._regenerateVertexData(),!1),this._beingRegenerated=!1)},t.prototype.asNewGeometry=function(t){return e.prototype.copy.call(this,t)},t.prototype.setAllVerticesData=function(t,i){this._beingRegenerated&&e.prototype.setAllVerticesData.call(this,t,!1)},t.prototype.setVerticesData=function(t,i,r){this._beingRegenerated&&e.prototype.setVerticesData.call(this,t,i,!1)},t.prototype._regenerateVertexData=function(){throw new Error("Abstract method")},t.prototype.copy=function(e){throw new Error("Must be overriden in sub-classes.")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.canBeRegenerated=this.canBeRegenerated(),t},t})(t);i._Primitive=r;var n=(function(t){function i(i,r,n,o,s,a,h,c,l){void 0===l&&(l=e.Mesh.DEFAULTSIDE),t.call(this,i,r,h,c),this.pathArray=n,this.closeArray=o,this.closePath=s,this.offset=a,this.side=l}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateRibbon({pathArray:this.pathArray,closeArray:this.closeArray,closePath:this.closePath,offset:this.offset,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.pathArray,this.closeArray,this.closePath,this.offset,this.canBeRegenerated(),null,this.side)},i})(r);i.Ribbon=n;var o=(function(i){function r(t,r,n,o,s,a){void 0===a&&(a=e.Mesh.DEFAULTSIDE),i.call(this,t,r,o,s),this.size=n,this.side=a}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateBox({size:this.size,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.size=this.size,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Box(i.id,r,i.size,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Box=o;var s=(function(i){function r(t,r,n,o,s,a,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE),i.call(this,t,r,s,a),this.segments=n,this.diameter=o,this.side=h}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateSphere({segments:this.segments,diameter:this.diameter,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.segments,this.diameter,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.segments=this.segments,e.diameter=this.diameter,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Sphere(i.id,r,i.segments,i.diameter,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Sphere=s;var a=(function(t){function i(i,r,n,o,s,a,h){void 0===h&&(h=e.Mesh.DEFAULTSIDE),t.call(this,i,r,s,a),this.radius=n,this.tessellation=o,this.side=h}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateDisc({radius:this.radius,tessellation:this.tessellation,sideOrientation:this.side})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.radius,this.tessellation,this.canBeRegenerated(),null,this.side)},i})(r);i.Disc=a;var h=(function(i){function r(t,r,n,o,s,a,h,c,l,u){void 0===h&&(h=1),void 0===u&&(u=e.Mesh.DEFAULTSIDE),i.call(this,t,r,c,l),this.height=n,this.diameterTop=o,this.diameterBottom=s,this.tessellation=a,this.subdivisions=h,this.side=u}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateCylinder({height:this.height,diameterTop:this.diameterTop,diameterBottom:this.diameterBottom,tessellation:this.tessellation,subdivisions:this.subdivisions,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.height,this.diameterTop,this.diameterBottom,this.tessellation,this.subdivisions,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.height=this.height,e.diameterTop=this.diameterTop,e.diameterBottom=this.diameterBottom,e.tessellation=this.tessellation,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Cylinder(i.id,r,i.height,i.diameterTop,i.diameterBottom,i.tessellation,i.subdivisions,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Cylinder=h;var c=(function(i){function r(t,r,n,o,s,a,h,c){void 0===c&&(c=e.Mesh.DEFAULTSIDE),i.call(this,t,r,a,h),this.diameter=n,this.thickness=o,this.tessellation=s,this.side=c}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorus({diameter:this.diameter,thickness:this.thickness,tessellation:this.tessellation,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.diameter,this.thickness,this.tessellation,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.diameter=this.diameter,e.thickness=this.thickness,e.tessellation=this.tessellation,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Torus(i.id,r,i.diameter,i.thickness,i.tessellation,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Torus=c;var l=(function(i){function r(e,t,r,n,o,s,a){i.call(this,e,t,s,a),this.width=r,this.height=n,this.subdivisions=o}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateGround({width:this.width,height:this.height,subdivisions:this.subdivisions})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.width,this.height,this.subdivisions,this.canBeRegenerated(),null)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.width=this.width,e.height=this.height,e.subdivisions=this.subdivisions,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Ground(i.id,r,i.width,i.height,i.subdivisions,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Ground=l;var u=(function(t){function i(e,i,r,n,o,s,a,h,c,l){t.call(this,e,i,c,l),this.xmin=r,this.zmin=n,this.xmax=o,this.zmax=s,this.subdivisions=a,this.precision=h}return __extends(i,t),i.prototype._regenerateVertexData=function(){return e.VertexData.CreateTiledGround({xmin:this.xmin,zmin:this.zmin,xmax:this.xmax,zmax:this.zmax,subdivisions:this.subdivisions,precision:this.precision})},i.prototype.copy=function(e){return new i(e,this.getScene(),this.xmin,this.zmin,this.xmax,this.zmax,this.subdivisions,this.precision,this.canBeRegenerated(),null)},i})(r);i.TiledGround=u;var d=(function(i){function r(t,r,n,o,s,a){void 0===a&&(a=e.Mesh.DEFAULTSIDE),i.call(this,t,r,o,s),this.size=n,this.side=a}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreatePlane({size:this.size,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.size,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);
return e.size=this.size,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.Plane(i.id,r,i.size,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.Plane=d;var f=(function(i){function r(t,r,n,o,s,a,h,c,l,u,d){void 0===d&&(d=e.Mesh.DEFAULTSIDE),i.call(this,t,r,l,u),this.radius=n,this.tube=o,this.radialSegments=s,this.tubularSegments=a,this.p=h,this.q=c,this.side=d}return __extends(r,i),r.prototype._regenerateVertexData=function(){return e.VertexData.CreateTorusKnot({radius:this.radius,tube:this.tube,radialSegments:this.radialSegments,tubularSegments:this.tubularSegments,p:this.p,q:this.q,sideOrientation:this.side})},r.prototype.copy=function(e){return new r(e,this.getScene(),this.radius,this.tube,this.radialSegments,this.tubularSegments,this.p,this.q,this.canBeRegenerated(),null,this.side)},r.prototype.serialize=function(){var e=i.prototype.serialize.call(this);return e.radius=this.radius,e.tube=this.tube,e.radialSegments=this.radialSegments,e.tubularSegments=this.tubularSegments,e.p=this.p,e.q=this.q,e},r.Parse=function(i,r){if(r.getGeometryByID(i.id))return null;var n=new t.Primitives.TorusKnot(i.id,r,i.radius,i.tube,i.radialSegments,i.tubularSegments,i.p,i.q,i.canBeRegenerated,null);return e.Tags.AddTagsTo(n,i.tags),r.pushGeometry(n,!0),n},r})(r);i.TorusKnot=f})(i=t.Primitives||(t.Primitives={}))})(t=e.Geometry||(e.Geometry={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,i,r),this.generateOctree=!1,this._worldInverse=new e.Matrix}return __extends(i,t),Object.defineProperty(i.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!0,configurable:!0}),i.prototype.optimize=function(e,t){void 0===t&&(t=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e),this.createOrUpdateSubmeshesOctree(t)},i.prototype.getHeightAtCoordinates=function(e,t){if(e-=this.position.x,t-=this.position.z,e/=this.scaling.x,t/=this.scaling.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var i=this._getFacetAt(e,t),r=-(i.x*e+i.z*t+i.w)/i.y;return r*this.scaling.y+this.position.y},i.prototype.getNormalAtCoordinates=function(t,i){var r=new e.Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(t,i,r),r},i.prototype.getNormalAtCoordinatesToRef=function(e,t,i){if(e-=this.position.x,t-=this.position.z,e/=this.scaling.x,t/=this.scaling.z,!(e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)){this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var r=this._getFacetAt(e,t);i.x=r.x,i.y=r.y,i.z=r.z}},i.prototype.updateCoordinateHeights=function(){this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads()},i.prototype._getFacetAt=function(e,t){var i,r=(this._subdivisionsX,this._subdivisionsY,Math.floor((e+this._maxX)*this._subdivisionsX/this._width)),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),o=this._heightQuads[n*this._subdivisionsX+r];return i=t<o.slope.x*e+o.slope.y?o.facet1:o.facet2},i.prototype._initHeightQuads=function(){var t=this._subdivisionsX,i=this._subdivisionsY;this._heightQuads=new Array;for(var r=0;r<i;r++)for(var n=0;n<t;n++){var o={slope:e.Vector2.Zero(),facet1:new e.Vector4(0,0,0,0),facet2:new e.Vector4(0,0,0,0)};this._heightQuads[r*t+n]=o}},i.prototype._computeHeightQuads=function(){for(var t=this.getVerticesData(e.VertexBuffer.PositionKind),i=e.Tmp.Vector3[3],r=e.Tmp.Vector3[2],n=e.Tmp.Vector3[1],o=e.Tmp.Vector3[0],s=e.Tmp.Vector3[4],a=e.Tmp.Vector3[5],h=e.Tmp.Vector3[6],c=e.Tmp.Vector3[7],l=e.Tmp.Vector3[8],u=0,d=0,f=0,p=0,_=0,m=0,g=0,v=this._subdivisionsX,y=this._subdivisionsY,x=0;x<y;x++)for(var b=0;b<v;b++){u=3*b,d=x*(v+1)*3,f=(x+1)*(v+1)*3,i.x=t[d+u],i.y=t[d+u+1],i.z=t[d+u+2],r.x=t[d+u+3],r.y=t[d+u+4],r.z=t[d+u+5],n.x=t[f+u],n.y=t[f+u+1],n.z=t[f+u+2],o.x=t[f+u+3],o.y=t[f+u+4],o.z=t[f+u+5],p=(o.z-i.z)/(o.x-i.x),_=i.z-p*i.x,r.subtractToRef(i,s),n.subtractToRef(i,a),o.subtractToRef(i,h),e.Vector3.CrossToRef(h,a,c),e.Vector3.CrossToRef(s,h,l),c.normalize(),l.normalize(),m=-(c.x*i.x+c.y*i.y+c.z*i.z),g=-(l.x*r.x+l.y*r.y+l.z*r.z);var A=this._heightQuads[x*v+b];A.slope.copyFromFloats(p,_),A.facet1.copyFromFloats(c.x,c.y,c.z,m),A.facet2.copyFromFloats(l.x,l.y,l.z,g)}},i})(e.Mesh);e.GroundMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===n&&(n=null),t.call(this,i,r,n,o,s),this.color=new e.Color3(1,1,1),this.alpha=1,this._positionBuffer={},o&&(this.color=o.color.clone(),this.alpha=o.alpha),this._intersectionThreshold=.1,this._colorShader=new e.ShaderMaterial("colorShader",r,"color",{attributes:[e.VertexBuffer.PositionKind],uniforms:["worldViewProjection","color"],needAlphaBlending:!0}),this._positionBuffer[e.VertexBuffer.PositionKind]=null}return __extends(i,t),Object.defineProperty(i.prototype,"intersectionThreshold",{get:function(){return this._intersectionThreshold},set:function(t){this._intersectionThreshold!==t&&(this._intersectionThreshold=t,this.geometry&&(this.geometry.boundingBias=new e.Vector2(0,t)))},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"material",{get:function(){return this._colorShader},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"checkCollisions",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.createInstance=function(t){return e.Tools.Log("LinesMeshes do not support createInstance."),null},i.prototype._bind=function(t,i,r){var n=this.getScene().getEngine();this._positionBuffer[e.VertexBuffer.PositionKind]=this._geometry.getVertexBuffer(e.VertexBuffer.PositionKind),n.bindBuffers(this._positionBuffer,this._geometry.getIndexBuffer(),this._colorShader.getEffect()),this._colorShader.setColor4("color",this.color.toColor4(this.alpha))},i.prototype._draw=function(e,t,i){if(this._geometry&&this._geometry.getVertexBuffers()&&this._geometry.getIndexBuffer()){var r=this.getScene().getEngine();r.draw(!1,e.indexStart,e.indexCount)}},i.prototype.dispose=function(e){this._colorShader.dispose(),t.prototype.dispose.call(this,e)},i.prototype.clone=function(e,t,r){return new i(e,this.getScene(),t,this,r)},i})(e.Mesh);e.LinesMesh=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){var r=this;void 0===t&&(t=""),void 0===i&&(i="black"),this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=function(){var e=r._renderingCanvas.getBoundingClientRect();r._loadingDiv.style.position="absolute",r._loadingDiv.style.left=e.left+"px",r._loadingDiv.style.top=e.top+"px",r._loadingDiv.style.width=e.width+"px",r._loadingDiv.style.height=e.height+"px"}}return e.prototype.displayLoadingUI=function(){var e=this;if(!this._loadingDiv){this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText;var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==",t.style.position="absolute",t.style.left="50%",t.style.top="50%",t.style.marginLeft="-50px",t.style.marginTop="-50px",t.style.transition="transform 1.0s ease",t.style.webkitTransition="-webkit-transform 1.0s ease";var i=360,r=function(){i+=360,t.style.transform="rotateZ("+i+"deg)",t.style.webkitTransform="rotateZ("+i+"deg)"};t.addEventListener("transitionend",r),t.addEventListener("webkitTransitionEnd",r),this._loadingDiv.appendChild(t);var n=new Image;n.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=",n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.marginLeft="-50px",n.style.marginTop="-50px",this._loadingDiv.appendChild(n),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),setTimeout((function(){e._loadingDiv.style.opacity="1",t.style.transform="rotateZ(360deg)",t.style.webkitTransform="rotateZ(360deg)"}),0)}},e.prototype.hideLoadingUI=function(){var e=this;if(this._loadingDiv){var t=function(){e._loadingDiv&&(document.body.removeChild(e._loadingDiv),window.removeEventListener("resize",e._resizeLoadingUI),e._loadingDiv=null)};this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",t)}},Object.defineProperty(e.prototype,"loadingUIText",{set:function(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loadingUIBackgroundColor",{get:function(){return this._loadingDivBackgroundColor},set:function(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)},enumerable:!0,configurable:!0}),e})();e.DefaultLoadingScreen=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._audioContext=null,this._audioContextInitialized=!1,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.unlocked=!1,this.isMP3supported=!1,this.isOGGsupported=!1,"undefined"==typeof window.AudioContext&&"undefined"==typeof window.webkitAudioContext||(window.AudioContext=window.AudioContext||window.webkitAudioContext,this.canUseWebAudio=!0);var e=document.createElement("audio");e&&e.canPlayType&&e.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")&&(this.isMP3supported=!0),e&&e.canPlayType&&e.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0),/iPad|iPhone|iPod/.test(navigator.platform)?this._unlockiOSaudio():this.unlocked=!0}return Object.defineProperty(t.prototype,"audioContext",{get:function(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext},enumerable:!0,configurable:!0}),t.prototype._unlockiOSaudio=function(){var e=this,t=function(){var i=e.audioContext.createBuffer(1,1,22050),r=e.audioContext.createBufferSource();r.buffer=i,r.connect(e.audioContext.destination),r.start(0),setTimeout((function(){r.playbackState!==r.PLAYING_STATE&&r.playbackState!==r.FINISHED_STATE||(e.unlocked=!0,window.removeEventListener("touchend",t,!1),e.onAudioUnlocked&&e.onAudioUnlocked())}),0)};window.addEventListener("touchend",t,!1)},t.prototype._initializeAudioContext=function(){try{this.canUseWebAudio&&(this._audioContext=new AudioContext,this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this._audioContext.destination),this._audioContextInitialized=!0)}catch(t){this.canUseWebAudio=!1,e.Tools.Error("Web Audio: "+t.message)}},t.prototype.dispose=function(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1},t.prototype.getGlobalVolume=function(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1},t.prototype.setGlobalVolume=function(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)},t.prototype.connectToAnalyser=function(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))},t})();e.AudioEngine=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){var s=this;if(this.autoplay=!1,this.loop=!1,this.useCustomAttenuation=!1,this.spatialSound=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._startOffset=0,this._position=e.Vector3.Zero(),this._localDirection=new e.Vector3(1,0,0),this._volume=1,this._isLoaded=!1,this._isReadyToPlay=!1,this.isPlaying=!1,this.isPaused=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=t,this._scene=r,this._readyToPlayCallback=n,this._customAttenuationFunction=function(e,t,i,r,n){return t<i?e*(1-t/i):0},o&&(this.autoplay=o.autoplay||!1,this.loop=o.loop||!1,void 0!==o.volume&&(this._volume=o.volume),this.spatialSound=o.spatialSound||!1,this.maxDistance=o.maxDistance||100,this.useCustomAttenuation=o.useCustomAttenuation||!1,this.rolloffFactor=o.rolloffFactor||1,this.refDistance=o.refDistance||1,this.distanceModel=o.distanceModel||"linear",this._playbackRate=o.playbackRate||1,this._streaming=o.streaming||!1),e.Engine.audioEngine.canUseWebAudio){this._soundGain=e.Engine.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._ouputAudioNode=this._soundGain,this.spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.AddSound(this);var a=!0;if(i){"string"==typeof i&&(this._urlType="String"),Array.isArray(i)&&(this._urlType="Array"),i instanceof ArrayBuffer&&(this._urlType="ArrayBuffer");var h=[],c=!1;switch(this._urlType){case"ArrayBuffer":i.byteLength>0&&(c=!0,this._soundLoaded(i));break;case"String":h.push(i);case"Array":0===h.length&&(h=i);for(var l=0;l<h.length;l++){var u=h[l];if(u.indexOf(".mp3",u.length-4)!==-1&&e.Engine.audioEngine.isMP3supported&&(c=!0),u.indexOf(".ogg",u.length-4)!==-1&&e.Engine.audioEngine.isOGGsupported&&(c=!0),u.indexOf(".wav",u.length-4)!==-1&&(c=!0),c){this._streaming?(this._htmlAudioElement=new Audio(u),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,this._htmlAudioElement.crossOrigin="anonymous",this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(function(){s._isReadyToPlay=!0,s.autoplay&&s.play(),s._readyToPlayCallback&&s._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement)):e.Tools.LoadFile(u,(function(e){s._soundLoaded(e)}),null,this._scene.database,!0);break}}break;default:a=!1}a?c||(this._isReadyToPlay=!0,this._readyToPlayCallback&&window.setTimeout((function(){s._readyToPlayCallback()}),1e3)):e.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}}else this._scene.mainSoundTrack.AddSound(this),e.Engine.audioEngine.WarnedWebAudioUnsupported||(e.Tools.Error("Web Audio is not supported by your browser."),e.Engine.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&window.setTimeout((function(){s._readyToPlayCallback()}),1e3)}return t.prototype.dispose=function(){e.Engine.audioEngine.canUseWebAudio&&this._isReadyToPlay&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,this.soundTrackId===-1?this._scene.mainSoundTrack.RemoveSound(this):this._scene.soundTracks[this.soundTrackId].RemoveSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedMesh=null))},t.prototype._soundLoaded=function(t){var i=this;this._isLoaded=!0,e.Engine.audioEngine.audioContext.decodeAudioData(t,(function(e){i._audioBuffer=e,i._isReadyToPlay=!0,i.autoplay&&i.play(),i._readyToPlayCallback&&i._readyToPlayCallback()}),(function(t){e.Tools.Error("Error while decoding audio data for: "+i.name+" / Error: "+t)}))},t.prototype.setAudioBuffer=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._audioBuffer=t,this._isReadyToPlay=!0)},t.prototype.updateOptions=function(e){e&&(this.loop=e.loop||this.loop,this.maxDistance=e.maxDistance||this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation||this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor||this.rolloffFactor,this.refDistance=e.refDistance||this.refDistance,this.distanceModel=e.distanceModel||this.distanceModel,this._playbackRate=e.playbackRate||this._playbackRate,this._updateSpatialParameters(),this.isPlaying&&(this._streaming?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource.playbackRate.value=this._playbackRate))},t.prototype._createSpatialParameters=function(){e.Engine.audioEngine.canUseWebAudio&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=e.Engine.audioEngine.audioContext.createPanner(),this._updateSpatialParameters(),this._soundPanner.connect(this._ouputAudioNode),this._inputAudioNode=this._soundPanner)},t.prototype._updateSpatialParameters=function(){this.spatialSound&&(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel))},t.prototype.switchPanningModelToHRTF=function(){this._panningModel="HRTF",this._switchPanningModel()},t.prototype.switchPanningModelToEqualPower=function(){this._panningModel="equalpower",this._switchPanningModel()},t.prototype._switchPanningModel=function(){e.Engine.audioEngine.canUseWebAudio&&this.spatialSound&&(this._soundPanner.panningModel=this._panningModel)},t.prototype.connectToSoundTrackAudioNode=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._isOutputConnected&&this._ouputAudioNode.disconnect(),this._ouputAudioNode.connect(t),this._isOutputConnected=!0)},t.prototype.setDirectionalCone=function(t,i,r){return i<t?void e.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=t,this._coneOuterAngle=i,this._coneOuterGain=r,this._isDirectional=!0,void(this.isPlaying&&this.loop&&(this.stop(),this.play())))},t.prototype.setPosition=function(t){this._position=t,e.Engine.audioEngine.canUseWebAudio&&this.spatialSound&&this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z)},t.prototype.setLocalDirectionToMesh=function(t){this._localDirection=t,e.Engine.audioEngine.canUseWebAudio&&this._connectedMesh&&this.isPlaying&&this._updateDirection()},t.prototype._updateDirection=function(){var t=this._connectedMesh.getWorldMatrix(),i=e.Vector3.TransformNormal(this._localDirection,t);i.normalize(),this._soundPanner.setOrientation(i.x,i.y,i.z)},t.prototype.updateDistanceFromListener=function(){if(e.Engine.audioEngine.canUseWebAudio&&this._connectedMesh&&this.useCustomAttenuation){var t=this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,t,this.maxDistance,this.refDistance,this.rolloffFactor)}},t.prototype.setAttenuationFunction=function(e){this._customAttenuationFunction=e},t.prototype.play=function(t,i){var r=this;if(this._isReadyToPlay&&this._scene.audioEnabled)try{this._startOffset<0&&(t=-this._startOffset,this._startOffset=0);var n=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource&&this._streamingSource||this.spatialSound&&(this._soundPanner.setPosition(this._position.x,this._position.y,this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedMesh?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming?(this._streamingSource||(this._streamingSource=e.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=function(){r._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement.play()):(this._soundSource=e.Engine.audioEngine.audioContext.createBufferSource(),this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=function(){r._onended()},this._soundSource.start(n,this.isPaused?this._startOffset%this._soundSource.buffer.duration:i?i:0)),this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(o){e.Tools.Error("Error while trying to play audio: "+this.name+", "+o.message)}},t.prototype._onended=function(){this.isPlaying=!1,this.onended&&this.onended()},t.prototype.stop=function(t){if(this.isPlaying){if(this._streaming)this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0);else{var i=t?e.Engine.audioEngine.audioContext.currentTime+t:e.Engine.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=null,this.isPaused||(this._startOffset=0)}this.isPlaying=!1}},t.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement.pause():(this.stop(0),this._startOffset+=e.Engine.audioEngine.audioContext.currentTime-this._startTime))},t.prototype.setVolume=function(t,i){e.Engine.audioEngine.canUseWebAudio&&(i?(this._soundGain.gain.cancelScheduledValues(e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,e.Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(t,e.Engine.audioEngine.audioContext.currentTime+i)):this._soundGain.gain.value=t),this._volume=t},t.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource.playbackRate.value=this._playbackRate)},t.prototype.getVolume=function(){return this._volume},t.prototype.attachToMesh=function(e){var t=this;this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedMesh=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},e.registerAfterWorldMatrixUpdate(this._registerFunc)},t.prototype.detachFromMesh=function(){this._connectedMesh&&(this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedMesh=null)},t.prototype._onRegisterAfterWorldMatrixUpdate=function(t){this.setPosition(t.getBoundingInfo().boundingSphere.centerWorld),e.Engine.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()},t.prototype.clone=function(){var e=this;if(this._streaming)return null;var i=function(){e._isReadyToPlay?(n._audioBuffer=e.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play()):window.setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new t(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},t.prototype.getAudioBuffer=function(){return this._audioBuffer},t.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedMesh&&(e.connectedMeshId=this._connectedMesh.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},t.Parse=function(i,r,n,o){var s,a=i.name;s=i.url?n+i.url:n+a;var h,c={autoplay:i.autoplay,loop:i.loop,volume:i.volume,spatialSound:i.spatialSound,maxDistance:i.maxDistance,rolloffFactor:i.rolloffFactor,refDistance:i.refDistance,distanceModel:i.distanceModel,playbackRate:i.playbackRate};if(o){var l=function(){o._isReadyToPlay?(h._audioBuffer=o.getAudioBuffer(),h._isReadyToPlay=!0,h.autoplay&&h.play()):window.setTimeout(l,300)};h=new t(a,new ArrayBuffer(0),r,null,c),l()}else h=new t(a,s,r,function(){r._removePendingData(h)},c),r._addPendingData(h);if(i.position){var u=e.Vector3.FromArray(i.position);h.setPosition(u)}if(i.isDirectional&&(h.setDirectionalCone(i.coneInnerAngle||360,i.coneOuterAngle||360,i.coneOuterGain||0),i.localDirectionToMesh)){var d=e.Vector3.FromArray(i.localDirectionToMesh);h.setLocalDirectionToMesh(d)}if(i.connectedMeshId){var f=r.getMeshByID(i.connectedMeshId);f&&h.attachToMesh(f)}return h},t})();e.Sound=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t){this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,this._isMainTrack||(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return t.prototype._initializeSoundTrackAudioGraph=function(){e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode=e.Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(e.Engine.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},t.prototype.dispose=function(){if(e.Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},t.prototype.AddSound=function(t){this._isInitialized||this._initializeSoundTrackAudioGraph(),e.Engine.audioEngine.canUseWebAudio&&t.connectToSoundTrackAudioNode(this._outputAudioNode),t.soundTrackId&&(t.soundTrackId===-1?this._scene.mainSoundTrack.RemoveSound(t):this._scene.soundTracks[t.soundTrackId].RemoveSound(t)),this.soundCollection.push(t),
t.soundTrackId=this.id},t.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);t!==-1&&this.soundCollection.splice(t,1)},t.prototype.setVolume=function(t){e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode.gain.value=t)},t.prototype.switchPanningModelToHRTF=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToHRTF()},t.prototype.switchPanningModelToEqualPower=function(){if(e.Engine.audioEngine.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToEqualPower()},t.prototype.connectToAnalyser=function(t){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=t,e.Engine.audioEngine.canUseWebAudio&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,e.Engine.audioEngine.masterGain))},t})();e.SoundTrack=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,i,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,o,s,a,h,c),this.direction=r,this.blurWidth=n,this.onApplyObservable.add((function(e){e.setFloat2("screenSize",l.width,l.height),e.setVector2("direction",l.direction),e.setFloat("blurWidth",l.blurWidth)}))}return __extends(i,t),i})(e.PostProcess),i=(function(){function i(t,r,n){this._vertexBuffers={},this._mainTextureDesiredSize={width:0,height:0},this._meshes={},this._maxSize=0,this._shouldRender=!1,this._instanceGlowingMeshStencilReference=i.glowingMeshStencilReference++,this._excludedMeshes={},this.innerGlow=!0,this.outerGlow=!0,this.isEnabled=!0,this.onDisposeObservable=new e.Observable,this.onBeforeRenderMainTextureObservable=new e.Observable,this.onBeforeBlurObservable=new e.Observable,this.onAfterBlurObservable=new e.Observable,this.onBeforeComposeObservable=new e.Observable,this.onAfterComposeObservable=new e.Observable,this.onSizeChangedObservable=new e.Observable,this._scene=r;var o=r.getEngine();this._engine=o,this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.highlightLayers.push(this),this._engine.isStencilEnable||e.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }"),this._options=n||{mainTextureRatio:.25,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:e.Engine.ALPHA_COMBINE},this._options.mainTextureRatio=this._options.mainTextureRatio||.25,this._options.blurTextureSizeRatio=this._options.blurTextureSizeRatio||.5,this._options.blurHorizontalSize=this._options.blurHorizontalSize||1,this._options.blurVerticalSize=this._options.blurVerticalSize||1,this._options.alphaBlendingMode=this._options.alphaBlendingMode||e.Engine.ALPHA_COMBINE;var s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1);var a=new e.VertexBuffer(o,s,e.VertexBuffer.PositionKind,(!1),(!1),2);this._vertexBuffers[e.VertexBuffer.PositionKind]=a;var h=[];h.push(0),h.push(1),h.push(2),h.push(0),h.push(2),h.push(3),this._indexBuffer=o.createIndexBuffer(h),this._glowMapMergeEffect=o.createEffect("glowMapMerge",[e.VertexBuffer.PositionKind],["offset"],["textureSampler"],""),this.setMainTextureSize(),this.createTextureAndPostProcesses()}return Object.defineProperty(i.prototype,"blurHorizontalSize",{get:function(){return this._horizontalBlurPostprocess.blurWidth},set:function(e){this._horizontalBlurPostprocess.blurWidth=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"blurVerticalSize",{get:function(){return this._verticalBlurPostprocess.blurWidth},set:function(e){this._verticalBlurPostprocess.blurWidth=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"camera",{get:function(){return this._options.camera},enumerable:!0,configurable:!0}),i.prototype.createTextureAndPostProcesses=function(){var r=this,n=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,o=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;n=e.Tools.GetExponentOfTwo(n,this._maxSize),o=e.Tools.GetExponentOfTwo(o,this._maxSize),this._mainTexture=new e.RenderTargetTexture("HighlightLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._mainTexture.activeCamera=this._options.camera,this._mainTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(e.Texture.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._blurTexture=new e.RenderTargetTexture("HighlightLayerBlurRTT",{width:n,height:o},this._scene,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._blurTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(e.Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._downSamplePostprocess=new e.PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.onApplyObservable.add((function(e){e.setTexture("textureSampler",r._mainTexture)})),this._options.alphaBlendingMode===e.Engine.ALPHA_COMBINE?(this._horizontalBlurPostprocess=new t("HighlightLayerHBP",new e.Vector2(1,0),this._options.blurHorizontalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)})),this._verticalBlurPostprocess=new t("HighlightLayerVBP",new e.Vector2(0,1),this._options.blurVerticalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)}))):(this._horizontalBlurPostprocess=new e.BlurPostProcess("HighlightLayerHBP",new e.Vector2(1,0),this._options.blurHorizontalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)})),this._verticalBlurPostprocess=new e.BlurPostProcess("HighlightLayerVBP",new e.Vector2(0,1),this._options.blurVerticalSize,1,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",n,o)}))),this._mainTexture.onAfterUnbindObservable.add((function(){r.onBeforeBlurObservable.notifyObservers(r),r._scene.postProcessManager.directRender([r._downSamplePostprocess,r._horizontalBlurPostprocess,r._verticalBlurPostprocess],r._blurTexture.getInternalTexture()),r.onAfterBlurObservable.notifyObservers(r)}));var s=function(t){var n=t.getRenderingMesh(),o=r._scene,s=o.getEngine();s.setState(t.getMaterial().backFaceCulling);var a=n._getInstancesRenderList(t._id);if(!a.mustReturn&&!r._excludedMeshes[n.id]){var h=null!==s.getCaps().instancedArrays&&null!==a.visibleInstances[t._id]&&void 0!==a.visibleInstances[t._id],c=r._meshes[n.id],l=t.getMaterial(),u=null;if(c&&c.glowEmissiveOnly&&l&&(u=l.emissiveTexture),r.isReady(t,h,u)){if(s.enableEffect(r._glowMapGenerationEffect),n._bind(t,r._glowMapGenerationEffect,e.Material.TriangleFillMode),r._glowMapGenerationEffect.setMatrix("viewProjection",o.getTransformMatrix()),c?r._glowMapGenerationEffect.setFloat4("color",c.color.r,c.color.g,c.color.b,1):r._glowMapGenerationEffect.setFloat4("color",i.neutralColor.r,i.neutralColor.g,i.neutralColor.b,i.neutralColor.a),l&&l.needAlphaTesting()){var d=l.getAlphaTestTexture();r._glowMapGenerationEffect.setTexture("diffuseSampler",d),r._glowMapGenerationEffect.setMatrix("diffuseMatrix",d.getTextureMatrix())}u&&(r._glowMapGenerationEffect.setTexture("emissiveSampler",u),r._glowMapGenerationEffect.setMatrix("emissiveMatrix",u.getTextureMatrix())),n.useBones&&n.computeBonesUsingShaders&&r._glowMapGenerationEffect.setMatrices("mBones",n.skeleton.getTransformMatrices(n)),n._processRendering(t,r._glowMapGenerationEffect,e.Material.TriangleFillMode,a,h,(function(e,t){return r._glowMapGenerationEffect.setMatrix("world",t)}))}else r._mainTexture.resetRefreshCounter()}};this._mainTexture.customRenderFunction=function(e,t,i){r.onBeforeRenderMainTextureObservable.notifyObservers(r);var n;for(n=0;n<e.length;n++)s(e.data[n]);for(n=0;n<t.length;n++)s(t.data[n]);for(n=0;n<i.length;n++)s(i.data[n])},this._mainTexture.onClearObservable.add((function(e){e.clear(i.neutralColor,!0,!0,!0)}))},i.prototype.isReady=function(t,i,r){if(!t.getMaterial().isReady(t.getMesh(),i))return!1;var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMesh(),a=t.getMaterial(),h=!1,c=!1;if(a&&a.needAlphaTesting()){var l=a.getAlphaTestTexture();l&&(n.push("#define ALPHATEST"),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===l.coordinatesIndex?(n.push("#define DIFFUSEUV2"),c=!0):s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push("#define DIFFUSEUV1"),h=!0))}r&&(n.push("#define EMISSIVE"),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&1===r.coordinatesIndex?(n.push("#define EMISSIVEUV2"),c=!0):s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push("#define EMISSIVEUV1"),h=!0)),h&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),c&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2")),s.useBones&&s.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),s.numBoneInfluencers>4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var u=n.join("\n");return this._cachedDefines!==u&&(this._cachedDefines=u,this._glowMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",o,["world","mBones","viewProjection","diffuseMatrix","color","emissiveMatrix"],["diffuseSampler","emissiveSampler"],u)),this._glowMapGenerationEffect.isReady()},i.prototype.render=function(){var t=this._glowMapMergeEffect;if(t.isReady()&&this._blurTexture.isReady()){var i=this._scene.getEngine();this.onBeforeComposeObservable.notifyObservers(this),i.enableEffect(t),i.setState(!1);var r=i.getStencilBuffer(),n=i.getStencilFunction(),o=i.getStencilMask(),s=i.getAlphaMode();t.setTexture("textureSampler",this._blurTexture),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t),i.setAlphaMode(this._options.alphaBlendingMode),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&(t.setFloat("offset",0),i.setStencilFunction(e.Engine.NOTEQUAL),i.draw(!0,0,6)),this.innerGlow&&(t.setFloat("offset",1),i.setStencilFunction(e.Engine.EQUAL),i.draw(!0,0,6)),i.setStencilFunction(n),i.setStencilMask(o),i.setAlphaMode(s),i.setStencilBuffer(r),this.onAfterComposeObservable.notifyObservers(this);var a=this._mainTexture.getSize();this.setMainTextureSize(),a.width===this._mainTextureDesiredSize.width&&a.height===this._mainTextureDesiredSize.height||(this.onSizeChangedObservable.notifyObservers(this),this.disposeTextureAndPostProcesses(),this.createTextureAndPostProcesses())}},i.prototype.addExcludedMesh=function(e){var t=this._excludedMeshes[e.id];t||(this._excludedMeshes[e.id]={mesh:e,beforeRender:e.onBeforeRenderObservable.add((function(e){e.getEngine().setStencilBuffer(!1)})),afterRender:e.onAfterRenderObservable.add((function(e){e.getEngine().setStencilBuffer(!0)}))})},i.prototype.removeExcludedMesh=function(e){var t=this._excludedMeshes[e.id];t&&(e.onBeforeRenderObservable.remove(t.beforeRender),e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.id]=void 0},i.prototype.addMesh=function(e,t,i){var r=this;void 0===i&&(i=!1);var n=this._meshes[e.id];n?n.color=t:this._meshes[e.id]={mesh:e,color:t,observerHighlight:e.onBeforeRenderObservable.add((function(e){r._excludedMeshes[e.id]?r.defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(r._instanceGlowingMeshStencilReference)})),observerDefault:e.onAfterRenderObservable.add(this.defaultStencilReference),glowEmissiveOnly:i},this._shouldRender=!0},i.prototype.removeMesh=function(e){var t=this._meshes[e.id];t&&(e.onBeforeRenderObservable.remove(t.observerHighlight),e.onAfterRenderObservable.remove(t.observerDefault)),this._meshes[e.id]=void 0,this._shouldRender=!1;for(var i in this._meshes)if(i){this._shouldRender=!0;break}},i.prototype.shouldRender=function(){return this.isEnabled&&this._shouldRender},i.prototype.setMainTextureSize=function(){this._options.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._options.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._options.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderingCanvas().width*this._options.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderingCanvas().height*this._options.mainTextureRatio,this._mainTextureDesiredSize.width=e.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize),this._mainTextureDesiredSize.height=e.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize))},i.prototype.defaultStencilReference=function(e){e.getScene().getEngine().setStencilFunctionReference(i.normalMeshStencilReference)},i.prototype.disposeTextureAndPostProcesses=function(){this._blurTexture.dispose(),this._mainTexture.dispose(),this._downSamplePostprocess.dispose(),this._horizontalBlurPostprocess.dispose(),this._verticalBlurPostprocess.dispose()},i.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.disposeTextureAndPostProcesses();for(var i in this._meshes){var r=this._meshes[i];r&&r.mesh&&(r.mesh.onBeforeRenderObservable.remove(r.observerHighlight),r.mesh.onAfterRenderObservable.remove(r.observerDefault))}this._meshes=null;for(var i in this._excludedMeshes){var r=this._excludedMeshes[i];r&&(r.mesh.onBeforeRenderObservable.remove(r.beforeRender),r.mesh.onAfterRenderObservable.remove(r.afterRender))}this._excludedMeshes=null;var n=this._scene.highlightLayers.indexOf(this,0);n>-1&&this._scene.highlightLayers.splice(n,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeBlurObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},i.neutralColor=new e.Color4(0,0,0,0),i.glowingMeshStencilReference=2,i.normalMeshStencilReference=1,i})();e.HighlightLayer=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e.TransformCoordinatesToRefSIMD=function(t,i,r){e.TransformCoordinatesFromFloatsToRefSIMD(t.x,t.y,t.z,i,r)},e.TransformCoordinatesFromFloatsToRefSIMD=function(e,t,i,r,n){var o=r.m,s=SIMD.Float32x4.load(o,0),a=SIMD.Float32x4.load(o,4),h=SIMD.Float32x4.load(o,8),c=SIMD.Float32x4.load(o,12),l=SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(e),s),SIMD.Float32x4.mul(SIMD.Float32x4.splat(t),a)),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(i),h),c));l=SIMD.Float32x4.div(l,SIMD.Float32x4.swizzle(l,3,3,3,3)),n.x=SIMD.Float32x4.extractLane(l,0),n.y=SIMD.Float32x4.extractLane(l,1),n.z=SIMD.Float32x4.extractLane(l,2)},e})(),i=(function(){function e(){}return e.prototype.multiplyToArraySIMD=function(e,t,i){for(var r=this.m,n=e.m,o=SIMD.Float32x4.load(n,0),s=SIMD.Float32x4.load(n,4),a=SIMD.Float32x4.load(n,8),h=SIMD.Float32x4.load(n,12),c=0;c<16;c+=4)SIMD.Float32x4.store(t,c+i,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c]),o),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c+1]),s),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c+2]),a),SIMD.Float32x4.mul(SIMD.Float32x4.splat(r[c+3]),h)))));return this},e.prototype.invertToRefSIMD=function(e){var t=this.m,i=e.m,r=SIMD.Float32x4.load(t,0),n=SIMD.Float32x4.load(t,4),o=SIMD.Float32x4.load(t,8),s=SIMD.Float32x4.load(t,12),a=SIMD.Float32x4.shuffle(r,n,0,1,4,5),h=SIMD.Float32x4.shuffle(o,s,0,1,4,5),c=SIMD.Float32x4.shuffle(a,h,0,2,4,6);h=SIMD.Float32x4.shuffle(h,a,1,3,5,7),a=SIMD.Float32x4.shuffle(r,n,2,3,6,7);var l=SIMD.Float32x4.shuffle(o,s,2,3,6,7),u=SIMD.Float32x4.shuffle(a,l,0,2,4,6);l=SIMD.Float32x4.shuffle(l,a,1,3,5,7),a=SIMD.Float32x4.mul(u,l),a=SIMD.Float32x4.swizzle(a,1,0,3,2);var d=SIMD.Float32x4.mul(h,a),f=SIMD.Float32x4.mul(c,a);a=SIMD.Float32x4.swizzle(a,2,3,0,1),d=SIMD.Float32x4.sub(SIMD.Float32x4.mul(h,a),d),f=SIMD.Float32x4.sub(SIMD.Float32x4.mul(c,a),f),f=SIMD.Float32x4.swizzle(f,2,3,0,1),a=SIMD.Float32x4.mul(h,u),a=SIMD.Float32x4.swizzle(a,1,0,3,2),d=SIMD.Float32x4.add(SIMD.Float32x4.mul(l,a),d);var p=SIMD.Float32x4.mul(c,a);a=SIMD.Float32x4.swizzle(a,2,3,0,1),d=SIMD.Float32x4.sub(d,SIMD.Float32x4.mul(l,a)),p=SIMD.Float32x4.sub(SIMD.Float32x4.mul(c,a),p),p=SIMD.Float32x4.swizzle(p,2,3,0,1),a=SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(h,2,3,0,1),l),a=SIMD.Float32x4.swizzle(a,1,0,3,2),u=SIMD.Float32x4.swizzle(u,2,3,0,1),d=SIMD.Float32x4.add(SIMD.Float32x4.mul(u,a),d);var _=SIMD.Float32x4.mul(c,a);a=SIMD.Float32x4.swizzle(a,2,3,0,1),d=SIMD.Float32x4.sub(d,SIMD.Float32x4.mul(u,a)),_=SIMD.Float32x4.sub(SIMD.Float32x4.mul(c,a),_),_=SIMD.Float32x4.swizzle(_,2,3,0,1),a=SIMD.Float32x4.mul(c,h),a=SIMD.Float32x4.swizzle(a,1,0,3,2),_=SIMD.Float32x4.add(SIMD.Float32x4.mul(l,a),_),p=SIMD.Float32x4.sub(SIMD.Float32x4.mul(u,a),p),a=SIMD.Float32x4.swizzle(a,2,3,0,1),_=SIMD.Float32x4.sub(SIMD.Float32x4.mul(l,a),_),p=SIMD.Float32x4.sub(p,SIMD.Float32x4.mul(u,a)),a=SIMD.Float32x4.mul(c,l),a=SIMD.Float32x4.swizzle(a,1,0,3,2),f=SIMD.Float32x4.sub(f,SIMD.Float32x4.mul(u,a)),_=SIMD.Float32x4.add(SIMD.Float32x4.mul(h,a),_),a=SIMD.Float32x4.swizzle(a,2,3,0,1),f=SIMD.Float32x4.add(SIMD.Float32x4.mul(u,a),f),_=SIMD.Float32x4.sub(_,SIMD.Float32x4.mul(h,a)),a=SIMD.Float32x4.mul(c,u),a=SIMD.Float32x4.swizzle(a,1,0,3,2),f=SIMD.Float32x4.add(SIMD.Float32x4.mul(l,a),f),p=SIMD.Float32x4.sub(p,SIMD.Float32x4.mul(h,a)),a=SIMD.Float32x4.swizzle(a,2,3,0,1),f=SIMD.Float32x4.sub(f,SIMD.Float32x4.mul(l,a)),p=SIMD.Float32x4.add(SIMD.Float32x4.mul(h,a),p);var m=SIMD.Float32x4.mul(c,d);return m=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(m,2,3,0,1),m),m=SIMD.Float32x4.add(SIMD.Float32x4.swizzle(m,1,0,3,2),m),a=SIMD.Float32x4.reciprocalApproximation(m),m=SIMD.Float32x4.sub(SIMD.Float32x4.add(a,a),SIMD.Float32x4.mul(m,SIMD.Float32x4.mul(a,a))),m=SIMD.Float32x4.swizzle(m,0,0,0,0),SIMD.Float32x4.store(i,0,SIMD.Float32x4.mul(m,d)),SIMD.Float32x4.store(i,4,SIMD.Float32x4.mul(m,f)),SIMD.Float32x4.store(i,8,_=SIMD.Float32x4.mul(m,_)),SIMD.Float32x4.store(i,12,SIMD.Float32x4.mul(m,p)),this},e.LookAtLHToRefSIMD=function(e,t,i,r){var n=r.m,o=SIMD.Float32x4(t.x,t.y,t.z,0),s=SIMD.Float32x4(e.x,e.y,e.z,0),a=SIMD.Float32x4(i.x,i.y,i.z,0),h=SIMD.Float32x4.sub(o,s),c=SIMD.Float32x4.mul(h,h);c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),h=SIMD.Float32x4.mul(h,SIMD.Float32x4.reciprocalSqrtApproximation(c)),c=SIMD.Float32x4.mul(a,a),c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),a=SIMD.Float32x4.mul(a,SIMD.Float32x4.reciprocalSqrtApproximation(c));var l=SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(h,1,2,0,3),SIMD.Float32x4.swizzle(a,2,0,1,3)),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(h,2,0,1,3),SIMD.Float32x4.swizzle(a,1,2,0,3)));c=SIMD.Float32x4.mul(l,l),c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),l=SIMD.Float32x4.mul(l,SIMD.Float32x4.reciprocalSqrtApproximation(c));var u=SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(l,1,2,0,3),SIMD.Float32x4.swizzle(h,2,0,1,3)),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(l,2,0,1,3),SIMD.Float32x4.swizzle(h,1,2,0,3)));c=SIMD.Float32x4.mul(l,l),c=SIMD.Float32x4.add(c,SIMD.Float32x4.add(SIMD.Float32x4.swizzle(c,1,2,0,3),SIMD.Float32x4.swizzle(c,2,0,1,3))),l=SIMD.Float32x4.mul(l,SIMD.Float32x4.reciprocalSqrtApproximation(c));var d=SIMD.Float32x4.splat(0);l=SIMD.Float32x4.neg(l);var f=SIMD.Float32x4.shuffle(l,u,0,1,4,5),p=SIMD.Float32x4.shuffle(h,d,0,1,4,5),_=SIMD.Float32x4.shuffle(f,p,0,2,4,6),m=SIMD.Float32x4.shuffle(f,p,1,3,5,7),g=SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(l,u,2,3,6,7),SIMD.Float32x4.shuffle(h,d,2,3,6,7),0,2,4,6),v=SIMD.Float32x4(0,0,0,1),y=SIMD.Float32x4(1,0,0,0);SIMD.Float32x4.store(n,0,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v))))),y=SIMD.Float32x4(0,1,0,0),SIMD.Float32x4.store(n,4,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v))))),y=SIMD.Float32x4(0,0,1,0),SIMD.Float32x4.store(n,8,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v))))),y=SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(s),3,1),SIMD.Float32x4.store(n,12,SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,0,0,0,0),_),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,1,1,1,1),m),SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,2,2,2,2),g),SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(y,3,3,3,3),v)))))},e})(),r=e.Matrix.prototype.multiplyToArray,n=e.Matrix.prototype.invertToRef,o=e.Matrix.LookAtLHToRef,s=e.Vector3.TransformCoordinatesToRef,a=e.Vector3.TransformCoordinatesFromFloatsToRef,h=(function(){function h(){}return Object.defineProperty(h,"IsEnabled",{get:function(){return h._isEnabled},enumerable:!0,configurable:!0}),h.DisableSIMD=function(){e.Matrix.prototype.multiplyToArray=r,e.Matrix.prototype.invertToRef=n,e.Matrix.LookAtLHToRef=o,e.Vector3.TransformCoordinatesToRef=s,e.Vector3.TransformCoordinatesFromFloatsToRef=a,h._isEnabled=!1},h.EnableSIMD=function(){void 0!==self.SIMD&&(self.Math.fround||(self.Math.fround=(function(e){return function(t){return e[0]=t,e[0]}})(new Float32Array(1))),self.Math.imul||(self.Math.imul=function(e,t){var i=e>>>16&65535,r=65535&e,n=t>>>16&65535,o=65535&t;return r*o+(i*o+r*n<<16>>>0)|0}),e.Matrix.prototype.multiplyToArray=i.prototype.multiplyToArraySIMD,e.Matrix.prototype.invertToRef=i.prototype.invertToRefSIMD,e.Matrix.LookAtLHToRef=i.LookAtLHToRefSIMD,e.Vector3.TransformCoordinatesToRef=t.TransformCoordinatesToRefSIMD,e.Vector3.TransformCoordinatesFromFloatsToRef=t.TransformCoordinatesFromFloatsToRefSIMD,h._isEnabled=!0)},h._isEnabled=!1,h})();e.SIMDHelper=h})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this._pos=i,this._size=r,this._root=e,this._parent=t,this._contentSize=null,this._bottomNode=null,this._leftNode=null,this._initialSize=null,this._rightNode=null}return Object.defineProperty(t.prototype,"pos",{get:function(){return this._pos},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"contentSize",{get:function(){return this._contentSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"UVs",{get:function(){return this.getUVsForCustomSize(this._root._size)},enumerable:!0,configurable:!0}),t.prototype.getUVsForCustomSize=function(t){var i=this._root._size.width,r=this._root._size.height,n=new e.Vector2(this._pos.x/i,this._pos.y/r),o=new e.Vector2((this._pos.x+t.width-1)/i,(this._pos.y+t.height-1)/r),s=new Array;return s.push(n),s.push(new e.Vector2(o.x,n.y)),s.push(o),s.push(new e.Vector2(n.x,o.y)),s},t.prototype.freeContent=function(){this.contentSize&&(this._contentSize=null,this.attemptDefrag())},Object.defineProperty(t.prototype,"isUsed",{get:function(){return null!=this._contentSize||null!=this._leftNode},enumerable:!0,configurable:!0}),t.prototype.findAndSplitNode=function(e){var t=this.findNode(e);return t?(t.splitNode(e),t):null},t.prototype.findNode=function(e){var t=null;if(this.isUsed)this._leftNode&&(t=this._leftNode.findNode(e)),!t&&this._rightNode&&(t=this._rightNode.findNode(e)),!t&&this._bottomNode&&(t=this._bottomNode.findNode(e));else if(this._initialSize){if(!(e.width<=this._initialSize.width&&e.height<=this._initialSize.height))return null;t=this}else e.width<=this._size.width&&e.height<=this._size.height&&(t=this);return t},t.prototype.splitNode=function(i){return!this._contentSize&&this._initialSize?(this._contentSize=i.clone(),this._leftNode=new t(this._root,this,new e.Vector2(this._pos.x,this._pos.y),new e.Size(this._initialSize.width,this._initialSize.height)),this._leftNode.splitNode(i)):(this._contentSize=i.clone(),this._initialSize=i.clone(),i.width!==this._size.width&&(this._rightNode=new t(this._root,this,new e.Vector2(this._pos.x+i.width,this._pos.y),new e.Size(this._size.width-i.width,i.height))),i.height!==this._size.height&&(this._bottomNode=new t(this._root,this,new e.Vector2(this._pos.x,this._pos.y+i.height),new e.Size(this._size.width,this._size.height-i.height))),this)},t.prototype.attemptDefrag=function(){!this.isUsed&&this.isRecursiveFree&&(this.clearNode(),this._parent&&this._parent.attemptDefrag())},t.prototype.clearNode=function(){this._initialSize=null,this._rightNode=null,this._bottomNode=null},Object.defineProperty(t.prototype,"isRecursiveFree",{get:function(){return!this.contentSize&&(!this._leftNode||this._leftNode.isRecursiveFree)&&(!this._rightNode||this._rightNode.isRecursiveFree)&&(!this._bottomNode||this._bottomNode.isRecursiveFree)},enumerable:!0,configurable:!0}),t.prototype.evalFreeSize=function(e){var t=0;return this.isUsed||(t=this._initialSize?this._initialSize.surface:this._size.surface),this._rightNode&&(t+=this._rightNode.evalFreeSize(0)),this._bottomNode&&(t+=this._bottomNode.evalFreeSize(0)),t+e},t})();e.PackedRect=t;var i=(function(t){function i(i){t.call(this,null,null,e.Vector2.Zero(),i),this._root=this}return __extends(i,t),i.prototype.addRect=function(e){var t=this.findAndSplitNode(e);return t},Object.defineProperty(i.prototype,"freeSpace",{get:function(){var e=0;return e=this.evalFreeSize(e),e/(this._size.width*this._size.height)},enumerable:!0,configurable:!0}),i})(t);e.RectPackingMap=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e})();e.DynamicFloatArrayElementInfo=t;var i=(function(){function e(e,i){this.compareValueOffset=null,this.sortingAscending=!0,this._stride=e,this.buffer=new Float32Array(e*i),this._lastUsed=0,this._firstFree=0,this._allEntries=new Array(i),this._freeEntries=new Array(i);for(var r=0;r<i;r++){var n=new t;n.offset=r*e,this._allEntries[r]=n,this._freeEntries[i-r-1]=n}}return e.prototype.allocElement=function(){0===this._freeEntries.length&&this._growBuffer();var e=this._freeEntries.pop();return this._lastUsed=Math.max(e.offset,this._lastUsed),e.offset===this._firstFree&&(this._freeEntries.length>0?this._firstFree=this._freeEntries[this._freeEntries.length-1].offset:this._firstFree+=this._stride),e},e.prototype.freeElement=function(e){this._firstFree=Math.min(e.offset,this._firstFree),this._freeEntries.push(e)},e.prototype.pack=function(){if(0===this._freeEntries.length)return this.buffer;if(this._lastUsed<this._firstFree){var e=this.buffer.subarray(0,this._lastUsed+this._stride);return e}var i=this._stride,r=new t;r.offset=this.totalElementCount*i,this._freeEntries.push(r);for(var n=this._freeEntries.sort((function(e,t){return e.offset-t.offset})),o=this._allEntries.sort((function(e,t){return e.offset-t.offset})),s=n[0].offset,a=1,h=(this.usedElementCount+1)*i,c=n[0].offset,l=1;l<n.length&&!(s>=h);l++){var u=n[l],d=u.offset,f=d-c;if(f!==i){for(var p=f/i-1,_=d-i,m=Math.min(a,p),g=0;g<m;g++){var v=s/i,y=_/i,x=o[y];this._moveElement(x,s);var b=o[v];b.offset=_,o[v]=x,o[y]=b,_-=i,s+=i}a<=p?(s=_+i,a=1+m):a=(d-s)/i+1,c=d}else++a,c=d}var A=this.buffer.subarray(0,s);return this._lastUsed=s-i,this._firstFree=s,n.pop(),this._freeEntries=n.sort((function(e,t){return t.offset-e.offset})),this._allEntries=o,A},e.prototype._moveElement=function(e,t){for(var i=0;i<this._stride;i++)this.buffer[t+i]=this.buffer[e.offset+i];e.offset=t},e.prototype._growBuffer=function(){var e=Math.floor(1.5*this.totalElementCount),i=new Float32Array(e*this._stride);i.set(this.buffer);for(var r=this.totalElementCount,n=e-this.totalElementCount,o=0;o<n;o++){var s=new t;s.offset=(r+o)*this.stride,this._allEntries.push(s),this._freeEntries[n-o-1]=s}this._firstFree=r*this.stride,this.buffer=i},Object.defineProperty(e.prototype,"totalElementCount",{get:function(){return this._allEntries.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"freeElementCount",{get:function(){return this._freeEntries.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"usedElementCount",{get:function(){return this._allEntries.length-this._freeEntries.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stride",{get:function(){return this._stride},enumerable:!0,configurable:!0}),e.prototype.sort=function(){var e=this;if(!this.compareValueOffset)throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");var t=this.usedElementCount;if(!this._sortTable||this._sortTable.length<t){var i=Math.min(this.totalElementCount,2*t);this._sortTable=new Array(i)}this._sortedTable&&this._sortedTable.length===t||(this._sortedTable=new Array(t)),this.pack();for(var n=0,o=this.stride,s=0;s<t;s++,n+=o){var a=this._sortTable[s];a||(a=new r,this._sortTable[s]=a),a.compareData=this.buffer[n+this.compareValueOffset],a.offset=n,a.swapedOffset=null,this._sortedTable[s]=a}this.sortingAscending?this._sortedTable.sort((function(e,t){return e.compareData-t.compareData})):this._sortedTable.sort((function(e,t){return t.compareData-e.compareData}));for(var h=function(t,i){for(var r=0;r<o;r++){var n=e.buffer[i+r];e.buffer[i+r]=e.buffer[t+r],e.buffer[t+r]=n}},s=0;s<t;s++){var c=this._sortedTable[s],l=this._sortTable[s],u=c.offset;if(c.swapedOffset){for(var d=c;d.swapedOffset;)d=this._sortTable[d.swapedOffset/o];u=d.offset}l.swapedOffset=u,u!==l.offset&&h(u,l.offset),this._allEntries[c.offset/o].offset=l.offset}return this._allEntries.sort((function(e,t){return e.offset-t.offset})),!0},e})();e.DynamicFloatArray=i;var r=(function(){function e(){this.compareData=this.offset=this.swapedOffset=null}return e})()})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){}return e})();e.CharInfo=t;var i=(function(i){function r(t,r,n,o,s,a,h){if(void 0===o&&(o=200),void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=!1),void 0===h&&(h=!1),i.call(this,null,n,!0,!1,s),this._charInfos={},this._curCharCount=0,this._lastUpdateCharCount=-1,this._usedCounter=1,this.name=t,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._sdfScale=8,this._signedDistanceField=h,this._superSample=!1,a||h){var c=this.getSuperSampleFont(r);c&&(this._superSample=!0,r=c)}this._canvas=document.createElement("canvas"),this._context=this._canvas.getContext("2d"),this._context.font=r,this._context.fillStyle="white",
this._context.textBaseline="top",this._cachedFontId=null;var l=this.getFontHeight(r);this._lineHeightSuper=l.height+4,this._lineHeight=this._superSample?Math.ceil(this._lineHeightSuper/2):this._lineHeightSuper,this._offset=l.offset-1,this._xMargin=1+Math.ceil(this._lineHeightSuper/15),this._yMargin=this._xMargin;var u=this._context.measureText("W").width;this._spaceWidthSuper=this._context.measureText(" ").width,this._spaceWidth=this._superSample?this._spaceWidthSuper/2:this._spaceWidthSuper;var d=(this._lineHeightSuper+this._yMargin)*(u+this._xMargin)*o,f=Math.sqrt(d),p=Math.pow(2,Math.ceil(Math.log(f)/Math.log(2)));this._texture=n.getEngine().createDynamicTexture(p,p,!1,s);var _=this.getSize();if(this.hasAlpha=this._signedDistanceField===!1,this._canvas=document.createElement("canvas"),this._canvas.width=_.width,this._canvas.height=_.height,this._context=this._canvas.getContext("2d"),this._context.textBaseline="top",this._context.font=r,this._context.fillStyle="white",this._context.imageSmoothingEnabled=!1,this._context.clearRect(0,0,_.width,_.height),this._signedDistanceField){var m=document.createElement("canvas"),g=this._sdfScale;m.width=u*g,m.height=this._lineHeightSuper*g;var v=m.getContext("2d");v.scale(g,g),v.textBaseline="top",v.font=r,v.fillStyle="white",v.imageSmoothingEnabled=!1,this._sdfCanvas=m,this._sdfContext=v}this._currentFreePosition=e.Vector2.Zero();for(var y=32;y<127;y++){var x=String.fromCharCode(y);this.getChar(x)}this.update()}return __extends(r,i),Object.defineProperty(r.prototype,"isSuperSampled",{get:function(){return this._superSample},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"isSignedDistanceField",{get:function(){return this._signedDistanceField},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"spaceWidth",{get:function(){return this._spaceWidth},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"lineHeight",{get:function(){return this._lineHeight},enumerable:!0,configurable:!0}),r.GetCachedFontTexture=function(t,i,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var s=t;s.__fontTextureCache__||(s.__fontTextureCache__=new e.StringDictionary);var a=s.__fontTextureCache__,h=i.toLocaleLowerCase()+(n?"_+SS":"_-SS")+(o?"_+SDF":"_-SDF"),c=a.get(h);return c?(++c._usedCounter,c):(c=new r(null,i,t,n?100:200,e.Texture.BILINEAR_SAMPLINGMODE,n,o),c._cachedFontId=h,a.add(h,c),c)},r.ReleaseCachedFontTexture=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n=e,o=n.__fontTextureCache__;if(o){var s=t.toLocaleLowerCase()+(i?"_+SS":"_-SS")+(r?"_+SDF":"_-SDF"),a=o.get(s);0===--a._usedCounter&&(o.remove(s),a.dispose())}},r.prototype.getChar=function(i){if(1!==i.length)return null;var r=this._charInfos[i];if(r)return r;r=new t;var n=this._context.measureText(i),o=this.getSize(),s=Math.round(n.width);if(this._currentFreePosition.x+s+this._xMargin>o.width&&(this._currentFreePosition.x=0,this._currentFreePosition.y+=this._lineHeightSuper+this._yMargin,this._currentFreePosition.y>o.height))return this.getChar("!");if(this._signedDistanceField){this._sdfContext.clearRect(0,0,this._sdfCanvas.width,this._sdfCanvas.height),this._sdfContext.fillText(i,0,-this._offset);var a=this._sdfContext.getImageData(0,0,s*this._sdfScale,this._sdfCanvas.height),h=this._computeSDFChar(a);this._context.putImageData(h,this._currentFreePosition.x,this._currentFreePosition.y)}else this._context.fillText(i,this._currentFreePosition.x,this._currentFreePosition.y-this._offset);if(r.topLeftUV=new e.Vector2(this._currentFreePosition.x/o.width,this._currentFreePosition.y/o.height),r.bottomRightUV=new e.Vector2((this._currentFreePosition.x+s)/o.width,r.topLeftUV.y+(this._lineHeightSuper+2)/o.height),this._signedDistanceField){var c=1/o.width;r.topLeftUV.addInPlace(new e.Vector2(c,c)),r.bottomRightUV.addInPlace(new e.Vector2(c,c))}return r.charWidth=this._superSample?s/2:s,this._charInfos[i]=r,this._curCharCount++,this._currentFreePosition.x+=s+this._xMargin,r},r.prototype._computeSDFChar=function(e){for(var t=this._sdfScale,i=e.width,r=e.height,n=i/t,o=r/t,s=0,a=0,h=t,c=h-1,l=function(n,o,h,c,l){var u=n*t,d=o*t;if(u+h<0||u+h>=i||d+c<0||d+c>=r)return!0;var f=e.data[4*((d+c)*i+(u+h))],p=f>0===l;return p||(s=h,a=c),p},u=function(e,t,i){if(l(e,t,0,c,i)&&l(e,t,0,-c,i)&&l(e,t,-c,0,i)&&l(e,t,c,0,i))return 0;for(var r=1;r<=h;r++){if(!(l(e,t,0,r,i)&&l(e,t,0,-r,i)&&l(e,t,-r,0,i)&&l(e,t,r,0,i)))return r*r;for(var n=1;n<=r;n++)if(!(l(e,t,-n,r,i)&&l(e,t,n,r,i)&&l(e,t,r,-n,i)&&l(e,t,r,n,i)&&l(e,t,-n,-r,i)&&l(e,t,n,-r,i)&&l(e,t,-r,-n,i)&&l(e,t,-r,n,i))){var o=r*r+n*n,u=1;return l(e,t,s-1,a,i)||(o+=(s-1)*(s-1)+a*a,++u),l(e,t,s+1,a,i)||(o+=(s+1)*(s+1)+a*a,++u),l(e,t,s,a-1,i)||(o+=s*s+(a-1)*(a-1),++u),l(e,t,s,a+1,i)||(o+=s*s+(a+1)*(a+1),++u),l(e,t,s-1,a-1,i)||(o+=(s-1)*(s-1)+(a-1)*(a-1),++u),l(e,t,s+1,a+1,i)||(o+=(s+1)*(s+1)+(a+1)*(a+1),++u),l(e,t,s+1,a-1,i)||(o+=(s+1)*(s+1)+(a-1)*(a-1),++u),l(e,t,s-1,a+1,i)||(o+=(s-1)*(s-1)+(a+1)*(a+1),++u),o/u}}return 0},d=new Array(n*o),f=0;f<o;f++)for(var p=0;p<n;p++){var _=l(p,f,0,0,!0),m=u(p,f,_);0===m&&(m=h*h*2),d[f*n+p]=_?m:-m}for(var g=this._context.createImageData(n,o),v=n*o,y=0;y<v;y++){var m=d[y],x=m<0?-1:1;m=Math.sqrt(Math.abs(m))*x,m*=127.5/h,m+=127.5,m<0?m=0:m>255&&(m=255),m+=.5,g.data[4*y+0]=m,g.data[4*y+1]=m,g.data[4*y+2]=m,g.data[4*y+3]=255}return g},r.prototype.measureText=function(t,i){void 0===i&&(i=4);for(var r=0,n=0,o=1,s=0,a=0,h=t;a<h.length;a++){var c=h[a];if("\n"!==c)if("\t"!==c)c<" "||(n+=this.getChar(c).charWidth,++s);else{var l=s+i;l-=l%i,n+=(l-s)*this.spaceWidth,s=l}else r=Math.max(r,n),s=0,n=0,++o}return r=Math.max(r,n),new e.Size(r,o*this.lineHeight)},r.prototype.getSuperSampleFont=function(e){var t=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/,i=e.toLocaleLowerCase().match(t);if(null==i)return null;var r=parseInt(i[4]);i[4]=(2*r).toString()+(i[4].match(/\D+/)||[]).pop();for(var n="",o=1;o<i.length;o++)null!=i[o]&&(n+=i[o]+" ");return n},r.prototype.getFontHeight=function(e){var t=document.createElement("canvas"),i=t.getContext("2d");i.fillRect(0,0,t.width,t.height),i.textBaseline="top",i.fillStyle="white",i.font=e,i.fillText("jH|",0,0);for(var r=i.getImageData(0,0,t.width,t.height).data,n=-1,o=-1,s=0;s<t.height;s++)for(var a=0;a<t.width;a++){var h=4*(s*t.width+a);{if(0!==r[h]){n===-1&&(n=s);break}if(a===t.width-1&&n!==-1){o=s,s=t.height;break}}}return{height:o-n+1,offset:n-1}},Object.defineProperty(r.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),r.prototype.getContext=function(){return this._context},r.prototype.update=function(){this._lastUpdateCharCount<this._curCharCount&&(this.getScene().getEngine().updateDynamicTexture(this._texture,this._canvas,!1,!0),this._lastUpdateCharCount=this._curCharCount)},r.prototype.clone=function(){return null},r.prototype.incCachedFontTextureCounter=function(){++this._usedCounter},r.prototype.decCachedFontTextureCounter=function(){var e=this.getScene(),t=e.__fontTextureCache__;t&&0===--this._usedCounter&&(t.remove(this._cachedFontId),this.dispose())},r})(e.Texture);e.FontTexture=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=!1),t.call(this,null,r,!s,!1,o),this.name=i,this._size=n,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._rectPackingMap=new e.RectPackingMap(new e.Size(n.width,n.height)),this._texture=r.getEngine().createRenderTargetTexture(n,{generateMipMaps:!this.noMipmap,type:e.Engine.TEXTURETYPE_UNSIGNED_INT})}return __extends(i,t),i.prototype.allocateRect=function(e){return this._rectPackingMap.addRect(e)},i.prototype.freeRect=function(e){e&&e.freeContent()},Object.defineProperty(i.prototype,"freeSpace",{get:function(){return this._rectPackingMap.freeSpace},enumerable:!0,configurable:!0}),i.prototype.bindTextureForRect=function(e,t){return this.bindTextureForPosSize(e.pos,e.contentSize,t)},i.prototype.bindTextureForPosSize=function(t,i,r){var n=this.getScene().getEngine();n.bindFramebuffer(this._texture),this._replacedViewport=n.setDirectViewport(t.x,t.y,i.width,i.height),r&&n.scissorClear(t.x,t.y,i.width,i.height,new e.Color4(0,0,0,0))},i.prototype.unbindTexture=function(t){t&&e.Tools.DumpFramebuffer(this._size.width,this._size.height,this.getScene().getEngine());var i=this.getScene().getEngine();this._replacedViewport&&(i.setViewport(this._replacedViewport),this._replacedViewport=null),i.unBindFramebuffer(this._texture)},Object.defineProperty(i.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),i.prototype.clone=function(){return null},i})(e.Texture);e.MapTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){t.call(this,i,r),this._textures={},this._textureArrays={},this._floats={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._matrices3x3={},this._matrices2x2={},this._vectors3Arrays={},this._cachedWorldViewMatrix=new e.Matrix,this._shaderPath=n,o.needAlphaBlending=o.needAlphaBlending||!1,o.needAlphaTesting=o.needAlphaTesting||!1,o.attributes=o.attributes||["position","normal","uv"],o.uniforms=o.uniforms||["worldViewProjection"],o.samplers=o.samplers||[],o.defines=o.defines||[],this._options=o}return __extends(i,t),i.prototype.needAlphaBlending=function(){return this._options.needAlphaBlending},i.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting},i.prototype._checkUniform=function(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)},i.prototype.setTexture=function(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this},i.prototype.setTextureArray=function(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this},i.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},i.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},i.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},i.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},i.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},i.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},i.prototype.setVector4=function(e,t){return this._checkUniform(e),this._vectors4[e]=t,this},i.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},i.prototype.setMatrix3x3=function(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this},i.prototype.setMatrix2x2=function(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this},i.prototype.setArray3=function(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this},i.prototype._checkCache=function(e,t,i){return!t||(this._effect&&this._effect.defines.indexOf("#define INSTANCES")!==-1!==i,!1)},i.prototype.isReady=function(t,i){var r=this.getScene(),n=r.getEngine();if(!this.checkReadyOnEveryCall&&this._renderId===r.getRenderId()&&this._checkCache(r,t,i))return!0;var o=[],s=new e.EffectFallbacks;i&&o.push("#define INSTANCES");for(var a=0;a<this._options.defines.length;a++)o.push(this._options.defines[a]);t&&t.useBones&&t.computeBonesUsingShaders&&(o.push("#define NUM_BONE_INFLUENCERS "+t.numBoneInfluencers),o.push("#define BonesPerMesh "+(t.skeleton.bones.length+1)),s.addCPUSkinningFallback(0,t)),n.getAlphaTesting()&&o.push("#define ALPHATEST");var h=this._effect,c=o.join("\n");return this._effect=n.createEffect(this._shaderPath,this._options.attributes,this._options.uniforms,this._options.samplers,c,s,this.onCompiled,this.onError),!!this._effect.isReady()&&(h!==this._effect&&r.resetCachedMaterial(),this._renderId=r.getRenderId(),!0)},i.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._options.uniforms.indexOf("world")!==-1&&this._effect.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&this._effect.setMatrix("worldViewProjection",e.multiply(t.getTransformMatrix()))},i.prototype.bind=function(i,r){if(this.bindOnlyWorldMatrix(i),this.getScene().getCachedMaterial()!==this){this._options.uniforms.indexOf("view")!==-1&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),this._options.uniforms.indexOf("projection")!==-1&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),this._options.uniforms.indexOf("viewProjection")!==-1&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.MaterialHelper.BindBonesParameters(r,this._effect);var n;for(n in this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._textureArrays)this._effect.setTextureArray(n,this._textureArrays[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var o=this._colors4[n];this._effect.setFloat4(n,o.r,o.g,o.b,o.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._vectors4)this._effect.setVector4(n,this._vectors4[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);for(n in this._matrices3x3)this._effect.setMatrix3x3(n,this._matrices3x3[n]);for(n in this._matrices2x2)this._effect.setMatrix2x2(n,this._matrices2x2[n]);for(n in this._vectors3Arrays)this._effect.setArray3(n,this._vectors3Arrays[n])}t.prototype.bind.call(this,i,r)},i.prototype.clone=function(e){var t=new i(e,this.getScene(),this._shaderPath,this._options);return t},i.prototype.dispose=function(e,i){if(i){var r;for(r in this._textures)this._textures[r].dispose();for(r in this._textureArrays)for(var n=this._textureArrays[r],o=0;o<n.length;o++)n[o].dispose()}this._textures={},t.prototype.dispose.call(this,e,i)},i.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);t.customType="BABYLON.ShaderMaterial",t.options=this._options,t.shaderPath=this._shaderPath;var i;t.textures={};for(i in this._textures)t.textures[i]=this._textures[i].serialize();t.textureArrays={};for(i in this._textureArrays){t.textureArrays[i]=[];for(var r=this._textureArrays[i],n=0;n<r.length;n++)t.textureArrays[i].push(r[n].serialize())}t.floats={};for(i in this._floats)t.floats[i]=this._floats[i];t.floatArrays={};for(i in this._floatsArrays)t.floatArrays[i]=this._floatsArrays[i];t.colors3={};for(i in this._colors3)t.colors3[i]=this._colors3[i].asArray();t.colors4={};for(i in this._colors4)t.colors4[i]=this._colors4[i].asArray();t.vectors2={};for(i in this._vectors2)t.vectors2[i]=this._vectors2[i].asArray();t.vectors3={};for(i in this._vectors3)t.vectors3[i]=this._vectors3[i].asArray();t.vectors4={};for(i in this._vectors4)t.vectors4[i]=this._vectors4[i].asArray();t.matrices={};for(i in this._matrices)t.matrices[i]=this._matrices[i].asArray();t.matrices3x3={};for(i in this._matrices3x3)t.matrices3x3[i]=this._matrices3x3[i];t.matrices2x2={};for(i in this._matrices2x2)t.matrices2x2[i]=this._matrices2x2[i];t.vectors3Arrays={};for(i in this._vectors3Arrays)t.vectors3Arrays[i]=this._vectors3Arrays[i];return t},i.Parse=function(t,r,n){var o,s=e.SerializationHelper.Parse((function(){return new i(t.name,r,t.shaderPath,t.options)}),t,r,n);for(o in t.textures)s.setTexture(o,e.Texture.Parse(t.textures[o],r,n));for(o in t.textureArrays){for(var a=t.textureArrays[o],h=new Array,c=0;c<a.length;c++)h.push(e.Texture.Parse(a[c],r,n));s.setTextureArray(o,h)}for(o in t.floats)s.setFloat(o,t.floats[o]);for(o in t.floatsArrays)s.setFloats(o,t.floatsArrays[o]);for(o in t.colors3)s.setColor3(o,e.Color3.FromArray(t.colors3[o]));for(o in t.colors4)s.setColor4(o,e.Color4.FromArray(t.colors4[o]));for(o in t.vectors2)s.setVector2(o,e.Vector2.FromArray(t.vectors2[o]));for(o in t.vectors3)s.setVector3(o,e.Vector3.FromArray(t.vectors3[o]));for(o in t.vectors4)s.setVector4(o,e.Vector4.FromArray(t.vectors4[o]));for(o in t.matrices)s.setMatrix(o,e.Matrix.FromArray(t.matrices[o]));for(o in t.matrices3x3)s.setMatrix3x3(o,t.matrices3x3[o]);for(o in t.matrices2x2)s.setMatrix2x2(o,t.matrices2x2[o]);for(o in t.vectors3Arrays)s.setArray3(o,t.vectors3Arrays[o]);return s},i})(e.Material);e.ShaderMaterial=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){function i(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function r(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}var n=542327876,o=131072,s=512,a=4,h=64,c=131072,l=i("DXT1"),u=i("DXT3"),d=i("DXT5"),f=31,p=0,_=1,m=2,g=3,v=4,y=7,x=20,b=21,A=22,T=28,E=(function(){function t(){}return t.GetDDSInfo=function(e){var t=new Int32Array(e,0,f),i=1;return t[m]&o&&(i=Math.max(1,t[y])),{width:t[v],height:t[g],mipmapCount:i,isFourCC:(t[x]&a)===a,isRGB:(t[x]&h)===h,isLuminance:(t[x]&c)===c,isCube:(t[T]&s)===s}},t.GetRGBAArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),s=new Uint8Array(n),a=0,h=t-1;h>=0;h--)for(var c=0;c<e;c++){var l=i+4*(c+h*e);o[a+2]=s[l],o[a+1]=s[l+1],o[a]=s[l+2],o[a+3]=s[l+3],a+=4}return o},t.GetRGBArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),s=new Uint8Array(n),a=0,h=t-1;h>=0;h--)for(var c=0;c<e;c++){var l=i+3*(c+h*e);o[a+2]=s[l],o[a+1]=s[l+1],o[a]=s[l+2],a+=3}return o},t.GetLuminanceArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),s=new Uint8Array(n),a=0,h=t-1;h>=0;h--)for(var c=0;c<e;c++){var l=i+(c+h*e);o[a]=s[l],a++}return o},t.UploadDDSLevels=function(i,s,a,h,c,x){var T,E,P,S,M,C,R,O,D,I,L=new Int32Array(a,0,f);if(L[p]!=n)return void e.Tools.Error("Invalid magic number in DDS header");if(!h.isFourCC&&!h.isRGB&&!h.isLuminance)return void e.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");if(h.isFourCC)switch(T=L[b]){case l:E=8,P=s.COMPRESSED_RGBA_S3TC_DXT1_EXT;break;case u:E=16,P=s.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case d:E=16,P=s.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;default:return void console.error("Unsupported FourCC code:",r(T))}D=1,L[m]&o&&c!==!1&&(D=Math.max(1,L[y]));for(var w=L[A],B=0;B<x;B++){var F=1===x?i.TEXTURE_2D:i.TEXTURE_CUBE_MAP_POSITIVE_X+B;for(S=L[v],M=L[g],R=L[_]+4,I=0;I<D;++I){if(h.isRGB)24===w?(C=S*M*3,O=t.GetRGBArrayBuffer(S,M,R,C,a),i.texImage2D(F,I,i.RGB,S,M,0,i.RGB,i.UNSIGNED_BYTE,O)):(C=S*M*4,O=t.GetRGBAArrayBuffer(S,M,R,C,a),i.texImage2D(F,I,i.RGBA,S,M,0,i.RGBA,i.UNSIGNED_BYTE,O));else if(h.isLuminance){var V=i.getParameter(i.UNPACK_ALIGNMENT),N=S,U=Math.floor((S+V-1)/V)*V;C=U*(M-1)+N,O=t.GetLuminanceArrayBuffer(S,M,R,C,a),i.texImage2D(F,I,i.LUMINANCE,S,M,0,i.LUMINANCE,i.UNSIGNED_BYTE,O)}else C=Math.max(4,S)/4*Math.max(4,M)/4*E,O=new Uint8Array(a,R,C),i.compressedTexImage2D(F,I,P,S,M,0,O);R+=C,S*=.5,M*=.5,S=Math.max(1,S),M=Math.max(1,M)}}},t})();t.DDSTools=E})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){return void 0===t&&(t=!0),void 0===i&&(i=10),this._useDeltaForWorldStep=t,this.name="CannonJSPlugin",this._physicsMaterials=[],this._fixedTimeStep=1/60,this._currentCollisionGroup=2,this._minus90X=new e.Quaternion((-.7071067811865475),0,0,.7071067811865475),this._plus90X=new e.Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=e.Vector3.Zero(),this._tmpQuaternion=new e.Quaternion,this._tmpDeltaPosition=e.Vector3.Zero(),this._tmpDeltaRotation=new e.Quaternion,this._tmpUnityRotation=new e.Quaternion,this.isSupported()?(this.world=new CANNON.World,this.world.broadphase=new CANNON.NaiveBroadphase,void(this.world.solver.iterations=i)):void e.Tools.Error("CannonJS is not available. Please make sure you included the js file.")}return t.prototype.setGravity=function(e){this.world.gravity.copy(e)},t.prototype.setTimeStep=function(e){this._fixedTimeStep=e},t.prototype.executeStep=function(e,t){this.world.step(this._fixedTimeStep,this._useDeltaForWorldStep?1e3*e:0,3)},t.prototype.applyImpulse=function(e,t,i){var r=new CANNON.Vec3(i.x,i.y,i.z),n=new CANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},t.prototype.applyForce=function(e,t,i){var r=new CANNON.Vec3(i.x,i.y,i.z),n=new CANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},t.prototype.generatePhysicsBody=function(e){if(e.parent)return void(e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate()));if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s]);e.physicsBody=new CANNON.Body(n),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){e.physicsBody[t].copy(i[t])})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)},t.prototype._processChildMeshes=function(t){var i=this,r=t.object.getChildMeshes?t.object.getChildMeshes():[];if(r.length){var n=function(e,r){var o=r.getPhysicsImpostor();if(o){var s=o.parent;if(s!==t){var e=r.position;o.physicsBody&&(i.removePhysicsBody(o),o.physicsBody=null),o.parent=t,o.resetUpdateFlags(),t.physicsBody.addShape(i._createShape(o),new CANNON.Vec3(e.x,e.y,e.z)),t.physicsBody.mass+=o.getParam("mass")}}r.getChildMeshes().forEach(n.bind(i,r.position))};r.forEach(n.bind(this,e.Vector3.Zero()))}},t.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this.world.remove(e.physicsBody)},t.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s={pivotA:o.mainPivot?(new CANNON.Vec3).copy(o.mainPivot):null,pivotB:o.connectedPivot?(new CANNON.Vec3).copy(o.connectedPivot):null,axisA:o.mainAxis?(new CANNON.Vec3).copy(o.mainAxis):null,axisB:o.connectedAxis?(new CANNON.Vec3).copy(o.connectedAxis):null,maxForce:o.nativeParams.maxForce,collideConnected:!!o.collision};switch(t.joint.type){case e.PhysicsJoint.HingeJoint:case e.PhysicsJoint.Hinge2Joint:n=new CANNON.HingeConstraint(i,r,s);break;case e.PhysicsJoint.DistanceJoint:n=new CANNON.DistanceConstraint(i,r,o.maxDistance||2);break;case e.PhysicsJoint.SpringJoint:var a=o;n=new CANNON.Spring(i,r,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:s.pivotA,localAnchorB:s.pivotB});break;case e.PhysicsJoint.LockJoint:n=new CANNON.LockConstraint(i,r,s);break;case e.PhysicsJoint.PointToPointJoint:case e.PhysicsJoint.BallAndSocketJoint:default:n=new CANNON.PointToPointConstraint(i,s.pivotA,r,s.pivotA,s.maxForce)}n.collideConnected=!!o.collision,t.joint.physicsJoint=n,t.joint.type!==e.PhysicsJoint.SpringJoint?this.world.addConstraint(n):t.mainImpostor.registerAfterPhysicsStep((function(){n.applyForce()}))}},t.prototype.removeJoint=function(e){this.world.removeConstraint(e.joint.physicsJoint)},t.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r<this._physicsMaterials.length;r++)if(n=this._physicsMaterials[r],n.friction===t&&n.restitution===i)return n;var o=new CANNON.Material(e);return o.friction=t,o.restitution=i,this._physicsMaterials.push(o),o},t.prototype._checkWithEpsilon=function(t){return t<e.PhysicsEngine.Epsilon?e.PhysicsEngine.Epsilon:t},t.prototype._createShape=function(t){var i,r=t.object,n=t.getObjectExtendSize();switch(t.type){case e.PhysicsEngine.SphereImpostor:var o=n.x,s=n.y,a=n.z;i=new CANNON.Sphere(Math.max(this._checkWithEpsilon(o),this._checkWithEpsilon(s),this._checkWithEpsilon(a))/2);break;case e.PhysicsImpostor.CylinderImpostor:i=new CANNON.Cylinder(this._checkWithEpsilon(n.x)/2,this._checkWithEpsilon(n.x)/2,this._checkWithEpsilon(n.y),16);break;case e.PhysicsImpostor.BoxImpostor:var h=n.scale(.5);i=new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(h.x),this._checkWithEpsilon(h.y),this._checkWithEpsilon(h.z)));break;case e.PhysicsImpostor.PlaneImpostor:e.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),i=new CANNON.Plane;break;case e.PhysicsImpostor.MeshImpostor:var c=r.getVerticesData?r.getVerticesData(e.VertexBuffer.PositionKind):[],l=r.getIndices?r.getIndices():[];e.Tools.Warn("MeshImpostor only collides against spheres."),i=new CANNON.Trimesh(c,l);break;case e.PhysicsImpostor.HeightmapImpostor:i=this._createHeightmap(r);break;case e.PhysicsImpostor.ParticleImpostor:i=new CANNON.Particle}return i},t.prototype._createHeightmap=function(t,i){for(var r=t.getVerticesData(e.VertexBuffer.PositionKind),n=[],o=i||~~(Math.sqrt(r.length/3)-1),s=Math.min(t.getBoundingInfo().boundingBox.extendSize.x,t.getBoundingInfo().boundingBox.extendSize.z),a=2*s/o,h=t.getBoundingInfo().boundingBox.extendSize.y,c=0;c<r.length;c+=3){var l=Math.round(r[c+0]/a+o/2),u=Math.round((r[c+2]/a-o/2)*-1),d=r[c+1]+h;n[l]||(n[l]=[]),n[l][u]||(n[l][u]=d),n[l][u]=Math.max(d,n[l][u])}for(var l=0;l<=o;++l){if(!n[l]){for(var f=1;!n[(l+f)%o];)f++;n[l]=n[(l+f)%o].slice()}for(var u=0;u<=o;++u)if(!n[l][u]){for(var p,f=1;void 0===p;)p=n[l][(u+f++)%o];n[l][u]=p}}var _=new CANNON.Heightfield(n,{elementSize:a});return _.minY=h,_},t.prototype._updatePhysicsBodyTransformation=function(t){var i=t.object;i.computeWorldMatrix&&i.computeWorldMatrix(!0);var r=t.getObjectCenter();t.getObjectExtendSize();this._tmpDeltaPosition.copyFrom(i.position.subtract(r)),this._tmpPosition.copyFrom(r);var n=i.rotationQuaternion;if(t.type!==e.PhysicsImpostor.PlaneImpostor&&t.type!==e.PhysicsImpostor.HeightmapImpostor&&t.type!==e.PhysicsImpostor.CylinderImpostor||(n=n.multiply(this._minus90X),t.setDeltaRotation(this._plus90X)),t.type===e.PhysicsEngine.HeightmapImpostor){var o=i,s=o.rotationQuaternion;o.rotationQuaternion=this._tmpUnityRotation,o.computeWorldMatrix(!0);var a=r.clone(),h=o.getPivotMatrix()||e.Matrix.Translation(0,0,0);o.rotationQuaternion=s;var c=e.Matrix.Translation(o.getBoundingInfo().boundingBox.extendSize.x,0,-o.getBoundingInfo().boundingBox.extendSize.z);o.setPivotMatrix(c),o.computeWorldMatrix(!0);var l=o.getBoundingInfo().boundingBox.center.subtract(r).subtract(o.position).negate();this._tmpPosition.copyFromFloats(l.x,l.y-o.getBoundingInfo().boundingBox.extendSize.y,l.z),this._tmpDeltaPosition.copyFrom(o.getBoundingInfo().boundingBox.center.subtract(a)),this._tmpDeltaPosition.y+=o.getBoundingInfo().boundingBox.extendSize.y,o.setPivotMatrix(h),o.computeWorldMatrix(!0)}else t.type===e.PhysicsEngine.MeshImpostor&&(this._tmpDeltaPosition.copyFromFloats(0,0,0),this._tmpPosition.copyFrom(i.position));t.setDeltaPosition(this._tmpDeltaPosition),t.physicsBody.position.copy(this._tmpPosition),t.physicsBody.quaternion.copy(n)},t.prototype.setTransformationFromPhysicsBody=function(e){e.object.position.copyFrom(e.physicsBody.position),e.object.rotationQuaternion.copyFrom(e.physicsBody.quaternion)},t.prototype.setPhysicsBodyTransformation=function(e,t,i){e.physicsBody.position.copy(t),e.physicsBody.quaternion.copy(i)},t.prototype.isSupported=function(){return void 0!==window.CANNON},t.prototype.setLinearVelocity=function(e,t){e.physicsBody.velocity.copy(t)},t.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},t.prototype.getLinearVelocity=function(t){var i=t.physicsBody.velocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.setBodyMass=function(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()},t.prototype.sleepBody=function(e){e.physicsBody.sleep()},t.prototype.wakeUpBody=function(e){e.physicsBody.wakeUp()},t.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.distance=t},t.prototype.enableMotor=function(e,t){t||e.physicsJoint.enableMotor()},t.prototype.disableMotor=function(e,t){t||e.physicsJoint.disableMotor()},t.prototype.setMotor=function(e,t,i,r){r||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))},t.prototype.setLimit=function(e,t,i){e.physicsJoint.motorEquation.maxForce=t,e.physicsJoint.motorEquation.minForce=void 0===i?-t:i},t.prototype.dispose=function(){},t})();e.CannonJSPlugin=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=e.Vector3.Zero(),this.world=new OIMO.World(1/60,2,t,(!0)),this.world.worldscale(1),this.world.clear(),this.world.isNoStat=!0}return t.prototype.setGravity=function(e){this.world.gravity.copy(e)},t.prototype.setTimeStep=function(e){this.world.timeStep=e},t.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody}),o.onCollide({body:n.physicsBody}),r=r.next):r=r.next}else r=r.next},t.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.massInfo.mass;e.physicsBody.applyImpulse(i.scale(OIMO.INV_SCALE),t.scale(OIMO.INV_SCALE*r))},t.prototype.applyForce=function(t,i,r){e.Tools.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(t,i,r)},t.prototype.generatePhysicsBody=function(t){var i=this;if(t.parent)return void(t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate()));if(t.isBodyInitRequired()){var r={name:t.uniqueId,config:[t.getParam("mass")||1,t.getParam("friction"),t.getParam("restitution")],size:[],type:[],pos:[],rot:[],move:0!==t.getParam("mass"),world:this.world},n=[t],o=function(e){e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&(n.push(e.physicsImpostor),e.physicsImpostor._init())}))};o(t.object);var s=function(t){return Math.max(t,e.PhysicsEngine.Epsilon)};n.forEach((function(n){var o=n.object.rotationQuaternion,a=(new OIMO.Euler).setFromQuaternion({x:t.object.rotationQuaternion.x,y:t.object.rotationQuaternion.y,z:t.object.rotationQuaternion.z,s:t.object.rotationQuaternion.w}),h=n.getObjectExtendSize();if(n===t){var c=t.getObjectCenter();t.object.position.subtractToRef(c,i._tmpPositionVector),r.pos.push(c.x),r.pos.push(c.y),r.pos.push(c.z),r.rot.push(a.x/(OIMO.degtorad||OIMO.TO_RAD)),r.rot.push(a.y/(OIMO.degtorad||OIMO.TO_RAD)),r.rot.push(a.z/(OIMO.degtorad||OIMO.TO_RAD))}else r.pos.push(n.object.position.x),r.pos.push(n.object.position.y),r.pos.push(n.object.position.z),r.rot.push(0),r.rot.push(0),r.rot.push(0);switch(n.type){case e.PhysicsImpostor.ParticleImpostor:e.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");case e.PhysicsImpostor.SphereImpostor:var l=h.x,u=h.y,d=h.z,f=Math.max(s(l),s(u),s(d))/2;r.type.push("sphere"),r.size.push(f),r.size.push(f),r.size.push(f);break;case e.PhysicsImpostor.CylinderImpostor:var p=s(h.x)/2,_=s(h.y);r.type.push("cylinder"),r.size.push(p),r.size.push(_),r.size.push(_);break;case e.PhysicsImpostor.PlaneImpostor:case e.PhysicsImpostor.BoxImpostor:
default:var p=s(h.x),_=s(h.y),m=s(h.z);r.type.push("box"),r.size.push(p),r.size.push(_),r.size.push(m)}n.object.rotationQuaternion=o})),t.physicsBody=new OIMO.Body(r).body}else this._tmpPositionVector.copyFromFloats(0,0,0);t.setDeltaPosition(this._tmpPositionVector)},t.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},t.prototype.generateJoint=function(t){var i=t.mainImpostor.physicsBody,r=t.connectedImpostor.physicsBody;if(i&&r){var n,o=t.joint.jointData,s=o.nativeParams||{},a={body1:i,body2:r,axe1:s.axe1||(o.mainAxis?o.mainAxis.asArray():null),axe2:s.axe2||(o.connectedAxis?o.connectedAxis.asArray():null),pos1:s.pos1||(o.mainPivot?o.mainPivot.asArray():null),pos2:s.pos2||(o.connectedPivot?o.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||o.collision,spring:s.spring,world:this.world};switch(t.joint.type){case e.PhysicsJoint.BallAndSocketJoint:n="jointBall";break;case e.PhysicsJoint.SpringJoint:e.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var h=o;a.min=h.length||a.min,a.max=Math.max(a.min,a.max);case e.PhysicsJoint.DistanceJoint:n="jointDistance",a.max=o.maxDistance;break;case e.PhysicsJoint.PrismaticJoint:n="jointPrisme";break;case e.PhysicsJoint.SliderJoint:n="jointSlide";break;case e.PhysicsJoint.WheelJoint:n="jointWheel";break;case e.PhysicsJoint.HingeJoint:default:n="jointHinge"}a.type=n,t.joint.physicsJoint=new OIMO.Link(a).joint}},t.prototype.removeJoint=function(t){try{this.world.removeJoint(t.joint.physicsJoint)}catch(i){e.Tools.Warn(i)}},t.prototype.isSupported=function(){return void 0!==OIMO},t.prototype.setTransformationFromPhysicsBody=function(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){var t=this._getLastShape(e.physicsBody);e.object.position.x=t.position.x*OIMO.WORLD_SCALE,e.object.position.y=t.position.y*OIMO.WORLD_SCALE,e.object.position.z=t.position.z*OIMO.WORLD_SCALE}else e.object.position.copyFrom(e.physicsBody.getPosition());e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()),e.object.rotationQuaternion.normalize()}},t.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;r.position.init(t.x*OIMO.INV_SCALE,t.y*OIMO.INV_SCALE,t.z*OIMO.INV_SCALE),r.orientation.init(i.w,i.x,i.y,i.z),r.syncShapes(),r.awake()},t.prototype._getLastShape=function(e){for(var t=e.shapes;t.next;)t=t.next;return t},t.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.init(t.x,t.y,t.z)},t.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.init(t.x,t.y,t.z)},t.prototype.getLinearVelocity=function(t){var i=t.physicsBody.linearVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.getAngularVelocity=function(t){var i=t.physicsBody.angularVelocity;return i?new e.Vector3(i.x,i.y,i.z):null},t.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},t.prototype.sleepBody=function(e){e.physicsBody.sleep()},t.prototype.wakeUpBody=function(e){e.physicsBody.awake()},t.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},t.prototype.setMotor=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},t.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},t.prototype.dispose=function(){this.world.clear()},t})();e.OimoJSPlugin=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"displayPass",["passSampler"],["passSampler"],i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.DisplayPassPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i}return e})();e.SimplificationSettings=t;var i=(function(){function t(){this.running=!1,this._simplificationArray=[]}return t.prototype.addTask=function(e){this._simplificationArray.push(e)},t.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},t.prototype.runSimplification=function(t){var i=this;if(t.parallelProcessing)t.settings.forEach((function(e){var r=i.getSimplifier(t);r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,e.quality===t.settings[t.settings.length-1].quality&&t.successCallback&&t.successCallback(),i.executeNext()}))}));else{var r=this.getSimplifier(t),n=function(e,i){r.simplify(e,(function(r){t.mesh.addLODLevel(e.distance,r),r.isVisible=!0,i()}))};e.AsyncLoop.Run(t.settings.length,(function(e){n(t.settings[e.index],(function(){e.executeNext()}))}),(function(){t.successCallback&&t.successCallback(),i.executeNext()}))}},t.prototype.getSimplifier=function(e){switch(e.simplificationType){case r.QUADRATIC:default:return new h(e.mesh)}},t})();e.SimplificationQueue=i,(function(e){e[e.QUADRATIC=0]="QUADRATIC"})(e.SimplificationType||(e.SimplificationType={}));var r=e.SimplificationType,n=(function(){function e(e){this.vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}return e})();e.DecimationTriangle=n;var o=(function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new s,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e})();e.DecimationVertex=o;var s=(function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,s,a,h){var c=this.data[e]*this.data[n]*this.data[h]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[o]*this.data[s]-this.data[i]*this.data[n]*this.data[s]-this.data[e]*this.data[o]*this.data[a]-this.data[t]*this.data[r]*this.data[h];return c},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e})();e.QuadraticMatrix=s;var a=(function(){function e(e,t){this.vertexId=e,this.triangleId=t}return e})();e.Reference=a;var h=(function(){function t(t){this._mesh=t,this.initialized=!1,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=e.Epsilon}return t.prototype.simplify=function(t,i){var r=this;this.initDecimatedMesh(),e.AsyncLoop.Run(this._mesh.subMeshes.length,(function(e){r.initWithMesh(e.index,(function(){r.runDecimation(t,e.index,(function(){e.executeNext()}))}),t.optimizeMesh)}),(function(){setTimeout((function(){i(r._reconstructedMesh)}),0)}))},t.prototype.isTriangleOnBoundingBox=function(e){var t=this,i=0;return e.vertices.forEach((function(e){var r=0,n=e.position,o=t._mesh.getBoundingInfo().boundingBox;(o.maximum.x-n.x<t.boundingBoxEpsilon||n.x-o.minimum.x>t.boundingBoxEpsilon)&&++r,o.maximum.y!==n.y&&n.y!==o.minimum.y||++r,o.maximum.z!==n.z&&n.z!==o.minimum.z||++r,r>1&&++i})),i>1&&console.log(e,i),i>1},t.prototype.runDecimation=function(t,i,r){var n=this,o=~~(this.triangles.length*t.quality),s=0,a=this.triangles.length,h=function(t,i){setTimeout((function(){t%5===0&&n.updateMesh(0===t);for(var r=0;r<n.triangles.length;++r)n.triangles[r].isDirty=!1;var h=1e-9*Math.pow(t+3,n.aggressiveness),c=function(t){var i=~~((n.triangles.length/2+t)%n.triangles.length),r=n.triangles[i];if(r&&!(r.error[3]>h||r.deleted||r.isDirty))for(var o=0;o<3;++o)if(r.error[o]<h){var a=[],c=[],l=r.vertices[o],u=r.vertices[(o+1)%3];if(l.isBorder||u.isBorder)continue;var d=e.Vector3.Zero(),f=e.Vector3.Zero(),p=e.Vector2.Zero(),_=new e.Color4(0,0,0,1);n.calculateError(l,u,d,f,p,_);var m=[];if(n.isFlipped(l,u,d,a,r.borderFactor,m))continue;if(n.isFlipped(u,l,d,c,r.borderFactor,m))continue;if(a.indexOf(!0)<0||c.indexOf(!0)<0)continue;var g=[];if(m.forEach((function(e){g.indexOf(e)===-1&&(e.deletePending=!0,g.push(e))})),g.length%2!==0)continue;l.q=u.q.add(l.q),l.updatePosition(d);var v=n.references.length;s=n.updateTriangles(l,l,a,s),s=n.updateTriangles(l,u,c,s);var y=n.references.length-v;if(y<=l.triangleCount){if(y)for(var x=0;x<y;x++)n.references[l.triangleStart+x]=n.references[v+x]}else l.triangleStart=v;l.triangleCount=y;break}};e.AsyncLoop.SyncAsyncForLoop(n.triangles.length,n.syncIterations,c,i,(function(){return a-s<=o}))}),0)};e.AsyncLoop.Run(this.decimationIterations,(function(e){a-s<=o?e.breakLoop():h(e.index,(function(){e.executeNext()}))}),(function(){setTimeout((function(){n.reconstructMesh(i),r()}),0)}))},t.prototype.initWithMesh=function(t,i,r){var s=this;this.vertices=[],this.triangles=[];var a=this._mesh.getVerticesData(e.VertexBuffer.PositionKind),h=this._mesh.getIndices(),c=this._mesh.subMeshes[t],l=function(e){if(r)for(var t=0;t<s.vertices.length;++t)if(s.vertices[t].position.equals(e))return s.vertices[t];return null},u=[],d=function(t){var i=t+c.verticesStart,r=e.Vector3.FromArray(a,3*i),n=l(r)||new o(r,s.vertices.length);n.originalOffsets.push(i),n.id===s.vertices.length&&s.vertices.push(n),u.push(n.id)},f=c.verticesCount;e.AsyncLoop.SyncAsyncForLoop(f,this.syncIterations/4>>0,d,(function(){var t=function(e){var t=c.indexStart/3+e,i=3*t,r=h[i+0],o=h[i+1],a=h[i+2],l=s.vertices[u[r-c.verticesStart]],d=s.vertices[u[o-c.verticesStart]],f=s.vertices[u[a-c.verticesStart]],p=new n([l,d,f]);p.originalOffset=i,s.triangles.push(p)};e.AsyncLoop.SyncAsyncForLoop(c.indexCount/3,s.syncIterations,t,(function(){s.init(i)}))}))},t.prototype.init=function(t){var i=this,r=function(t){var r=i.triangles[t];r.normal=e.Vector3.Cross(r.vertices[1].position.subtract(r.vertices[0].position),r.vertices[2].position.subtract(r.vertices[0].position)).normalize();for(var n=0;n<3;n++)r.vertices[n].q.addArrayInPlace(s.DataFromNumbers(r.normal.x,r.normal.y,r.normal.z,-e.Vector3.Dot(r.normal,r.vertices[0].position)))};e.AsyncLoop.SyncAsyncForLoop(this.triangles.length,this.syncIterations,r,(function(){var r=function(e){for(var t=i.triangles[e],r=0;r<3;++r)t.error[r]=i.calculateError(t.vertices[r],t.vertices[(r+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])};e.AsyncLoop.SyncAsyncForLoop(i.triangles.length,i.syncIterations,r,(function(){i.initialized=!0,t()}))}))},t.prototype.reconstructMesh=function(t){var i,r=[];for(i=0;i<this.vertices.length;++i)this.vertices[i].triangleCount=0;var n,o;for(i=0;i<this.triangles.length;++i)if(!this.triangles[i].deleted){for(n=this.triangles[i],o=0;o<3;++o)n.vertices[o].triangleCount=1;r.push(n)}var s=this._reconstructedMesh.getVerticesData(e.VertexBuffer.PositionKind)||[],a=this._reconstructedMesh.getVerticesData(e.VertexBuffer.NormalKind)||[],h=this._reconstructedMesh.getVerticesData(e.VertexBuffer.UVKind)||[],c=this._reconstructedMesh.getVerticesData(e.VertexBuffer.ColorKind)||[],l=this._mesh.getVerticesData(e.VertexBuffer.NormalKind),u=this._mesh.getVerticesData(e.VertexBuffer.UVKind),d=this._mesh.getVerticesData(e.VertexBuffer.ColorKind),f=0;for(i=0;i<this.vertices.length;++i){var p=this.vertices[i];p.id=f,p.triangleCount&&p.originalOffsets.forEach((function(e){s.push(p.position.x),s.push(p.position.y),s.push(p.position.z),a.push(l[3*e]),a.push(l[3*e+1]),a.push(l[3*e+2]),u&&u.length?(h.push(u[2*e]),h.push(u[2*e+1])):d&&d.length&&(c.push(d[4*e]),c.push(d[4*e+1]),c.push(d[4*e+2]),c.push(d[4*e+3])),++f}))}var _=this._reconstructedMesh.getTotalIndices(),m=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];var v=this._reconstructedMesh.getIndices(),y=this._mesh.getIndices();for(i=0;i<r.length;++i)n=r[i],[0,1,2].forEach((function(e){var t=y[n.originalOffset+e],i=n.vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),v.push(n.vertices[e].id+i+m)}));this._reconstructedMesh.setIndices(v),this._reconstructedMesh.setVerticesData(e.VertexBuffer.PositionKind,s),this._reconstructedMesh.setVerticesData(e.VertexBuffer.NormalKind,a),h.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.UVKind,h),c.length>0&&this._reconstructedMesh.setVerticesData(e.VertexBuffer.ColorKind,c);var x=this._mesh.subMeshes[t];if(t>0){this._reconstructedMesh.subMeshes=[],g.forEach((function(t){new e.SubMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,t.getMesh())}));new e.SubMesh(x.materialIndex,m,f,_,3*r.length,this._reconstructedMesh)}},t.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new e.Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},t.prototype.isFlipped=function(t,i,r,n,o,s){for(var a=0;a<t.triangleCount;++a){var h=this.triangles[this.references[t.triangleStart+a].triangleId];if(!h.deleted){var c=this.references[t.triangleStart+a].vertexId,l=h.vertices[(c+1)%3],u=h.vertices[(c+2)%3];if(l!==i&&u!==i){var d=l.position.subtract(r);d=d.normalize();var f=u.position.subtract(r);if(f=f.normalize(),Math.abs(e.Vector3.Dot(d,f))>.999)return!0;var p=e.Vector3.Cross(d,f).normalize();if(n[a]=!1,e.Vector3.Dot(p,h.normal)<.2)return!0}else n[a]=!0,s.push(h)}}return!1},t.prototype.updateTriangles=function(e,t,i,r){for(var n=r,o=0;o<t.triangleCount;++o){var s=this.references[t.triangleStart+o],a=this.triangles[s.triangleId];a.deleted||(i[o]&&a.deletePending?(a.deleted=!0,n++):(a.vertices[s.vertexId]=e,a.isDirty=!0,a.error[0]=this.calculateError(a.vertices[0],a.vertices[1])+a.borderFactor/2,a.error[1]=this.calculateError(a.vertices[1],a.vertices[2])+a.borderFactor/2,a.error[2]=this.calculateError(a.vertices[2],a.vertices[0])+a.borderFactor/2,a.error[3]=Math.min(a.error[0],a.error[1],a.error[2]),this.references.push(s)))}return n},t.prototype.identifyBorder=function(){for(var e=0;e<this.vertices.length;++e){var t,i=[],r=[],n=this.vertices[e];for(t=0;t<n.triangleCount;++t)for(var o=this.triangles[this.references[n.triangleStart+t].triangleId],s=0;s<3;s++){for(var a=0,h=o.vertices[s];a<i.length&&r[a]!==h.id;)++a;a===i.length?(i.push(1),r.push(h.id)):i[a]++}for(t=0;t<i.length;++t)1===i[t]?this.vertices[r[t]].isBorder=!0:this.vertices[r[t]].isBorder=!1}},t.prototype.updateMesh=function(e){void 0===e&&(e=!1);var t;if(!e){var i=[];for(t=0;t<this.triangles.length;++t)this.triangles[t].deleted||i.push(this.triangles[t]);this.triangles=i}for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleCount=0,this.vertices[t].triangleStart=0;var r,n,o;for(t=0;t<this.triangles.length;++t)for(r=this.triangles[t],n=0;n<3;++n)o=r.vertices[n],o.triangleCount++;var s=0;for(t=0;t<this.vertices.length;++t)this.vertices[t].triangleStart=s,s+=this.vertices[t].triangleCount,this.vertices[t].triangleCount=0;var h=new Array(3*this.triangles.length);for(t=0;t<this.triangles.length;++t)for(r=this.triangles[t],n=0;n<3;++n)o=r.vertices[n],h[o.triangleStart+o.triangleCount]=new a(n,t),o.triangleCount++;this.references=h,e&&this.identifyBorder()},t.prototype.vertexError=function(e,t){var i=t.x,r=t.y,n=t.z;return e.data[0]*i*i+2*e.data[1]*i*r+2*e.data[2]*i*n+2*e.data[3]*i+e.data[4]*r*r+2*e.data[5]*r*n+2*e.data[6]*r+e.data[7]*n*n+2*e.data[8]*n+e.data[9]},t.prototype.calculateError=function(t,i,r,n,o,s){var a=t.q.add(i.q),h=t.isBorder&&i.isBorder,c=0,l=a.det(0,1,2,1,4,5,2,5,7);if(0===l||h){var u=t.position.add(i.position).divide(new e.Vector3(2,2,2)),d=this.vertexError(a,t.position),f=this.vertexError(a,i.position),p=this.vertexError(a,u);c=Math.min(d,f,p),c===d?r&&r.copyFrom(t.position):c===f?r&&r.copyFrom(i.position):r&&r.copyFrom(u)}else r||(r=e.Vector3.Zero()),r.x=-1/l*a.det(1,2,3,4,5,6,5,7,8),r.y=1/l*a.det(0,2,3,1,5,6,2,7,8),r.z=-1/l*a.det(0,1,3,1,4,6,2,5,8),c=this.vertexError(a,r);return c},t})();e.QuadraticErrorSimplification=h})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=[],i=function(i,r){if(!t[i.id]&&!i.doNotSerialize){if(i instanceof e.Geometry.Primitives.Box)r.boxes.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Sphere)r.spheres.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Cylinder)r.cylinders.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Torus)r.toruses.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Ground)r.grounds.push(i.serialize());else if(i instanceof e.Geometry.Primitives.Plane)r.planes.push(i.serialize());else if(i instanceof e.Geometry.Primitives.TorusKnot)r.torusKnots.push(i.serialize());else{if(i instanceof e.Geometry.Primitives._Primitive)throw new Error("Unknown primitive type");r.vertexData.push(i.serializeVerticeData())}t[i.id]=!0}},r=function(t,r){var n={};n.name=t.name,n.id=t.id,e.Tags.HasTags(t)&&(n.tags=e.Tags.GetTags(t)),n.position=t.position.asArray(),t.rotationQuaternion?n.rotationQuaternion=t.rotationQuaternion.asArray():t.rotation&&(n.rotation=t.rotation.asArray()),n.scaling=t.scaling.asArray(),n.localMatrix=t.getPivotMatrix().asArray(),n.isEnabled=t.isEnabled(),n.isVisible=t.isVisible,n.infiniteDistance=t.infiniteDistance,n.pickable=t.isPickable,n.receiveShadows=t.receiveShadows,n.billboardMode=t.billboardMode,n.visibility=t.visibility,n.checkCollisions=t.checkCollisions,n.isBlocker=t.isBlocker,t.parent&&(n.parentId=t.parent.id);var o=t._geometry;if(o){var s=o.id;n.geometryId=s,t.getScene().getGeometryByID(s)||i(o,r.geometries),n.subMeshes=[];for(var a=0;a<t.subMeshes.length;a++){var h=t.subMeshes[a];n.subMeshes.push({materialIndex:h.materialIndex,verticesStart:h.verticesStart,verticesCount:h.verticesCount,indexStart:h.indexStart,indexCount:h.indexCount})}}t.material?n.materialId=t.material.id:t.material=null,t.skeleton&&(n.skeletonId=t.skeleton.id),t.getPhysicsImpostor()&&(n.physicsMass=t.getPhysicsMass(),n.physicsFriction=t.getPhysicsFriction(),n.physicsRestitution=t.getPhysicsRestitution(),n.physicsImpostor=t.getPhysicsImpostor().type),t.metadata&&(n.metadata=t.metadata),n.instances=[];for(var c=0;c<t.instances.length;c++){var l=t.instances[c],u={name:l.name,position:l.position.asArray(),scaling:l.scaling.asArray()};l.rotationQuaternion?u.rotationQuaternion=l.rotationQuaternion.asArray():l.rotation&&(u.rotation=l.rotation.asArray()),n.instances.push(u),e.Animation.AppendSerializedAnimations(l,u),u.ranges=l.serializeAnimationRanges()}return e.Animation.AppendSerializedAnimations(t,n),n.ranges=t.serializeAnimationRanges(),n.layerMask=t.layerMask,n.alphaIndex=t.alphaIndex,n.hasVertexAlpha=t.hasVertexAlpha,n.overlayAlpha=t.overlayAlpha,n.overlayColor=t.overlayColor.asArray(),n.renderOverlay=t.renderOverlay,n.applyFog=t.applyFog,t.actionManager&&(n.actions=t.actionManager.serialize(t.name)),n},n=function(t,n){if(t.delayLoadState===e.Engine.DELAYLOADSTATE_LOADED||t.delayLoadState===e.Engine.DELAYLOADSTATE_NONE){t.material&&(t.material instanceof e.StandardMaterial?(n.materials=n.materials||[],n.materials.some((function(e){return e.id===t.material.id}))||n.materials.push(t.material.serialize())):t.material instanceof e.MultiMaterial&&(n.multiMaterials=n.multiMaterials||[],n.multiMaterials.some((function(e){return e.id===t.material.id}))||n.multiMaterials.push(t.material.serialize())));var o=t._geometry;o&&(n.geometries||(n.geometries={},n.geometries.boxes=[],n.geometries.spheres=[],n.geometries.cylinders=[],n.geometries.toruses=[],n.geometries.grounds=[],n.geometries.planes=[],n.geometries.torusKnots=[],n.geometries.vertexData=[]),i(o,n.geometries)),t.skeleton&&(n.skeletons=n.skeletons||[],n.skeletons.push(t.skeleton.serialize())),n.meshes=n.meshes||[],n.meshes.push(r(t,n))}},o=(function(){function o(){}return o.ClearCache=function(){t=[]},o.Serialize=function(n){var o={};o.useDelayedTextureLoading=n.useDelayedTextureLoading,o.autoClear=n.autoClear,o.clearColor=n.clearColor.asArray(),o.ambientColor=n.ambientColor.asArray(),o.gravity=n.gravity.asArray(),o.collisionsEnabled=n.collisionsEnabled,o.workerCollisions=n.workerCollisions,n.fogMode&&0!==n.fogMode&&(o.fogMode=n.fogMode,o.fogColor=n.fogColor.asArray(),o.fogStart=n.fogStart,o.fogEnd=n.fogEnd,o.fogDensity=n.fogDensity),n.isPhysicsEnabled()&&(o.physicsEnabled=!0,o.physicsGravity=n.getPhysicsEngine().gravity.asArray(),o.physicsEngine=n.getPhysicsEngine().getPhysicsPluginName()),n.metadata&&(o.metadata=n.metadata),o.lights=[];var s,a;for(s=0;s<n.lights.length;s++)a=n.lights[s],a.doNotSerialize||o.lights.push(a.serialize());for(o.cameras=[],s=0;s<n.cameras.length;s++){var h=n.cameras[s];h.doNotSerialize||o.cameras.push(h.serialize())}n.activeCamera&&(o.activeCameraID=n.activeCamera.id),e.Animation.AppendSerializedAnimations(n,o),o.materials=[],o.multiMaterials=[];var c;for(s=0;s<n.materials.length;s++)c=n.materials[s],c.doNotSerialize||o.materials.push(c.serialize());for(o.multiMaterials=[],s=0;s<n.multiMaterials.length;s++){var l=n.multiMaterials[s];o.multiMaterials.push(l.serialize())}for(o.skeletons=[],s=0;s<n.skeletons.length;s++)o.skeletons.push(n.skeletons[s].serialize());o.geometries={},o.geometries.boxes=[],o.geometries.spheres=[],o.geometries.cylinders=[],o.geometries.toruses=[],o.geometries.grounds=[],o.geometries.planes=[],o.geometries.torusKnots=[],o.geometries.vertexData=[],t=[];var u=n.getGeometries();for(s=0;s<u.length;s++){var d=u[s];d.isReady()&&i(d,o.geometries)}for(o.meshes=[],s=0;s<n.meshes.length;s++){var f=n.meshes[s];if(f instanceof e.Mesh){var p=f;p.doNotSerialize||p.delayLoadState!==e.Engine.DELAYLOADSTATE_LOADED&&p.delayLoadState!==e.Engine.DELAYLOADSTATE_NONE||o.meshes.push(r(p,o))}}for(o.particleSystems=[],s=0;s<n.particleSystems.length;s++)o.particleSystems.push(n.particleSystems[s].serialize());for(o.lensFlareSystems=[],s=0;s<n.lensFlareSystems.length;s++)o.lensFlareSystems.push(n.lensFlareSystems[s].serialize());for(o.shadowGenerators=[],s=0;s<n.lights.length;s++){a=n.lights[s];var _=a.getShadowGenerator();_&&_ instanceof e.ShadowGenerator&&o.shadowGenerators.push(_.serialize())}for(n.actionManager&&(o.actions=n.actionManager.serialize("scene")),o.sounds=[],s=0;s<n.soundTracks.length;s++)for(var m=n.soundTracks[s],g=0;g<m.soundCollection.length;g++)o.sounds.push(m.soundCollection[g].serialize());return o},o.SerializeMesh=function(t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var o={};if(t=t instanceof Array?t:[t],i||r)for(var s=0;s<t.length;++s)r&&t[s].getDescendants().forEach((function(i){i instanceof e.Mesh&&t.indexOf(i)<0&&t.push(i)})),i&&t[s].parent&&t.indexOf(t[s].parent)<0&&t.push(t[s].parent);return t.forEach((function(e){n(e,o)})),o},o})();e.SceneSerializer=o})(BABYLON||(BABYLON={}));var Earcut;!(function(e){function t(e,t,r){r=r||2;var o=t&&t.length,s=o?t[0]*r:e.length,a=i(e,0,s,r,!0),h=[];if(!a)return h;var l,u,d,f,p,_,m;if(o&&(a=c(e,t,a,r)),e.length>80*r){l=d=e[0],u=f=e[1];for(var g=r;g<s;g+=r)p=e[g],_=e[g+1],p<l&&(l=p),_<u&&(u=_),p>d&&(d=p),_>f&&(f=_);m=Math.max(d-l,f-u)}return n(a,h,r,l,u,m,void 0),h}function i(e,t,i,r,n){var o,s;if(n===O(e,t,i,r)>0)for(o=t;o<i;o+=r)s=S(o,e[o],e[o+1],s);else for(o=i-r;o>=t;o-=r)s=S(o,e[o],e[o+1],s);return s&&x(s,s.next)&&(M(s),s=s.next),s}function r(e,t){if(!e)return e;t||(t=e);var i,r=e;do if(i=!1,r.steiner||!x(r,r.next)&&0!==y(r.prev,r,r.next))r=r.next;else{if(M(r),r=t=r.prev,r===r.next)return null;i=!0}while(i||r!==t);return t}function n(e,t,i,c,l,u,d){if(e){!d&&u&&f(e,c,l,u);for(var p,_,m=e;e.prev!==e.next;)if(p=e.prev,_=e.next,u?s(e,c,l,u):o(e))t.push(p.i/i),t.push(e.i/i),t.push(_.i/i),M(e),e=_.next,m=_.next;else if(e=_,e===m){d?1===d?(e=a(e,t,i),n(e,t,i,c,l,u,2)):2===d&&h(e,t,i,c,l,u):n(r(e,void 0),t,i,c,l,u,1);break}}}function o(e){var t=e.prev,i=e,r=e.next;if(y(t,i,r)>=0)return!1;for(var n=e.next.next;n!==e.prev;){if(g(t.x,t.y,i.x,i.y,r.x,r.y,n.x,n.y)&&y(n.prev,n,n.next)>=0)return!1;n=n.next}return!0}function s(e,t,i,r){var n=e.prev,o=e,s=e.next;if(y(n,o,s)>=0)return!1;for(var a=n.x<o.x?n.x<s.x?n.x:s.x:o.x<s.x?o.x:s.x,h=n.y<o.y?n.y<s.y?n.y:s.y:o.y<s.y?o.y:s.y,c=n.x>o.x?n.x>s.x?n.x:s.x:o.x>s.x?o.x:s.x,l=n.y>o.y?n.y>s.y?n.y:s.y:o.y>s.y?o.y:s.y,u=_(a,h,t,i,r),d=_(c,l,t,i,r),f=e.nextZ;f&&f.z<=d;){if(f!==e.prev&&f!==e.next&&g(n.x,n.y,o.x,o.y,s.x,s.y,f.x,f.y)&&y(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=e.prevZ;f&&f.z>=u;){if(f!==e.prev&&f!==e.next&&g(n.x,n.y,o.x,o.y,s.x,s.y,f.x,f.y)&&y(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0}function a(e,t,i){var r=e;do{var n=r.prev,o=r.next.next;!x(n,o)&&b(n,r,r.next,o)&&T(n,o)&&T(o,n)&&(t.push(n.i/i),t.push(r.i/i),t.push(o.i/i),M(r),M(r.next),r=e=o),r=r.next}while(r!==e);return r}function h(e,t,i,o,s,a){var h=e;do{for(var c=h.next.next;c!==h.prev;){if(h.i!==c.i&&v(h,c)){var l=P(h,c);return h=r(h,h.next),l=r(l,l.next),n(h,t,i,o,s,a,void 0),void n(l,t,i,o,s,a,void 0)}c=c.next}h=h.next}while(h!==e)}function c(e,t,n,o){var s,a,h,c,d,f=[];for(s=0,a=t.length;s<a;s++)h=t[s]*o,c=s<a-1?t[s+1]*o:e.length,d=i(e,h,c,o,!1),d===d.next&&(d.steiner=!0),f.push(m(d));for(f.sort(l),s=0;s<f.length;s++)u(f[s],n),n=r(n,n.next);return n}function l(e,t){return e.x-t.x}function u(e,t){if(t=d(e,t)){var i=P(t,e);r(i,i.next)}}function d(e,t){var i,r=t,n=e.x,o=e.y,s=-(1/0);do{if(o<=r.y&&o>=r.next.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=n&&a>s){if(s=a,a===n){if(o===r.y)return r;if(o===r.next.y)return r.next}i=r.x<r.next.x?r:r.next}}r=r.next}while(r!==t);if(!i)return null;if(n===s)return i.prev;var h,c=i,l=i.x,u=i.y,d=1/0;for(r=i.next;r!==c;)n>=r.x&&r.x>=l&&g(o<u?n:s,o,l,u,o<u?s:n,o,r.x,r.y)&&(h=Math.abs(o-r.y)/(n-r.x),(h<d||h===d&&r.x>i.x)&&T(r,e)&&(i=r,d=h)),r=r.next;return i}function f(e,t,i,r){var n=e;do null===n.z&&(n.z=_(n.x,n.y,t,i,r)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,p(n)}function p(e){var t,i,r,n,o,s,a,h,c=1;do{for(i=e,e=null,o=null,s=0;i;){for(s++,r=i,a=0,t=0;t<c&&(a++,r=r.nextZ,r);t++);for(h=c;a>0||h>0&&r;)0===a?(n=r,r=r.nextZ,h--):0!==h&&r?i.z<=r.z?(n=i,i=i.nextZ,a--):(n=r,r=r.nextZ,h--):(n=i,i=i.nextZ,a--),o?o.nextZ=n:e=n,n.prevZ=o,o=n;i=r}o.nextZ=null,c*=2}while(s>1);return e}function _(e,t,i,r,n){return e=32767*(e-i)/n,t=32767*(t-r)/n,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e|t<<1}function m(e){var t=e,i=e;do t.x<i.x&&(i=t),t=t.next;while(t!==e);return i}function g(e,t,i,r,n,o,s,a){return(n-s)*(t-a)-(e-s)*(o-a)>=0&&(e-s)*(r-a)-(i-s)*(t-a)>=0&&(i-s)*(o-a)-(n-s)*(r-a)>=0}function v(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!A(e,t)&&T(e,t)&&T(t,e)&&E(e,t)}function y(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function x(e,t){return e.x===t.x&&e.y===t.y}function b(e,t,i,r){return!!(x(e,t)&&x(i,r)||x(e,r)&&x(i,t))||y(e,t,i)>0!=y(e,t,r)>0&&y(i,r,e)>0!=y(i,r,t)>0}function A(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&b(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}function T(e,t){return y(e.prev,e,e.next)<0?y(e,t,e.next)>=0&&y(e,e.prev,t)>=0:y(e,t,e.prev)<0||y(e,e.next,t)<0}function E(e,t){var i=e,r=!1,n=(e.x+t.x)/2,o=(e.y+t.y)/2;do i.y>o!=i.next.y>o&&n<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next;while(i!==e);return r}function P(e,t){var i=new C(e.i,e.x,e.y),r=new C(t.i,t.x,t.y),n=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=n,n.prev=i,r.next=i,i.prev=r,o.next=r,r.prev=o,r}function S(e,t,i,r){var n=new C(e,t,i);return r?(n.next=r.next,n.prev=r,r.next.prev=n,r.next=n):(n.prev=n,n.next=n),n}function M(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function C(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function R(e,t,i,r){var n=t&&t.length,o=n?t[0]*i:e.length,s=Math.abs(O(e,0,o,i));if(n)for(var a=0,h=t.length;a<h;a++){var c=t[a]*i,l=a<h-1?t[a+1]*i:e.length;s-=Math.abs(O(e,c,l,i))}var u=0;for(a=0;a<r.length;a+=3){var d=r[a]*i,f=r[a+1]*i,p=r[a+2]*i;u+=Math.abs((e[d]-e[p])*(e[f+1]-e[d+1])-(e[d]-e[f])*(e[p+1]-e[d+1]))}return 0===s&&0===u?0:Math.abs((u-s)/s)}function O(e,t,i,r){for(var n=0,o=t,s=i-r;o<i;o+=r)n+=(e[s]-e[o])*(e[o+1]+e[s+1]),s=o;return n}function D(e){for(var t=e[0][0].length,i={vertices:[],holes:[],dimensions:t},r=0,n=0;n<e.length;n++){for(var o=0;o<e[n].length;o++)for(var s=0;s<t;s++)i.vertices.push(e[n][o][s]);n>0&&(r+=e[n-1].length,i.holes.push(r))}return i}e.earcut=t,e.deviation=R,e.flatten=D})(Earcut||(Earcut={}));var BABYLON;!(function(e){var t=0,i=(function(){function t(e,t,i){this.pos=e,this.normal=t,this.uv=i}return t.prototype.clone=function(){return new t(this.pos.clone(),this.normal.clone(),this.uv.clone())},t.prototype.flip=function(){this.normal=this.normal.scale(-1)},t.prototype.interpolate=function(i,r){return new t(e.Vector3.Lerp(this.pos,i.pos,r),e.Vector3.Lerp(this.normal,i.normal,r),e.Vector2.Lerp(this.uv,i.uv,r))},t})(),r=(function(){function t(e,t){this.normal=e,this.w=t}return t.FromPoints=function(i,r,n){var o=n.subtract(i),s=r.subtract(i);if(0===o.lengthSquared()||0===s.lengthSquared())return null;var a=e.Vector3.Normalize(e.Vector3.Cross(o,s));return new t(a,e.Vector3.Dot(a,i))},t.prototype.clone=function(){return new t(this.normal.clone(),this.w)},t.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},t.prototype.splitPolygon=function(i,r,o,s,a){var h,c,l=0,u=1,d=2,f=3,p=0,_=[];for(h=0;h<i.vertices.length;h++){c=e.Vector3.Dot(this.normal,i.vertices[h].pos)-this.w;var m=c<-t.EPSILON?d:c>t.EPSILON?u:l;p|=m,_.push(m)}switch(p){case l:(e.Vector3.Dot(this.normal,i.plane.normal)>0?r:o).push(i);break;case u:s.push(i);break;case d:a.push(i);break;case f:var g=[],v=[];for(h=0;h<i.vertices.length;h++){var y=(h+1)%i.vertices.length,x=_[h],b=_[y],A=i.vertices[h],T=i.vertices[y];if(x!==d&&g.push(A),x!==u&&v.push(x!==d?A.clone():A),(x|b)===f){c=(this.w-e.Vector3.Dot(this.normal,A.pos))/e.Vector3.Dot(this.normal,T.pos.subtract(A.pos));var E=A.interpolate(T,c);g.push(E),v.push(E.clone())}}var P;g.length>=3&&(P=new n(g,i.shared),P.plane&&s.push(P)),v.length>=3&&(P=new n(v,i.shared),P.plane&&a.push(P))}},t.EPSILON=1e-5,t})(),n=(function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=r.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){var t=this.vertices.map((function(e){return e.clone()}));return new e(t,this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e})(),o=(function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=[],e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t.plane=this.plane&&this.plane.clone(),t.front=this.front&&this.front.clone(),t.back=this.back&&this.back.clone(),t.polygons=this.polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e<this.polygons.length;e++)this.polygons[e].flip();this.plane&&this.plane.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();var t=this.front;this.front=this.back,this.back=t},e.prototype.clipPolygons=function(e){if(!this.plane)return e.slice();for(var t=[],i=[],r=0;r<e.length;r++)this.plane.splitPolygon(e[r],t,i,t,i);return this.front&&(t=this.front.clipPolygons(t)),i=this.back?this.back.clipPolygons(i):[],t.concat(i)},e.prototype.clipTo=function(e){this.polygons=e.clipPolygons(this.polygons),this.front&&this.front.clipTo(e),this.back&&this.back.clipTo(e)},e.prototype.allPolygons=function(){var e=this.polygons.slice();return this.front&&(e=e.concat(this.front.allPolygons())),this.back&&(e=e.concat(this.back.allPolygons())),e},e.prototype.build=function(t){if(t.length){this.plane||(this.plane=t[0].plane.clone());for(var i=[],r=[],n=0;n<t.length;n++)this.plane.splitPolygon(t[n],this.polygons,this.polygons,i,r);
i.length&&(this.front||(this.front=new e),this.front.build(i)),r.length&&(this.back||(this.back=new e),this.back.build(r))}},e})(),s=(function(){function r(){this.polygons=new Array}return r.FromMesh=function(o){var s,a,h,c,l,u,d,f,p,_,m,g=new Array;if(!(o instanceof e.Mesh))throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";o.computeWorldMatrix(!0),d=o.getWorldMatrix(),f=o.position.clone(),p=o.rotation.clone(),o.rotationQuaternion&&(_=o.rotationQuaternion.clone()),m=o.scaling.clone();for(var v=o.getIndices(),y=o.getVerticesData(e.VertexBuffer.PositionKind),x=o.getVerticesData(e.VertexBuffer.NormalKind),b=o.getVerticesData(e.VertexBuffer.UVKind),A=o.subMeshes,T=0,E=A.length;T<E;T++)for(var P=A[T].indexStart,S=A[T].indexCount+A[T].indexStart;P<S;P+=3){u=[];for(var M=0;M<3;M++){var C=new e.Vector3(x[3*v[P+M]],x[3*v[P+M]+1],x[3*v[P+M]+2]);h=new e.Vector2(b[2*v[P+M]],b[2*v[P+M]+1]);var R=new e.Vector3(y[3*v[P+M]],y[3*v[P+M]+1],y[3*v[P+M]+2]);c=e.Vector3.TransformCoordinates(R,d),a=e.Vector3.TransformNormal(C,d),s=new i(c,a,h),u.push(s)}l=new n(u,{subMeshId:T,meshId:t,materialIndex:A[T].materialIndex}),l.plane&&g.push(l)}var O=r.FromPolygons(g);return O.matrix=d,O.position=f,O.rotation=p,O.scaling=m,O.rotationQuaternion=_,t++,O},r.FromPolygons=function(e){var t=new r;return t.polygons=e,t},r.prototype.clone=function(){var e=new r;return e.polygons=this.polygons.map((function(e){return e.clone()})),e.copyTransformAttributes(this),e},r.prototype.toPolygons=function(){return this.polygons},r.prototype.union=function(e){var t=new o(this.clone().polygons),i=new o(e.clone().polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),r.FromPolygons(t.allPolygons()).copyTransformAttributes(this)},r.prototype.unionInPlace=function(e){var t=new o(this.polygons),i=new o(e.polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this.polygons=t.allPolygons()},r.prototype.subtract=function(e){var t=new o(this.clone().polygons),i=new o(e.clone().polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),r.FromPolygons(t.allPolygons()).copyTransformAttributes(this)},r.prototype.subtractInPlace=function(e){var t=new o(this.polygons),i=new o(e.polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this.polygons=t.allPolygons()},r.prototype.intersect=function(e){var t=new o(this.clone().polygons),i=new o(e.clone().polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),r.FromPolygons(t.allPolygons()).copyTransformAttributes(this)},r.prototype.intersectInPlace=function(e){var t=new o(this.polygons),i=new o(e.polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this.polygons=t.allPolygons()},r.prototype.inverse=function(){var e=this.clone();return e.inverseInPlace(),e},r.prototype.inverseInPlace=function(){this.polygons.map((function(e){e.flip()}))},r.prototype.copyTransformAttributes=function(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this},r.prototype.buildMeshGeometry=function(t,i,r){var n=this.matrix.clone();n.invert();var o,s,a,h=new e.Mesh(t,i),c=[],l=[],u=[],d=[],f=e.Vector3.Zero(),p=e.Vector3.Zero(),_=e.Vector2.Zero(),m=this.polygons,g=[0,0,0],v={},y=0,x={};r&&m.sort((function(e,t){return e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId}));for(var b=0,A=m.length;b<A;b++){o=m[b],x[o.shared.meshId]||(x[o.shared.meshId]={}),x[o.shared.meshId][o.shared.subMeshId]||(x[o.shared.meshId][o.shared.subMeshId]={indexStart:+(1/0),indexEnd:-(1/0),materialIndex:o.shared.materialIndex}),a=x[o.shared.meshId][o.shared.subMeshId];for(var T=2,E=o.vertices.length;T<E;T++){g[0]=0,g[1]=T-1,g[2]=T;for(var P=0;P<3;P++){f.copyFrom(o.vertices[g[P]].pos),p.copyFrom(o.vertices[g[P]].normal),_.copyFrom(o.vertices[g[P]].uv);var S=e.Vector3.TransformCoordinates(f,n),M=e.Vector3.TransformNormal(p,n);s=v[S.x+","+S.y+","+S.z],"undefined"!=typeof s&&u[3*s]===M.x&&u[3*s+1]===M.y&&u[3*s+2]===M.z&&d[2*s]===_.x&&d[2*s+1]===_.y||(c.push(S.x,S.y,S.z),d.push(_.x,_.y),u.push(p.x,p.y,p.z),s=v[S.x+","+S.y+","+S.z]=c.length/3-1),l.push(s),a.indexStart=Math.min(y,a.indexStart),a.indexEnd=Math.max(y,a.indexEnd),y++}}}if(h.setVerticesData(e.VertexBuffer.PositionKind,c),h.setVerticesData(e.VertexBuffer.NormalKind,u),h.setVerticesData(e.VertexBuffer.UVKind,d),h.setIndices(l),r){var C,R=0;h.subMeshes=new Array;for(var O in x){C=-1;for(var D in x[O])a=x[O][D],e.SubMesh.CreateFromIndices(a.materialIndex+R,a.indexStart,a.indexEnd-a.indexStart+1,h),C=Math.max(a.materialIndex,C);R+=++C}}return h},r.prototype.toMesh=function(e,t,i,r){var n=this.buildMeshGeometry(e,i,r);return n.material=t,n.position.copyFrom(this.position),n.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(n.rotationQuaternion=this.rotationQuaternion.clone()),n.scaling.copyFrom(this.scaling),n.computeWorldMatrix(!0),n},r})();e.CSG=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,i,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,o.postProcessScaleFactor,r,e.Texture.BILINEAR_SAMPLINGMODE,null,null),this._isRightEye=n,this._distortionFactors=o.distortionK,this._postProcessScaleFactor=o.postProcessScaleFactor,this._lensCenterOffset=o.lensCenterOffset,this.onSizeChangedObservable.add((function(){s.aspectRatio=.5*s.width/s.height,s._scaleIn=new e.Vector2(2,2/s.aspectRatio),s._scaleFactor=new e.Vector2(.5*(1/s._postProcessScaleFactor),.5*(1/s._postProcessScaleFactor)*s.aspectRatio),s._lensCenter=new e.Vector2(s._isRightEye?.5-.5*s._lensCenterOffset:.5+.5*s._lensCenterOffset,.5)})),this.onApplyObservable.add((function(e){e.setFloat2("LensCenter",s._lensCenter.x,s._lensCenter.y),e.setFloat2("Scale",s._scaleFactor.x,s._scaleFactor.y),e.setFloat2("ScaleIn",s._scaleIn.x,s._scaleIn.y),e.setFloat4("HmdWarpParam",s._distortionFactors[0],s._distortionFactors[1],s._distortionFactors[2],s._distortionFactors[3])}))}return __extends(i,t),i})(e.PostProcess);e.VRDistortionCorrectionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"})(e.JoystickAxis||(e.JoystickAxis={}));var t=e.JoystickAxis,i=(function(){function i(r){var n=this;r?this._leftJoystick=!0:this._leftJoystick=!1,this._joystickIndex=i._globalJoystickIndex,i._globalJoystickIndex++,this._axisTargetedByLeftAndRight=t.X,this._axisTargetedByUpAndDown=t.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new e.StringDictionary,this.deltaPosition=e.Vector3.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._rotationSpeed=25,this._inverseRotationSpeed=1/(this._rotationSpeed/1e3),this._rotateOnAxisRelativeToMesh=!1,this._onResize=function(e){i.vjCanvasWidth=window.innerWidth,i.vjCanvasHeight=window.innerHeight,i.vjCanvas.width=i.vjCanvasWidth,i.vjCanvas.height=i.vjCanvasHeight,i.halfWidth=i.vjCanvasWidth/2,i.halfHeight=i.vjCanvasHeight/2},i.vjCanvas||(window.addEventListener("resize",this._onResize,!1),i.vjCanvas=document.createElement("canvas"),i.vjCanvasWidth=window.innerWidth,i.vjCanvasHeight=window.innerHeight,i.vjCanvas.width=window.innerWidth,i.vjCanvas.height=window.innerHeight,i.vjCanvas.style.width="100%",i.vjCanvas.style.height="100%",i.vjCanvas.style.position="absolute",i.vjCanvas.style.backgroundColor="transparent",i.vjCanvas.style.top="0px",i.vjCanvas.style.left="0px",i.vjCanvas.style.zIndex="5",i.vjCanvas.style.msTouchAction="none",i.vjCanvas.setAttribute("touch-action","none"),i.vjCanvasContext=i.vjCanvas.getContext("2d"),i.vjCanvasContext.strokeStyle="#ffffff",i.vjCanvasContext.lineWidth=2,document.body.appendChild(i.vjCanvas)),i.halfWidth=i.vjCanvas.width/2,i.halfHeight=i.vjCanvas.height/2,this.pressed=!1,this._joystickColor="cyan",this._joystickPointerID=-1,this._joystickPointerPos=new e.Vector2(0,0),this._joystickPreviousPointerPos=new e.Vector2(0,0),this._joystickPointerStartPos=new e.Vector2(0,0),this._deltaJoystickVector=new e.Vector2(0,0),this._onPointerDownHandlerRef=function(e){n._onPointerDown(e)},this._onPointerMoveHandlerRef=function(e){n._onPointerMove(e)},this._onPointerOutHandlerRef=function(e){n._onPointerUp(e)},this._onPointerUpHandlerRef=function(e){n._onPointerUp(e)},i.vjCanvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),i.vjCanvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),i.vjCanvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),i.vjCanvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),i.vjCanvas.addEventListener("contextmenu",(function(e){e.preventDefault()}),!1),requestAnimationFrame((function(){n._drawVirtualJoystick()}))}return i.prototype.setJoystickSensibility=function(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)},i.prototype._onPointerDown=function(e){var t;e.preventDefault(),t=this._leftJoystick===!0?e.clientX<i.halfWidth:e.clientX>i.halfWidth,t&&this._joystickPointerID<0?(this._joystickPointerID=e.pointerId,this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone(),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):i._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))},i.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var i=this.reverseLeftRight?-1:1,r=i*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,r));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,r));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,r))}var n=this.reverseUpDown?1:-1,o=n*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var s=this._touches.get(e.pointerId.toString());s&&(s.x=e.clientX,s.y=e.clientY)}},i.prototype._onPointerUp=function(e){if(this._joystickPointerID==e.pointerId)i.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-63,this._joystickPointerStartPos.y-63,126,126),i.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-41,this._joystickPreviousPointerPos.y-41,82,82),this._joystickPointerID=-1,this.pressed=!1;else{var t=this._touches.get(e.pointerId.toString());t&&i.vjCanvasContext.clearRect(t.prevX-43,t.prevY-43,86,86)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())},i.prototype.setJoystickColor=function(e){this._joystickColor=e},i.prototype.setActionOnTouch=function(e){this._action=e},i.prototype.setAxisForLeftRight=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=t.X}},i.prototype.setAxisForUpDown=function(e){switch(e){case t.X:case t.Y:case t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=t.Y}},i.prototype._clearCanvas=function(){this._leftJoystick?i.vjCanvasContext.clearRect(0,0,i.vjCanvasWidth/2,i.vjCanvasHeight):i.vjCanvasContext.clearRect(i.vjCanvasWidth/2,0,i.vjCanvasWidth,i.vjCanvasHeight)},i.prototype._drawVirtualJoystick=function(){var e=this;this.pressed&&this._touches.forEach((function(t){t.pointerId===e._joystickPointerID?(i.vjCanvasContext.clearRect(e._joystickPointerStartPos.x-63,e._joystickPointerStartPos.y-63,126,126),i.vjCanvasContext.clearRect(e._joystickPreviousPointerPos.x-41,e._joystickPreviousPointerPos.y-41,82,82),i.vjCanvasContext.beginPath(),i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.lineWidth=2,i.vjCanvasContext.arc(e._joystickPointerStartPos.x,e._joystickPointerStartPos.y,60,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle=e._joystickColor,i.vjCanvasContext.arc(e._joystickPointerPos.x,e._joystickPointerPos.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),e._joystickPreviousPointerPos=e._joystickPointerPos.clone()):(i.vjCanvasContext.clearRect(t.prevX-43,t.prevY-43,86,86),i.vjCanvasContext.beginPath(),i.vjCanvasContext.fillStyle="white",i.vjCanvasContext.beginPath(),i.vjCanvasContext.strokeStyle="red",i.vjCanvasContext.lineWidth=6,i.vjCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),i.vjCanvasContext.stroke(),i.vjCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((function(){e._drawVirtualJoystick()}))},i.prototype.releaseCanvas=function(){i.vjCanvas&&(i.vjCanvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),i.vjCanvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),i.vjCanvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),i.vjCanvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(i.vjCanvas),i.vjCanvas=null)},i._globalJoystickIndex=0,i})();e.VirtualJoystick=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addVirtualJoystick()}return __extends(t,e),t})(e.FreeCamera);e.VirtualJoysticksCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){}return t.prototype.getLeftJoystick=function(){return this._leftjoystick},t.prototype.getRightJoystick=function(){return this._rightjoystick},t.prototype.checkInputs=function(){if(this._leftjoystick){var t=this.camera,i=50*t._computeLocalCameraSpeed(),r=e.Matrix.RotationYawPitchRoll(t.rotation.y,t.rotation.x,0),n=e.Vector3.TransformCoordinates(new e.Vector3(this._leftjoystick.deltaPosition.x*i,this._leftjoystick.deltaPosition.y*i,this._leftjoystick.deltaPosition.z*i),r);t.cameraDirection=t.cameraDirection.add(n),t.cameraRotation=t.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},t.prototype.attachControl=function(t,i){this._leftjoystick=new e.VirtualJoystick((!0)),this._leftjoystick.setAxisForUpDown(e.JoystickAxis.Z),this._leftjoystick.setAxisForLeftRight(e.JoystickAxis.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new e.VirtualJoystick((!1)),this._rightjoystick.setAxisForUpDown(e.JoystickAxis.X),this._rightjoystick.setAxisForLeftRight(e.JoystickAxis.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},t.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},t.prototype.getTypeName=function(){return"FreeCameraVirtualJoystickInput"},t.prototype.getSimpleName=function(){return"virtualJoystick"},t})();e.FreeCameraVirtualJoystickInput=t,e.CameraInputTypes.FreeCameraVirtualJoystickInput=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=this;e.call(this,t,"anaglyph",null,["leftSampler"],i,r[1],n,o,s),this._passedProcess=r[0]._rigPostProcess,this.onApplyObservable.add((function(e){e.setTextureFromPostProcess("leftSampler",a._passedProcess)}))}return __extends(t,e),t})(e.PostProcess);e.AnaglyphPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e){this._scene=e}return t.prototype.render=function(t,i,r){var n=this;void 0===r&&(r=!1);var o=this._scene,s=this._scene.getEngine(),a=null!==s.getCaps().instancedArrays&&null!==i.visibleInstances[t._id]&&void 0!==i.visibleInstances[t._id];if(this.isReady(t,a)){var h=t.getRenderingMesh(),c=t.getMaterial();if(s.enableEffect(this._effect),this._effect.setFloat("offset",r?0:h.outlineWidth),this._effect.setColor4("color",r?h.overlayColor:h.outlineColor,r?h.overlayAlpha:1),this._effect.setMatrix("viewProjection",o.getTransformMatrix()),h.useBones&&h.computeBonesUsingShaders&&this._effect.setMatrices("mBones",h.skeleton.getTransformMatrices(h)),h._bind(t,this._effect,e.Material.TriangleFillMode),c&&c.needAlphaTesting()){var l=c.getAlphaTestTexture();this._effect.setTexture("diffuseSampler",l),this._effect.setMatrix("diffuseMatrix",l.getTextureMatrix())}h._processRendering(t,this._effect,e.Material.TriangleFillMode,i,a,(function(e,t){n._effect.setMatrix("world",t)}))}},t.prototype.isReady=function(t,i){var r=[],n=[e.VertexBuffer.PositionKind,e.VertexBuffer.NormalKind],o=t.getMesh(),s=t.getMaterial();s&&s.needAlphaTesting()&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(n.push(e.VertexBuffer.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(n.push(e.VertexBuffer.UV2Kind),r.push("#define UV2"))),o.useBones&&o.computeBonesUsingShaders?(n.push(e.VertexBuffer.MatricesIndicesKind),n.push(e.VertexBuffer.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(e.VertexBuffer.MatricesIndicesExtraKind),n.push(e.VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):r.push("#define NUM_BONE_INFLUENCERS 0"),i&&(r.push("#define INSTANCES"),n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"));var a=r.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color"],["diffuseSampler"],a)),this._effect.isReady()},t})();e.OutlineRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r){this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this;e.SceneLoader.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,t,(function(e,t,r){n.loadedMeshes=e,n.loadedParticleSystems=t,n.loadedSkeletons=r,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()}),null,(function(){n.onError&&n.onError(n),r()}))},t})();e.MeshAssetTask=t;var i=(function(){function t(e,t){this.name=e,this.url=t,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this;e.Tools.LoadFile(this.url,(function(e){n.text=e,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()}),null,t.database,!1,(function(){n.onError&&n.onError(n),r()}))},t})();e.TextFileAssetTask=i;var r=(function(){function t(e,t){this.name=e,this.url=t,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this;e.Tools.LoadFile(this.url,(function(e){n.data=e,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()}),null,t.database,!0,(function(){n.onError&&n.onError(n),r()}))},t})();e.BinaryFileAssetTask=r;var n=(function(){function t(e,t){this.name=e,this.url=t,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this,o=new Image;e.Tools.SetCorsBehavior(this.url,o),o.onload=function(){n.image=o,n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()},o.onerror=function(){n.onError&&n.onError(n),r()},o.src=this.url},t})();e.ImageAssetTask=n;var o=(function(){function t(t,i,r,n,o){void 0===o&&(o=e.Texture.TRILINEAR_SAMPLINGMODE),this.name=t,this.url=i,this.noMipmap=r,this.invertY=n,this.samplingMode=o,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this,o=function(){n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()},s=function(){n.onError&&n.onError(n),r()};this.texture=new e.Texture(this.url,t,this.noMipmap,this.invertY,this.samplingMode,o,s)},t})();e.TextureAssetTask=o;var s=(function(){function t(e,t,i,r,n){this.name=e,this.url=t,this.extensions=i,this.noMipmap=r,this.files=n,this.isCompleted=!1}return t.prototype.run=function(t,i,r){var n=this,o=function(){n.isCompleted=!0,n.onSuccess&&n.onSuccess(n),i()},s=function(){n.onError&&n.onError(n),r()};this.texture=new e.CubeTexture(this.url,t,this.extensions,this.noMipmap,this.files,o,s)},t})();e.CubeTextureAssetTask=s;var a=(function(){function s(e){this.tasks=new Array,this.waitingTasksCount=0,this.useDefaultLoadingScreen=!0,this._scene=e}return s.prototype.addMeshTask=function(e,i,r,n){var o=new t(e,i,r,n);return this.tasks.push(o),o},s.prototype.addTextFileTask=function(e,t){var r=new i(e,t);return this.tasks.push(r),r},s.prototype.addBinaryFileTask=function(e,t){var i=new r(e,t);return this.tasks.push(i),i},s.prototype.addImageTask=function(e,t){var i=new n(e,t);return this.tasks.push(i),i},s.prototype.addTextureTask=function(t,i,r,n,s){void 0===s&&(s=e.Texture.TRILINEAR_SAMPLINGMODE);var a=new o(t,i,r,n,s);return this.tasks.push(a),a},s.prototype._decreaseWaitingTasksCount=function(){this.waitingTasksCount--,0===this.waitingTasksCount&&(this.onFinish&&this.onFinish(this.tasks),this._scene.getEngine().hideLoadingUI())},s.prototype._runTask=function(e){var t=this;e.run(this._scene,(function(){t.onTaskSuccess&&t.onTaskSuccess(e),t._decreaseWaitingTasksCount()}),(function(){t.onTaskError&&t.onTaskError(e),t._decreaseWaitingTasksCount()}))},s.prototype.reset=function(){return this.tasks=new Array,this},s.prototype.load=function(){if(this.waitingTasksCount=this.tasks.length,0===this.waitingTasksCount)return this.onFinish&&this.onFinish(this.tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e<this.tasks.length;e++){var t=this.tasks[e];this._runTask(t)}return this},s})();e.AssetsManager=a})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.compensateDistortion=!0}return Object.defineProperty(t.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftHMatrix",{get:function(){var t=this.hScreenSize/4-this.lensSeparationDistance/2,i=4*t/this.hScreenSize;return e.Matrix.Translation(i,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightHMatrix",{get:function(){var t=this.hScreenSize/4-this.lensSeparationDistance/2,i=4*t/this.hScreenSize;return e.Matrix.Translation(-i,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftPreViewMatrix",{get:function(){return e.Matrix.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightPreViewMatrix",{get:function(){return e.Matrix.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),t.GetDefault=function(){var e=new t;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e},t})();e.VRCameraMetrics=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this;void 0===o&&(o=!1),void 0===s&&(s={}),t.call(this,i,r,n),this.webVROptions=s,this._vrDevice=null,this._cacheState=null,this._vrEnabled=!1,this._attached=!1,this._positionOffset=r,this.getEngine().initWebVR(),this.getEngine().vrDisplaysPromise?(this._frameData=new VRFrameData,this.getEngine().vrDisplaysPromise.then((function(t){if(t.length>0){if(a._vrEnabled=!0,a.webVROptions.displayName){var i=t.some((function(e){return e.displayName===a.webVROptions.displayName&&(a._vrDevice=e,!0)}));i||(a._vrDevice=t[0],e.Tools.Warn("Display "+a.webVROptions.displayName+" was not found. Using "+a._vrDevice.displayName))}else a._vrDevice=t[0];a.setCameraRigMode(e.Camera.RIG_MODE_WEBVR,{vrDisplay:a._vrDevice,frameData:a._frameData}),a._attached&&a.getEngine().enableVR(a._vrDevice)}else e.Tools.Error("No WebVR devices found!")}))):e.Tools.Error("WebVR is not enabled on your browser"),this.rotationQuaternion=new e.Quaternion,this._quaternionCache=new e.Quaternion}return __extends(i,t),i.prototype._checkInputs=function(){if(this._vrEnabled&&this._vrDevice.getFrameData(this._frameData)){var e=this._frameData.pose;e&&e.orientation&&(this._cacheState=e,this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0],this._cacheState.orientation[1],-this._cacheState.orientation[2],-this._cacheState.orientation[3]),this.webVROptions.trackPosition&&this._cacheState.position&&(this.position.copyFromFloats(this._cacheState.position[0],this._cacheState.position[1],-this._cacheState.position[2]),this.webVROptions.positionScale&&this.position.scaleInPlace(this.webVROptions.positionScale),this.position.addInPlace(this._positionOffset)))}t.prototype._checkInputs.call(this)},i.prototype.attachControl=function(i,r){t.prototype.attachControl.call(this,i,r),this._attached=!0,r=!e.Camera.ForceAttachControlToAlwaysPreventDefault&&r,this._vrEnabled&&this.getEngine().enableVR(this._vrDevice)},i.prototype.detachControl=function(e){t.prototype.detachControl.call(this,e),this._vrEnabled=!1,this._attached=!1,this.getEngine().disableVR()},i.prototype.requestVRFullscreen=function(t){e.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.")},i.prototype.getTypeName=function(){return"WebVRFreeCamera"},i.prototype.resetToCurrentRotation=function(){this._vrDevice.resetPose()},i.prototype.setPositionOffset=function(e){e?this._positionOffset=e:this._positionOffset.copyFrom(this.position)},i})(e.FreeCamera);e.WebVRFreeCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){void 0===e&&(e=0),this.priority=e,this.apply=function(e){return!0}}return e})();e.SceneOptimization=t;var i=(function(e){function t(t,i){var r=this;void 0===t&&(t=0),void 0===i&&(i=1024),e.call(this,t),this.priority=t,this.maximumSize=i,this.apply=function(e){for(var t=!0,i=0;i<e.textures.length;i++){var n=e.textures[i];if(n.canRescale){var o=n.getSize(),s=Math.max(o.width,o.height);s>r.maximumSize&&(n.scale(.5),t=!1)}}return t}}return __extends(t,e),t})(t);e.TextureOptimization=i;var r=(function(e){function t(t,i){var r=this;void 0===t&&(t=0),void 0===i&&(i=2),e.call(this,t),this.priority=t,this.maximumScale=i,this._currentScale=1,this.apply=function(e){return r._currentScale++,e.getEngine().setHardwareScalingLevel(r._currentScale),r._currentScale>=r.maximumScale}}return __extends(t,e),t})(t);e.HardwareScalingOptimization=r;var n=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.shadowsEnabled=!1,!0}}return __extends(t,e),t})(t);e.ShadowsOptimization=n;var o=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.postProcessesEnabled=!1,!0}}return __extends(t,e),t})(t);e.PostProcessesOptimization=o;var s=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.lensFlaresEnabled=!1,!0}}return __extends(t,e),t})(t);e.LensFlaresOptimization=s;var a=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.particlesEnabled=!1,!0}}return __extends(t,e),t})(t);e.ParticlesOptimization=a;var h=(function(e){function t(){e.apply(this,arguments),this.apply=function(e){return e.renderTargetsEnabled=!1,!0}}return __extends(t,e),t})(t);e.RenderTargetsOptimization=h;var c=(function(t){function i(){var r=this;t.apply(this,arguments),this._canBeMerged=function(t){if(!(t instanceof e.Mesh))return!1;var i=t;return!(!i.isVisible||!i.isEnabled())&&(!(i.instances.length>0)&&(!i.skeleton&&!i.hasLODLevels&&!i.parent))},this.apply=function(t,n){for(var o=t.meshes.slice(0),s=o.length,a=0;a<s;a++){var h=new Array,c=o[a];if(r._canBeMerged(c)){h.push(c);for(var l=a+1;l<s;l++){var u=o[l];r._canBeMerged(u)&&u.material===c.material&&u.checkCollisions===c.checkCollisions&&(h.push(u),s--,o.splice(l,1),l--)}h.length<2||e.Mesh.MergeMeshes(h)}}return void 0!=n?n&&t.createOrUpdateSelectionOctree():i.UpdateSelectionTree&&t.createOrUpdateSelectionOctree(),!0}}return __extends(i,t),Object.defineProperty(i,"UpdateSelectionTree",{get:function(){return i._UpdateSelectionTree},set:function(e){i._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),i._UpdateSelectionTree=!1,i})(t);e.MergeMeshesOptimization=c;var l=(function(){function e(e,t){void 0===e&&(e=60),void 0===t&&(t=2e3),this.targetFrameRate=e,this.trackerDuration=t,this.optimizations=new Array}return e.LowDegradationAllowed=function(t){var r=new e(t),h=0;return r.optimizations.push(new c(h)),r.optimizations.push(new n(h)),r.optimizations.push(new s(h)),h++,r.optimizations.push(new o(h)),r.optimizations.push(new a(h)),h++,r.optimizations.push(new i(h,1024)),r},e.ModerateDegradationAllowed=function(t){var l=new e(t),u=0;return l.optimizations.push(new c(u)),l.optimizations.push(new n(u)),l.optimizations.push(new s(u)),u++,l.optimizations.push(new o(u)),l.optimizations.push(new a(u)),u++,l.optimizations.push(new i(u,512)),u++,l.optimizations.push(new h(u)),u++,l.optimizations.push(new r(u,2)),l},e.HighDegradationAllowed=function(t){var l=new e(t),u=0;return l.optimizations.push(new c(u)),l.optimizations.push(new n(u)),l.optimizations.push(new s(u)),u++,l.optimizations.push(new o(u)),l.optimizations.push(new a(u)),u++,l.optimizations.push(new i(u,256)),u++,l.optimizations.push(new h(u)),u++,l.optimizations.push(new r(u,4)),l},e})();e.SceneOptimizerOptions=l;var u=(function(){function e(){}return e._CheckCurrentState=function(t,i,r,n,o){if(t.getEngine().getFps()>=i.targetFrameRate)return void(n&&n());for(var s=!0,a=!0,h=0;h<i.optimizations.length;h++){var c=i.optimizations[h];c.priority===r&&(a=!1,s=s&&c.apply(t))}return a?void(o&&o()):(s&&r++,void t.executeWhenReady((function(){setTimeout((function(){e._CheckCurrentState(t,i,r,n,o)}),i.trackerDuration)})))},e.OptimizeAsync=function(t,i,r,n){i||(i=l.ModerateDegradationAllowed()),t.executeWhenReady((function(){setTimeout((function(){e._CheckCurrentState(t,i,0,r,n)}),i.trackerDuration)}))},e})();e.SceneOptimizer=u})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function e(e,t){this.distance=e,this.mesh=t}return e})();e.MeshLODLevel=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){void 0===a&&(a=!0),void 0===h&&(h=!1),void 0===c&&(c=e.Texture.TRILINEAR_SAMPLINGMODE),t.call(this,null,s,!a,h),this.format=o,this._texture=s.getEngine().createRawTexture(i,r,n,o,a,h,c),this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE}return __extends(i,t),i.prototype.update=function(e){this.getScene().getEngine().updateRawTexture(this._texture,e,this.format,this._invertY)},i.CreateLuminanceTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE,o,s,a,h);
},i.CreateLuminanceAlphaTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA,o,s,a,h)},i.CreateAlphaTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_ALPHA,o,s,a,h)},i.CreateRGBTexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGB,o,s,a,h)},i.CreateRGBATexture=function(t,r,n,o,s,a,h){return void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=e.Texture.TRILINEAR_SAMPLINGMODE),new i(t,r,n,e.Engine.TEXTUREFORMAT_RGBA,o,s,a,h)},i})(e.Texture);e.RawTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i){e.call(this,t.x,t.y),this.index=i}return __extends(t,e),t})(e.Vector2),i=(function(){function i(){this.elements=new Array}return i.prototype.add=function(e){var i=this,r=new Array;return e.forEach((function(e){if(0===r.length||!e.equalsWithEpsilon(r[0])){var n=new t(e,i.elements.length);r.push(n),i.elements.push(n)}})),r},i.prototype.computeBounds=function(){var t=new e.Vector2(this.elements[0].x,this.elements[0].y),i=new e.Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(e){e.x<t.x?t.x=e.x:e.x>i.x&&(i.x=e.x),e.y<t.y?t.y=e.y:e.y>i.y&&(i.y=e.y)})),{min:t,max:i,width:i.x-t.x,height:i.y-t.y}},i})(),r=(function(){function t(){}return t.Rectangle=function(t,i,r,n){return[new e.Vector2(t,i),new e.Vector2(r,i),new e.Vector2(r,n),new e.Vector2(t,n)]},t.Circle=function(t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=32);for(var o=new Array,s=0,a=2*Math.PI/n,h=0;h<n;h++)o.push(new e.Vector2(i+Math.cos(s)*t,r+Math.sin(s)*t)),s-=a;return o},t.Parse=function(t){var i,r=t.split(/[^-+eE\.\d]+/).map(parseFloat).filter((function(e){return!isNaN(e)})),n=[];for(i=0;i<(2147483646&r.length);i+=2)n.push(new e.Vector2(r[i],r[i+1]));return n},t.StartingAt=function(t,i){return e.Path2.StartingAt(t,i)},t})();e.Polygon=r;var n=(function(){function t(t,r,n){this._points=new i,this._outlinepoints=new i,this._holes=[],this._epoints=new Array,this._eholes=new Array,this._name=t,this._scene=n;var o;o=r instanceof e.Path2?r.getPoints():r,this._addToepoint(o),this._points.add(o),this._outlinepoints.add(o)}return t.prototype._addToepoint=function(e){for(var t=0,i=e;t<i.length;t++){var r=i[t];this._epoints.push(r.x,r.y)}},t.prototype.addHole=function(e){this._points.add(e);var t=new i;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this},t.prototype.build=function(t,i){var r=this;void 0===t&&(t=!1);var n=new e.Mesh(this._name,this._scene),o=[],s=[],a=[],h=this._points.computeBounds();this._points.elements.forEach((function(e){o.push(0,1,0),s.push(e.x,0,e.y),a.push((e.x-h.min.x)/h.width,(e.y-h.min.y)/h.height)}));for(var c=[],l=Earcut.earcut(this._epoints,this._eholes,2),u=0;u<l.length;u++)c.push(l[u]);if(i>0){var d=s.length/3;this._points.elements.forEach((function(e){o.push(0,-1,0),s.push(e.x,-i,e.y),a.push(1-(e.x-h.min.x)/h.width,1-(e.y-h.min.y)/h.height)}));for(var f=c.length,u=0;u<f;u+=3){var p=c[u+0],_=c[u+1],m=c[u+2];c.push(m+d),c.push(_+d),c.push(p+d)}this.addSide(s,o,a,c,h,this._outlinepoints,i,!1),this._holes.forEach((function(e){r.addSide(s,o,a,c,h,e,i,!0)}))}return n.setVerticesData(e.VertexBuffer.PositionKind,s,t),n.setVerticesData(e.VertexBuffer.NormalKind,o,t),n.setVerticesData(e.VertexBuffer.UVKind,a,t),n.setIndices(c),n},t.prototype.addSide=function(t,i,r,n,o,s,a,h){for(var c=t.length/3,l=0,u=0;u<s.elements.length;u++){var d,f=s.elements[u];d=u+1>s.elements.length-1?s.elements[0]:s.elements[u+1],t.push(f.x,0,f.y),t.push(f.x,-a,f.y),t.push(d.x,0,d.y),t.push(d.x,-a,d.y);var p=new e.Vector3(f.x,0,f.y),_=new e.Vector3(d.x,0,d.y),m=_.subtract(p),g=new e.Vector3(0,1,0),v=e.Vector3.Cross(m,g);v=v.normalize(),r.push(l/o.width,0),r.push(l/o.width,1),l+=m.length(),r.push(l/o.width,0),r.push(l/o.width,1),h?(i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),i.push(v.x,v.y,v.z),n.push(c),n.push(c+2),n.push(c+1),n.push(c+1),n.push(c+2),n.push(c+3)):(i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),i.push(-v.x,-v.y,-v.z),n.push(c),n.push(c+1),n.push(c+2),n.push(c+1),n.push(c+3),n.push(c+2)),c+=4}},t})();e.PolygonMeshBuilder=n})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){void 0===r&&(r=2),this.maxDepth=r,this.dynamicContent=new Array,this._maxBlockCapacity=i||64,this._selectionContent=new e.SmartArray(1024),this._creationFunc=t}return t.prototype.update=function(e,i,r){t._CreateBlocks(e,i,r,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)},t.prototype.addMesh=function(e){for(var t=0;t<this.blocks.length;t++){var i=this.blocks[t];i.addEntry(e)}},t.prototype.select=function(e,t){this._selectionContent.reset();for(var i=0;i<this.blocks.length;i++){var r=this.blocks[i];r.select(e,this._selectionContent,t)}return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},t.prototype.intersects=function(e,t,i){this._selectionContent.reset();for(var r=0;r<this.blocks.length;r++){var n=this.blocks[r];n.intersects(e,t,this._selectionContent,i)}return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},t.prototype.intersectsRay=function(e){this._selectionContent.reset();for(var t=0;t<this.blocks.length;t++){var i=this.blocks[t];i.intersectsRay(e,this._selectionContent)}return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},t._CreateBlocks=function(t,i,r,n,o,s,a,h){a.blocks=new Array;for(var c=new e.Vector3((i.x-t.x)/2,(i.y-t.y)/2,(i.z-t.z)/2),l=0;l<2;l++)for(var u=0;u<2;u++)for(var d=0;d<2;d++){var f=t.add(c.multiplyByFloats(l,u,d)),p=t.add(c.multiplyByFloats(l+1,u+1,d+1)),_=new e.OctreeBlock(f,p,n,o+1,s,h);_.addEntries(r),a.blocks.push(_)}},t.CreationFuncForMeshes=function(e,t){!e.isBlocked&&e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},t.CreationFuncForSubMeshes=function(e,t){e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},t})();e.Octree=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(e,t,i,r,n,o){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=n,this._creationFunc=o,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}return Object.defineProperty(t.prototype,"capacity",{get:function(){return this._capacity},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minPoint",{get:function(){return this._minPoint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxPoint",{get:function(){return this._maxPoint},enumerable:!0,configurable:!0}),t.prototype.addEntry=function(e){if(this.blocks)for(var t=0;t<this.blocks.length;t++){var i=this.blocks[t];i.addEntry(e)}else this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()},t.prototype.addEntries=function(e){for(var t=0;t<e.length;t++){var i=e[t];this.addEntry(i)}},t.prototype.select=function(t,i,r){if(e.BoundingBox.IsInFrustum(this._boundingVectors,t)){if(this.blocks){for(var n=0;n<this.blocks.length;n++){var o=this.blocks[n];o.select(t,i,r)}return}r?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}},t.prototype.intersects=function(t,i,r,n){if(e.BoundingBox.IntersectsSphere(this._minPoint,this._maxPoint,t,i)){if(this.blocks){for(var o=0;o<this.blocks.length;o++){var s=this.blocks[o];s.intersects(t,i,r,n)}return}n?r.concat(this.entries):r.concatWithNoDuplicate(this.entries)}},t.prototype.intersectsRay=function(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(var i=0;i<this.blocks.length;i++){var r=this.blocks[i];r.intersectsRay(e,t)}return}t.concatWithNoDuplicate(this.entries)}},t.prototype.createInnerBlocks=function(){e.Octree._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc)},t})();e.OctreeBlock=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,i,"blur",["screenSize","direction","blurWidth"],null,o,s,a,h,c),this.direction=r,this.blurWidth=n,this.onApplyObservable.add((function(e){e.setFloat2("screenSize",l.width,l.height),e.setVector2("direction",l.direction),e.setFloat("blurWidth",l.blurWidth)}))}return __extends(i,t),i})(e.PostProcess);e.BlurPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h,c,l,u){var d=this;t.call(this,i,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,h,c,l,u),this.color=n,this.depth=o,this.colorLevel=s,this.onActivateObservable.add((function(t){d._refRexture=d._refRexture||new e.Texture(r,t.getScene())})),this.onApplyObservable.add((function(e){e.setColor3("baseColor",d.color),e.setFloat("depth",d.depth),e.setFloat("colorLevel",d.colorLevel),e.setTexture("refractionSampler",d._refRexture)}))}return __extends(i,t),i.prototype.dispose=function(e){this._refRexture&&this._refRexture.dispose(),t.prototype.dispose.call(this,e)},i})(e.PostProcess);e.RefractionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){e.call(this,t,"blackAndWhite",null,null,i,r,n,o,s)}return __extends(t,e),t})(e.PostProcess);e.BlackAndWhitePostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var h=this;e.call(this,t,"convolution",["kernel","screenSize"],null,r,n,o,s,a),this.kernel=i,this.onApply=function(e){e.setFloat2("screenSize",h.width,h.height),e.setArray("kernel",h.kernel)}}return __extends(t,e),t.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],t.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],t.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],t.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],t.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],t.GaussianKernel=[0,1,0,1,1,1,0,1,0],t})(e.PostProcess);e.ConvolutionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s,a){var h=this;e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,s,a),this.kernelMatrix=i,this.onApply=function(e){e.setMatrix("kernelMatrix",h.kernelMatrix)}}return __extends(t,e),t})(e.PostProcess);e.FilterPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r,n,o,s){var a=this;e.call(this,t,"fxaa",["texelSize"],null,i,r,n,o,s),this.onSizeChangedObservable.add((function(){a.texelWidth=1/a.width,a.texelHeight=1/a.height})),this.onApplyObservable.add((function(e){e.setFloat2("texelSize",a.texelWidth,a.texelHeight)}))}return __extends(t,e),t})(e.PostProcess);e.FxaaPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a){var h=this;t.call(this,i,"stereoscopicInterlace",["stepSize"],["camASampler"],1,r[1],o,s,a,n?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=r[0]._rigPostProcess,this._stepSize=new e.Vector2(1/this.width,1/this.height),this.onSizeChangedObservable.add((function(){h._stepSize=new e.Vector2(1/h.width,1/h.height)})),this.onApplyObservable.add((function(e){e.setTextureFromPostProcess("camASampler",h._passedProcess),e.setFloat2("stepSize",h._stepSize.x,h._stepSize.y)}))}return __extends(i,t),i})(e.PostProcess);e.StereoscopicInterlacePostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o){this.size=t,this.position=i,this.alphaMode=e.Engine.ALPHA_ONEONE,this.dispose=function(){this.texture&&this.texture.dispose();var e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)},this.color=r||new e.Color3(1,1,1),this.texture=n?new e.Texture(n,o.getScene(),(!0)):null,this._system=o,o.lensFlares.push(this)}return t})();e.LensFlare=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.name=t,this.lensFlares=new Array,this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=r,this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&r.activeCamera.layerMask)};var n=r.getEngine(),o=[];o.push(1,1),o.push(-1,1),o.push(-1,-1),o.push(1,-1),this._vertexBuffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(n,o,e.VertexBuffer.PositionKind,(!1),(!1),2);var s=[];s.push(0),s.push(1),s.push(2),s.push(0),s.push(2),s.push(3),this._indexBuffer=n.createIndexBuffer(s),this._effect=n.createEffect("lensFlare",[e.VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype.getEmitter=function(){return this._emitter},t.prototype.setEmitter=function(e){this._emitter=e},t.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},t.prototype.computeEffectivePosition=function(t){var i=this.getEmitterPosition();return i=e.Vector3.Project(i,e.Matrix.Identity(),this._scene.getTransformMatrix(),t),this._positionX=i.x,this._positionY=i.y,i=e.Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(t.x-=this.viewportBorder,t.y-=this.viewportBorder,t.width+=2*this.viewportBorder,t.height+=2*this.viewportBorder,i.x+=this.viewportBorder,i.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),i.z>0&&(this._positionX>t.x&&this._positionX<t.x+t.width&&this._positionY>t.y&&this._positionY<t.y+t.height,!0)},t.prototype._isVisible=function(){if(!this._isEnabled)return!1;var t=this.getEmitterPosition(),i=t.subtract(this._scene.activeCamera.globalPosition),r=i.length();i.normalize();var n=new e.Ray(this._scene.activeCamera.globalPosition,i),o=this._scene.pickWithRay(n,this.meshesSelectionPredicate,!0);return!o.hit||o.distance>r},t.prototype.render=function(){if(!this._effect.isReady())return!1;var t=this._scene.getEngine(),i=this._scene.activeCamera.viewport,r=i.toGlobal(t.getRenderWidth(!0),t.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n,o;n=this._positionX<this.borderLimit+r.x?this.borderLimit+r.x-this._positionX:this._positionX>r.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0,o=this._positionY<this.borderLimit+r.y?this.borderLimit+r.y-this._positionY:this._positionY>r.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0;var s=n>o?n:o;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);var a=1-s/this.borderLimit;if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var h=r.x+r.width/2,c=r.y+r.height/2,l=h-this._positionX,u=c-this._positionY;t.enableEffect(this._effect),t.setState(!1),t.setDepthBuffer(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var d=0;d<this.lensFlares.length;d++){var f=this.lensFlares[d];t.setAlphaMode(f.alphaMode);var p=h-l*f.position,_=c-u*f.position,m=f.size,g=f.size*t.getAspectRatio(this._scene.activeCamera,!0),v=2*(p/(r.width+2*r.x))-1,y=1-2*(_/(r.height+2*r.y)),x=e.Matrix.FromValues(m/2,0,0,0,0,g/2,0,0,0,0,1,0,v,y,0,1);this._effect.setMatrix("viewportMatrix",x),this._effect.setTexture("textureSampler",f.texture),this._effect.setFloat4("color",f.color.r*a,f.color.g*a,f.color.b*a,1),t.draw(!0,0,6)}return t.setDepthBuffer(!0),t.setAlphaMode(e.Engine.ALPHA_DISABLE),!0},t.prototype.dispose=function(){var t=this._vertexBuffers[e.VertexBuffer.PositionKind];for(t&&(t.dispose(),this._vertexBuffers[e.VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();var i=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(i,1)},t.Parse=function(i,r,n){var o=r.getLastEntryByID(i.emitterId),s=i.name||"lensFlareSystem#"+i.emitterId,a=new t(s,o,r);a.id=i.id||s,a.borderLimit=i.borderLimit;for(var h=0;h<i.flares.length;h++){var c=i.flares[h];new e.LensFlare(c.size,c.position,e.Color3.FromArray(c.color),n+c.textureName,a)}return a},t.prototype.serialize=function(){var t={};t.id=this.id,t.name=this.name,t.emitterId=this.getEmitter().id,t.borderLimit=this.borderLimit,t.flares=[];for(var i=0;i<this.lensFlares.length;i++){var r=this.lensFlares[i];t.flares.push({size:r.size,position:r.position,color:r.color.asArray(),textureName:e.Tools.GetFilename(r.texture.name)})}return t},t})();e.LensFlareSystem=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){t.call(this,i,r,n),this._quaternionCache=new e.Quaternion,this.inputs.addDeviceOrientation()}return __extends(i,t),i.prototype.getTypeName=function(){return"DeviceOrientationCamera"},i.prototype._checkInputs=function(){t.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},i.prototype.resetToCurrentRotation=function(t){var i=this;void 0===t&&(t=e.Axis.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new e.Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(e){t[e]?i._initialQuaternion[e]*=-1:i._initialQuaternion[e]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},i})(e.FreeCamera);e.DeviceOrientationCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){void 0===o&&(o=!0),void 0===s&&(s=e.VRCameraMetrics.GetDefault()),t.call(this,i,r,n),s.compensateDistortion=o,this.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:s})}return __extends(i,t),i.prototype.getTypeName=function(){return"VRDeviceOrientationFreeCamera"},i})(e.DeviceOrientationCamera);e.VRDeviceOrientationFreeCamera=t;var i=(function(t){function i(i,r,n,o,s,a,h,c){void 0===h&&(h=!0),void 0===c&&(c=e.VRCameraMetrics.GetDefault()),t.call(this,i,r,n,o,s,a),c.compensateDistortion=h,this.setCameraRigMode(e.Camera.RIG_MODE_VR,{vrCameraMetrics:c}),this.inputs.addVRDeviceOrientation()}return __extends(i,t),i.prototype.getTypeName=function(){return"VRDeviceOrientationArcRotateCamera"},i})(e.ArcRotateCamera);e.VRDeviceOrientationArcRotateCamera=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(t,i,r){e.call(this,t,i,r),this.inputs.addGamepad()}return __extends(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadAngularSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadMoveSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getTypeName=function(){return"UniversalCamera"},t})(e.TouchCamera);e.UniversalCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(e){var t=this;this.babylonGamepads=[],this.oneGamepadConnected=!1,this.isMonitoring=!1,this.gamepadEventSupported="GamepadEvent"in window,this.gamepadSupportAvailable=navigator.getGamepads||!!navigator.webkitGetGamepads||!!navigator.msGetGamepads||!!navigator.webkitGamepads,this._callbackGamepadConnected=e,this.gamepadSupportAvailable&&(this.gamepadEventSupported?(this._onGamepadConnectedEvent=function(e){t._onGamepadConnected(e)},this._onGamepadDisonnectedEvent=function(e){t._onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisonnectedEvent,!1)):this._startMonitoringGamepads())}return e.prototype.dispose=function(){e.gamepadDOMInfo&&document.body.removeChild(e.gamepadDOMInfo),this._onGamepadConnectedEvent&&(window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.removeEventListener("gamepaddisconnected",this._onGamepadDisonnectedEvent,!1),this._onGamepadConnectedEvent=null,this._onGamepadDisonnectedEvent=null)},e.prototype._onGamepadConnected=function(e){var t=this._addNewGamepad(e.gamepad);this._callbackGamepadConnected&&this._callbackGamepadConnected(t),this._startMonitoringGamepads()},e.prototype._addNewGamepad=function(t){this.oneGamepadConnected||(this.oneGamepadConnected=!0,e.gamepadDOMInfo&&(document.body.removeChild(e.gamepadDOMInfo),e.gamepadDOMInfo=null));var i,r=t.id.search("Xbox One")!==-1;return i=r||t.id.search("Xbox 360")!==-1||t.id.search("xinput")!==-1?new a(t.id,t.index,t,r):new n(t.id,t.index,t),this.babylonGamepads.push(i),i},e.prototype._onGamepadDisconnected=function(e){for(var t in this.babylonGamepads)if(this.babylonGamepads[t].index==e.gamepad.index){this.babylonGamepads.splice(+t,1);break}0==this.babylonGamepads.length&&this._stopMonitoringGamepads()},e.prototype._startMonitoringGamepads=function(){this.isMonitoring||(this.isMonitoring=!0,this._checkGamepadsStatus())},e.prototype._stopMonitoringGamepads=function(){this.isMonitoring=!1},e.prototype._checkGamepadsStatus=function(){var e=this;this._updateGamepadObjects();for(var t in this.babylonGamepads)this.babylonGamepads[t].update();this.isMonitoring&&(window.requestAnimationFrame?window.requestAnimationFrame((function(){e._checkGamepadsStatus()})):window.mozRequestAnimationFrame?window.mozRequestAnimationFrame((function(){e._checkGamepadsStatus()})):window.webkitRequestAnimationFrame&&window.webkitRequestAnimationFrame((function(){e._checkGamepadsStatus()})))},e.prototype._updateGamepadObjects=function(){for(var e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[],t=0;t<e.length;t++)if(e[t])if(e[t].index in this.babylonGamepads)this.babylonGamepads[t].browserGamepad=e[t];else{var i=this._addNewGamepad(e[t]);this._callbackGamepadConnected&&this._callbackGamepadConnected(i)}},e})();e.Gamepads=t;var i=(function(){function e(e,t){this.x=e,this.y=t}return e})();e.StickValues=i;var r=(function(){function e(e,t,i,r,n,o,s){void 0===r&&(r=0),void 0===n&&(n=1),void 0===o&&(o=2),void 0===s&&(s=3),this.id=e,this.index=t,this.browserGamepad=i,this._leftStickAxisX=r,this._leftStickAxisY=n,this._rightStickAxisX=o,this._rightStickAxisY=s,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e})();e.Gamepad=r;var n=(function(e){function t(t,i,r){e.call(this,t,i,r),this.id=t,this.index=i,this.gamepad=r,this._buttons=new Array(r.buttons.length)}return __extends(t,e),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(this._onbuttondown&&1===e&&this._onbuttondown(i),this._onbuttonup&&0===e&&this._onbuttonup(i)),e},t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t<this._buttons.length;t++)this._buttons[t]=this._setButtonValue(this.gamepad.buttons[t].value,this._buttons[t],t)},t})(r);e.GenericPad=n,(function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.Start=4]="Start",e[e.Back=5]="Back",e[e.LB=6]="LB",e[e.RB=7]="RB",e[e.LeftStick=8]="LeftStick",e[e.RightStick=9]="RightStick"})(e.Xbox360Button||(e.Xbox360Button={}));var o=e.Xbox360Button;!(function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Left=2]="Left",e[e.Right=3]="Right"})(e.Xbox360Dpad||(e.Xbox360Dpad={}));var s=e.Xbox360Dpad,a=(function(e){function t(t,i,r,n){void 0===n&&(n=!1),e.call(this,t,i,r,0,1,n?3:2,n?4:3),this._leftTrigger=0,this._rightTrigger=0,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this._isXboxOnePad=n}return __extends(t,e),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!0,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(this._onbuttondown&&1===e&&this._onbuttondown(i),this._onbuttonup&&0===e&&this._onbuttonup(i)),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(this._ondpaddown&&1===e&&this._ondpaddown(i),this._ondpadup&&0===e&&this._ondpadup(i)),e},Object.defineProperty(t.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,o.A)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,o.B)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,o.X)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,o.Y)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,o.Start)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,o.Back)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,o.LB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,o.RB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,o.LeftStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,o.RightStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,s.Up)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,s.Down)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,s.Left)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,s.Right)},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this),this._isXboxOnePad?(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.axes[2],this.rightTrigger=this.browserGamepad.axes[5],this.buttonBack=this.browserGamepad.buttons[9].value,this.buttonStart=this.browserGamepad.buttons[8].value,this.buttonLeftStick=this.browserGamepad.buttons[6].value,this.buttonRightStick=this.browserGamepad.buttons[7].value,this.dPadUp=this.browserGamepad.buttons[11].value,this.dPadDown=this.browserGamepad.buttons[12].value,this.dPadLeft=this.browserGamepad.buttons[13].value,this.dPadRight=this.browserGamepad.buttons[14].value):(this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,
this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value)},t})(r);e.Xbox360Pad=a})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n){e.Tools.Warn("Deprecated. Please use Universal Camera instead."),t.call(this,i,r,n)}return __extends(i,t),Object.defineProperty(i.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadAngularSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;if(e)return e.gamepadMoveSensibility},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!0,configurable:!0}),i.prototype.getTypeName=function(){return"GamepadCamera"},i})(e.UniversalCamera);e.GamepadCamera=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},this._scene=t,this._audioEngine=e.Engine.audioEngine,this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))}return t.prototype.getFrequencyBinCount=function(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0},t.prototype.getByteFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs},t.prototype.getByteTimeDomainData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime},t.prototype.getFloatFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs},t.prototype.drawDebugCanvas=function(){var e=this;if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=function(){e.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc)){var t=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(var i=0;i<this.getFrequencyBinCount();i++){var r=t[i],n=r/this.BARGRAPHAMPLITUDE,o=this.DEBUGCANVASSIZE.height*n,s=this.DEBUGCANVASSIZE.height-o-1,a=this.DEBUGCANVASSIZE.width/this.getFrequencyBinCount(),h=i/this.getFrequencyBinCount()*360;this._debugCanvasContext.fillStyle="hsl("+h+", 100%, 50%)",this._debugCanvasContext.fillRect(i*a,s,a,o)}}},t.prototype.stopDebugCanvas=function(){this._debugCanvas&&(this._scene.unregisterBeforeRender(this._registerFunc),this._registerFunc=null,document.body.removeChild(this._debugCanvas),this._debugCanvas=null,this._debugCanvasContext=null)},t.prototype.connectAudioNodes=function(e,t){this._audioEngine.canUseWebAudio&&(e.connect(this._webAudioAnalyser),this._webAudioAnalyser.connect(t))},t.prototype.dispose=function(){this._audioEngine.canUseWebAudio&&this._webAudioAnalyser.disconnect()},t})();e.Analyser=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i){var r=this;void 0===i&&(i=e.Engine.TEXTURETYPE_FLOAT),this._viewMatrix=e.Matrix.Zero(),this._projectionMatrix=e.Matrix.Zero(),this._transformMatrix=e.Matrix.Zero(),this._worldViewProjection=e.Matrix.Zero(),this._scene=t;var n=t.getEngine();this._depthMap=new e.RenderTargetTexture("depthMap",{width:n.getRenderWidth(),height:n.getRenderHeight()},this._scene,(!1),(!0),i),this._depthMap.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.onClearObservable.add((function(t){t.clear(new e.Color4(1,1,1,1),!0,!0,!0)}));var o=function(t){var i=t.getRenderingMesh(),n=r._scene,o=n.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id];if(r.isReady(t,a)){o.enableEffect(r._effect),i._bind(t,r._effect,e.Material.TriangleFillMode);var h=t.getMaterial();if(r._effect.setMatrix("viewProjection",n.getTransformMatrix()),r._effect.setFloat("far",n.activeCamera.maxZ),h&&h.needAlphaTesting()){var c=h.getAlphaTestTexture();r._effect.setTexture("diffuseSampler",c),r._effect.setMatrix("diffuseMatrix",c.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&r._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),i._processRendering(t,r._effect,e.Material.TriangleFillMode,s,a,(function(e,t){return r._effect.setMatrix("world",t)}))}}};this._depthMap.customRenderFunction=function(e,t){var i;for(i=0;i<e.length;i++)o(e.data[i]);for(i=0;i<t.length;i++)o(t.data[i])}}return t.prototype.isReady=function(t,i){var r=t.getMaterial();if(r.disableDepthWrite)return!1;var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMesh();s.getScene();r&&r.needAlphaTesting()&&(n.push("#define ALPHATEST"),s.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),s.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),s.numBoneInfluencers>4&&(o.push(e.VertexBuffer.MatricesIndicesExtraKind),o.push(e.VertexBuffer.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),n.push("#define BonesPerMesh "+(s.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._effect=this._scene.getEngine().createEffect("depth",o,["world","mBones","viewProjection","diffuseMatrix","far"],["diffuseSampler"],a)),this._effect.isReady()},t.prototype.getDepthMap=function(){return this._depthMap},t.prototype.dispose=function(){this._depthMap.dispose()},t})();e.DepthRenderer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){var s=this;t.call(this,r.getEngine(),i),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.radius=1e-4,this.area=.0075,this.fallOff=1e-6,this.base=.5,this._firstUpdate=!0,this._scene=r,this._createRandomTexture(),this._depthTexture=r.enableDepthRenderer().getDepthMap();var a=n.ssaoRatio||n,h=n.combineRatio||n;this._ratio={ssaoRatio:a,combineRatio:h},this._originalColorPostProcess=new e.PassPostProcess("SSAOOriginalSceneColor",h,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),(!1)),this._createSSAOPostProcess(a),this._createBlurPostProcess(a),this._createSSAOCombinePostProcess(h),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOOriginalSceneColorEffect,function(){return s._originalColorPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAORenderEffect,function(){return s._ssaoPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOBlurHRenderEffect,function(){return s._blurHPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOBlurVRenderEffect,function(){return s._blurVPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),this.SSAOCombineRenderEffect,function(){return s._ssaoCombinePostProcess},(!0))),r.postProcessRenderPipelineManager.addPipeline(this),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,o)}return __extends(i,t),i.prototype.getBlurHPostProcess=function(){return e.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists"),null},i.prototype.getBlurVPostProcess=function(){return e.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists"),null},i.prototype.dispose=function(e){void 0===e&&(e=!1);for(var t=0;t<this._scene.cameras.length;t++){var i=this._scene.cameras[t];this._originalColorPostProcess.dispose(i),this._ssaoPostProcess.dispose(i),this._blurHPostProcess.dispose(i),this._blurVPostProcess.dispose(i),this._ssaoCombinePostProcess.dispose(i)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras)},i.prototype._createBlurPostProcess=function(t){for(var i=this,r=[],n=-8;n<8;n++)r.push(2*n);this._blurHPostProcess=new e.PostProcess("BlurH","ssao",["outSize","samplerOffsets"],["depthSampler"],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16"),this._blurHPostProcess.onApply=function(e){e.setFloat("outSize",i._ssaoCombinePostProcess.width),e.setTexture("depthSampler",i._depthTexture),i._firstUpdate&&e.setArray("samplerOffsets",r)},this._blurVPostProcess=new e.PostProcess("BlurV","ssao",["outSize","samplerOffsets"],["depthSampler"],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define BILATERAL_BLUR\n#define SAMPLES 16"),this._blurVPostProcess.onApply=function(e){e.setFloat("outSize",i._ssaoCombinePostProcess.height),e.setTexture("depthSampler",i._depthTexture),i._firstUpdate&&(e.setArray("samplerOffsets",r),i._firstUpdate=!1)}},i.prototype._createSSAOPostProcess=function(t){var i=this,r=16,n=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271],o=1/r;this._ssaoPostProcess=new e.PostProcess("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],t,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),"#define SAMPLES "+r+"\n#define SSAO");new e.Vector2(0,0);this._ssaoPostProcess.onApply=function(e){i._firstUpdate&&(e.setArray3("sampleSphere",n),e.setFloat("samplesFactor",o),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",i.totalStrength),e.setFloat("radius",i.radius),e.setFloat("area",i.area),e.setFloat("fallOff",i.fallOff),e.setFloat("base",i.base),e.setTexture("textureSampler",i._depthTexture),e.setTexture("randomSampler",i._randomTexture)}},i.prototype._createSSAOCombinePostProcess=function(t){var i=this;this._ssaoCombinePostProcess=new e.PostProcess("ssaoCombine","ssaoCombine",[],["originalColor"],t,null,e.Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1)),this._ssaoCombinePostProcess.onApply=function(e){e.setTextureFromPostProcess("originalColor",i._originalColorPostProcess)}},i.prototype._createRandomTexture=function(){var t=512;this._randomTexture=new e.DynamicTexture("SSAORandomTexture",t,this._scene,(!1),e.Texture.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=e.Texture.WRAP_ADDRESSMODE,this._randomTexture.wrapV=e.Texture.WRAP_ADDRESSMODE;for(var i=this._randomTexture.getContext(),r=function(e,t){return Math.random()*(t-e)+e},n=e.Vector3.Zero(),o=0;o<t;o++)for(var s=0;s<t;s++)n.x=Math.floor(255*r(-1,1)),n.y=Math.floor(255*r(-1,1)),n.z=Math.floor(255*r(-1,1)),i.fillStyle="rgb("+n.x+", "+n.y+", "+n.z+")",i.fillRect(o,s,1,1);this._randomTexture.update(!1)},__decorate([e.serialize()],i.prototype,"totalStrength",void 0),__decorate([e.serialize()],i.prototype,"radius",void 0),__decorate([e.serialize()],i.prototype,"area",void 0),__decorate([e.serialize()],i.prototype,"fallOff",void 0),__decorate([e.serialize()],i.prototype,"base",void 0),__decorate([e.serialize()],i.prototype,"_ratio",void 0),i})(e.PostProcessRenderPipeline);e.SSAORenderingPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a,h,c,l,u){var d=this;void 0===a&&(a=100),void 0===h&&(h=e.Texture.BILINEAR_SAMPLINGMODE),t.call(this,r,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],n.postProcessRatio||n,o,h,c,l,"#define NUM_SAMPLES "+a),this._screenCoordinates=e.Vector2.Zero(),this.customMeshPosition=e.Vector3.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=new Array,this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,u=null===o?u:o.getScene();var c=u.getEngine();this._viewPort=new e.Viewport(0,0,1,1).toGlobal(c.getRenderWidth(),c.getRenderHeight()),this.mesh=null!==s?s:i.CreateDefaultMesh("VolumetricLightScatteringMesh",u),this._createPass(u,n.passRatio||n),this.onActivate=function(e){d.isSupported||d.dispose(e),d.onActivate=null},this.onApplyObservable.add((function(e){d._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",d._volumetricLightScatteringRTT),e.setFloat("exposure",d.exposure),e.setFloat("decay",d.decay),e.setFloat("weight",d.weight),e.setFloat("density",d.density),e.setVector2("meshPositionOnScreen",d._screenCoordinates)}))}return __extends(i,t),Object.defineProperty(i.prototype,"useDiffuseColor",{get:function(){return e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(t){e.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!0,configurable:!0}),i.prototype.isReady=function(t,i){var r=t.getMesh();if(r===this.mesh)return r.material.isReady(r);var n=[],o=[e.VertexBuffer.PositionKind],s=t.getMaterial();s&&(s.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(o.push(e.VertexBuffer.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(o.push(e.VertexBuffer.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(o.push(e.VertexBuffer.MatricesIndicesKind),o.push(e.VertexBuffer.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton.bones.length+1))):n.push("#define NUM_BONE_INFLUENCERS 0"),i&&(n.push("#define INSTANCES"),o.push("world0"),o.push("world1"),o.push("world2"),o.push("world3"));var a=n.join("\n");return this._cachedDefines!==a&&(this._cachedDefines=a,this._volumetricLightScatteringPass=r.getScene().getEngine().createEffect({vertexElement:"depth",fragmentElement:"volumetricLightScatteringPass"},o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],a)),this._volumetricLightScatteringPass.isReady()},i.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},i.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},i.prototype.dispose=function(e){var i=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);i!==-1&&e.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),t.prototype.dispose.call(this,e)},i.prototype.getPass=function(){return this._volumetricLightScatteringRTT},i.prototype._meshExcluded=function(e){return this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1},i.prototype._createPass=function(t,i){var r=this,n=t.getEngine();this._volumetricLightScatteringRTT=new e.RenderTargetTexture("volumetricLightScatteringMap",{width:n.getRenderWidth()*i,height:n.getRenderHeight()*i},t,(!1),(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=e.Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,t.customRenderTargets.push(this._volumetricLightScatteringRTT);var o,s=function(t){var i=t.getRenderingMesh();if(!r._meshExcluded(i)){var n=i.getScene(),o=n.getEngine();o.setState(t.getMaterial().backFaceCulling);var s=i._getInstancesRenderList(t._id);if(!s.mustReturn){var a=null!==o.getCaps().instancedArrays&&null!==s.visibleInstances[t._id];if(r.isReady(t,a)){var h=r._volumetricLightScatteringPass;if(i===r.mesh&&(h=t.getMaterial().getEffect()),o.enableEffect(h),i._bind(t,h,e.Material.TriangleFillMode),i===r.mesh)t.getMaterial().bind(i.getWorldMatrix(),i);else{var c=t.getMaterial();if(r._volumetricLightScatteringPass.setMatrix("viewProjection",n.getTransformMatrix()),c&&c.needAlphaTesting()){var l=c.getAlphaTestTexture();r._volumetricLightScatteringPass.setTexture("diffuseSampler",l),l&&r._volumetricLightScatteringPass.setMatrix("diffuseMatrix",l.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&r._volumetricLightScatteringPass.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}i._processRendering(t,r._volumetricLightScatteringPass,e.Material.TriangleFillMode,s,a,(function(e,t){return h.setMatrix("world",t)}))}}}},a=new e.Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){o=t.clearColor,t.clearColor=a})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){t.clearColor=o})),this._volumetricLightScatteringRTT.customRenderFunction=function(i,r,n){var o,a=t.getEngine();for(o=0;o<i.length;o++)s(i.data[o]);for(a.setAlphaTesting(!0),o=0;o<r.length;o++)s(r.data[o]);if(a.setAlphaTesting(!1),n.length){for(o=0;o<n.length;o++){var h=n.data[o];h._alphaIndex=h.getMesh().alphaIndex,h._distanceToCamera=h.getBoundingInfo().boundingSphere.centerWorld.subtract(t.activeCamera.position).length()}var c=n.data.slice(0,n.length);for(c.sort((function(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0})),a.setAlphaMode(e.Engine.ALPHA_COMBINE),o=0;o<c.length;o++)s(c[o]);a.setAlphaMode(e.Engine.ALPHA_DISABLE)}}},i.prototype._updateMeshScreenCoordinates=function(t){var i,r=t.getTransformMatrix();i=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;var n=e.Vector3.Project(i,e.Matrix.Identity(),r,this._viewPort);this._screenCoordinates.x=n.x/this._viewPort.width,this._screenCoordinates.y=n.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)},i.CreateDefaultMesh=function(t,i){var r=e.Mesh.CreatePlane(t,1,i);r.billboardMode=e.AbstractMesh.BILLBOARDMODE_ALL;var n=new e.StandardMaterial(t+"Material",i);return n.emissiveColor=new e.Color3(1,1,1),r.material=n,r},__decorate([e.serializeAsVector3()],i.prototype,"customMeshPosition",void 0),__decorate([e.serialize()],i.prototype,"useCustomMeshPosition",void 0),__decorate([e.serialize()],i.prototype,"invert",void 0),__decorate([e.serializeAsMeshReference()],i.prototype,"mesh",void 0),__decorate([e.serialize()],i.prototype,"excludedMeshes",void 0),__decorate([e.serialize()],i.prototype,"exposure",void 0),__decorate([e.serialize()],i.prototype,"decay",void 0),__decorate([e.serialize()],i.prototype,"weight",void 0),__decorate([e.serialize()],i.prototype,"density",void 0),i})(e.PostProcess);e.VolumetricLightScatteringPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this;void 0===o&&(o=1),t.call(this,n.getEngine(),i),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._scene=n,this._depthTexture=n.enableDepthRenderer().getDepthMap(),r.grain_texture?this._grainTexture=r.grain_texture:this._createGrainTexture(),this._edgeBlur=r.edge_blur?r.edge_blur:0,this._grainAmount=r.grain_amount?r.grain_amount:0,this._chromaticAberration=r.chromatic_aberration?r.chromatic_aberration:0,this._distortion=r.distortion?r.distortion:0,this._highlightsGain=void 0!==r.dof_gain?r.dof_gain:-1,this._highlightsThreshold=r.dof_threshold?r.dof_threshold:1,this._dofDistance=void 0!==r.dof_focus_distance?r.dof_focus_distance:-1,this._dofAperture=r.dof_aperture?r.dof_aperture:1,this._dofDarken=r.dof_darken?r.dof_darken:0,this._dofPentagon=void 0===r.dof_pentagon||r.dof_pentagon,this._blurNoise=void 0===r.blur_noise||r.blur_noise,this._createChromaticAberrationPostProcess(o),this._createHighlightsPostProcess(o),this._createDepthOfFieldPostProcess(o/4),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),this.LensChromaticAberrationEffect,function(){return a._chromaticAberrationPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),this.HighlightsEnhancingEffect,function(){return a._highlightsPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),this.LensDepthOfFieldEffect,function(){return a._depthOfFieldPostProcess},(!0))),this._highlightsGain===-1&&this._disableEffect(this.HighlightsEnhancingEffect,null),n.postProcessRenderPipelineManager.addPipeline(this),s&&n.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,s)}return __extends(i,t),i.prototype.setEdgeBlur=function(e){this._edgeBlur=e},i.prototype.disableEdgeBlur=function(){this._edgeBlur=0},i.prototype.setGrainAmount=function(e){this._grainAmount=e},i.prototype.disableGrain=function(){this._grainAmount=0},i.prototype.setChromaticAberration=function(e){this._chromaticAberration=e},i.prototype.disableChromaticAberration=function(){this._chromaticAberration=0},i.prototype.setEdgeDistortion=function(e){this._distortion=e},i.prototype.disableEdgeDistortion=function(){this._distortion=0},i.prototype.setFocusDistance=function(e){this._dofDistance=e},i.prototype.disableDepthOfField=function(){this._dofDistance=-1},i.prototype.setAperture=function(e){this._dofAperture=e},i.prototype.setDarkenOutOfFocus=function(e){this._dofDarken=e},i.prototype.enablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n")},i.prototype.disablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect()},i.prototype.enableNoiseBlur=function(){this._blurNoise=!0},i.prototype.disableNoiseBlur=function(){this._blurNoise=!1},i.prototype.setHighlightsGain=function(e){this._highlightsGain=e},i.prototype.setHighlightsThreshold=function(e){this._highlightsGain===-1&&(this._highlightsGain=1),this._highlightsThreshold=e},i.prototype.disableHighlights=function(){this._highlightsGain=-1},i.prototype.dispose=function(e){void 0===e&&(e=!1),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=void 0,this._highlightsPostProcess=void 0,this._depthOfFieldPostProcess=void 0,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()},i.prototype._createChromaticAberrationPostProcess=function(t){var i=this;this._chromaticAberrationPostProcess=new e.PostProcess("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height"],[],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1)),this._chromaticAberrationPostProcess.onApply=function(e){e.setFloat("chromatic_aberration",i._chromaticAberration),e.setFloat("screen_width",i._scene.getEngine().getRenderingCanvas().width),e.setFloat("screen_height",i._scene.getEngine().getRenderingCanvas().height)}},i.prototype._createHighlightsPostProcess=function(t){var i=this;this._highlightsPostProcess=new e.PostProcess("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1),this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.onApply=function(e){e.setFloat("gain",i._highlightsGain),e.setFloat("threshold",i._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",i._chromaticAberrationPostProcess),e.setFloat("screen_width",i._scene.getEngine().getRenderingCanvas().width),e.setFloat("screen_height",i._scene.getEngine().getRenderingCanvas().height)}},i.prototype._createDepthOfFieldPostProcess=function(t){var i=this;this._depthOfFieldPostProcess=new e.PostProcess("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],t,null,e.Texture.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),(!1)),this._depthOfFieldPostProcess.onApply=function(e){e.setTexture("depthSampler",i._depthTexture),e.setTexture("grainSampler",i._grainTexture),e.setTextureFromPostProcess("textureSampler",i._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",i._depthOfFieldPostProcess),e.setFloat("grain_amount",i._grainAmount),e.setBool("blur_noise",i._blurNoise),e.setFloat("screen_width",i._scene.getEngine().getRenderingCanvas().width),e.setFloat("screen_height",i._scene.getEngine().getRenderingCanvas().height),e.setFloat("distortion",i._distortion),e.setBool("dof_enabled",i._dofDistance!==-1),e.setFloat("screen_distance",1/(.1-1/i._dofDistance)),e.setFloat("aperture",i._dofAperture),e.setFloat("darken",i._dofDarken),e.setFloat("edge_blur",i._edgeBlur),e.setBool("highlights",i._highlightsGain!==-1),e.setFloat("near",i._scene.activeCamera.minZ),e.setFloat("far",i._scene.activeCamera.maxZ)}},i.prototype._createGrainTexture=function(){var t=512;this._grainTexture=new e.DynamicTexture("LensNoiseTexture",t,this._scene,(!1),e.Texture.BILINEAR_SAMPLINGMODE),this._grainTexture.wrapU=e.Texture.WRAP_ADDRESSMODE,this._grainTexture.wrapV=e.Texture.WRAP_ADDRESSMODE;for(var i,r=this._grainTexture.getContext(),n=function(e,t){return Math.random()*(t-e)+e},o=0;o<t;o++)for(var s=0;s<t;s++)i=Math.floor(255*n(.42,.58)),r.fillStyle="rgb("+i+", "+i+", "+i+")",r.fillRect(o,s,1,1);this._grainTexture.update(!1)},i})(e.PostProcessRenderPipeline);e.LensRenderingPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){var c=this;t.call(this,i,"colorCorrection",null,["colorTable"],n,o,s,a,h),this._colorTableTexture=new e.Texture(r,o.getScene(),(!0),(!1),e.Texture.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=e.Texture.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=e.Texture.CLAMP_ADDRESSMODE,this.onApply=function(e){e.setTexture("colorTable",c._colorTableTexture)}}return __extends(i,t),i})(e.PostProcess);e.ColorCorrectionPostProcess=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o){t.call(this,i,r,o),this.interaxialDistance=n,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphFreeCamera"},i})(e.FreeCamera);e.AnaglyphFreeCamera=t;var i=(function(t){function i(i,r,n,o,s,a,h){t.call(this,i,r,n,o,s,h),this.interaxialDistance=a,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphArcRotateCamera"},i})(e.ArcRotateCamera);e.AnaglyphArcRotateCamera=i;var r=(function(t){function i(i,r,n,o){t.call(this,i,r,o),this.interaxialDistance=n,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphGamepadCamera"},i})(e.GamepadCamera);e.AnaglyphGamepadCamera=r;var n=(function(t){function i(i,r,n,o){t.call(this,i,r,o),this.interaxialDistance=n,this.setCameraRigMode(e.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"AnaglyphUniversalCamera"},i})(e.UniversalCamera);e.AnaglyphUniversalCamera=n;var o=(function(t){function i(i,r,n,o,s){t.call(this,i,r,s),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicFreeCamera"},i})(e.FreeCamera);e.StereoscopicFreeCamera=o;var s=(function(t){function i(i,r,n,o,s,a,h,c){t.call(this,i,r,n,o,s,c),this.interaxialDistance=a,this.isStereoscopicSideBySide=h,this.setCameraRigMode(h?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicArcRotateCamera"},i})(e.ArcRotateCamera);e.StereoscopicArcRotateCamera=s;var a=(function(t){function i(i,r,n,o,s){t.call(this,i,r,s),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicGamepadCamera"},i})(e.GamepadCamera);e.StereoscopicGamepadCamera=a;var h=(function(t){function i(i,r,n,o,s){t.call(this,i,r,s),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?e.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:e.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}return __extends(i,t),i.prototype.getTypeName=function(){return"StereoscopicUniversalCamera"},i})(e.UniversalCamera);e.StereoscopicUniversalCamera=h})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(r,n,o,s,a){var h=this;void 0===s&&(s=null),t.call(this,n.getEngine(),r),this.gaussCoeff=.3,this.gaussMean=1,this.gaussStandDev=.8,this.gaussMultiplier=4,this.exposure=1,this.minimumLuminance=1,this.maximumLuminance=1e20,this.luminanceIncreaserate=.5,this.luminanceDecreaseRate=.5,this.brightThreshold=.8,this._needUpdate=!0,this._scene=n,this._createBrightPassPostProcess(n,o),this._createDownSampleX4PostProcess(n,o),this._createGaussianBlurPostProcess(n,o),this._createTextureAdderPostProcess(n,o),this._createLuminanceGeneratorPostProcess(n),this._createHDRPostProcess(n,o),null===s?this._originalPostProcess=new e.PassPostProcess("hdr",o,null,e.Texture.BILINEAR_SAMPLINGMODE,n.getEngine(),(!1)):this._originalPostProcess=s,this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRPassPostProcess",function(){return h._originalPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRBrightPass",function(){return h._brightPassPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRDownSampleX4",function(){return h._downSampleX4PostProcess;
},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRGaussianBlurH",function(){return h._guassianBlurHPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRGaussianBlurV",function(){return h._guassianBlurVPostProcess},(!0))),this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRTextureAdder",function(){return h._textureAdderPostProcess},(!0)));for(var c=function(t){h.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDRDownSampler"+t,function(){return h._downSamplePostProcesses[t]},(!0)))},l=i.LUM_STEPS-1;l>=0;l--)c(l);this.addEffect(new e.PostProcessRenderEffect(n.getEngine(),"HDR",function(){return h._hdrPostProcess},(!0))),n.postProcessRenderPipelineManager.addPipeline(this),null!==a&&n.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(r,a),this.update()}return __extends(i,t),i.prototype.update=function(){this._needUpdate=!0},i.prototype.getCurrentLuminance=function(){return this._hdrCurrentLuminance},i.prototype.getOutputLuminance=function(){return this._hdrOutputLuminance},i.prototype.dispose=function(){this._originalPostProcess=void 0,this._brightPassPostProcess=void 0,this._downSampleX4PostProcess=void 0,this._guassianBlurHPostProcess=void 0,this._guassianBlurVPostProcess=void 0,this._textureAdderPostProcess=void 0;for(var e=i.LUM_STEPS-1;e>=0;e--)this._downSamplePostProcesses[e]=void 0;this._hdrPostProcess=void 0,this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras)},i.prototype._createHDRPostProcess=function(t,i){var r=this,n=0;this._hdrOutputLuminance=-1,this._hdrCurrentLuminance=1,this._hdrPostProcess=new e.PostProcess("hdr","hdr",["exposure","avgLuminance"],["otherSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define HDR"),this._hdrPostProcess.onApply=function(i){if(r._hdrOutputLuminance<0)r._hdrOutputLuminance=r._hdrCurrentLuminance;else{var o=(n-(n+t.getEngine().getDeltaTime()))/1e3;r._hdrCurrentLuminance<r._hdrOutputLuminance+r.luminanceDecreaseRate*o?r._hdrOutputLuminance+=r.luminanceDecreaseRate*o:r._hdrCurrentLuminance>r._hdrOutputLuminance-r.luminanceIncreaserate*o?r._hdrOutputLuminance-=r.luminanceIncreaserate*o:r._hdrOutputLuminance=r._hdrCurrentLuminance}r._hdrOutputLuminance=e.MathTools.Clamp(r._hdrOutputLuminance,r.minimumLuminance,r.maximumLuminance),n+=t.getEngine().getDeltaTime(),i.setTextureFromPostProcess("textureSampler",r._textureAdderPostProcess),i.setTextureFromPostProcess("otherSampler",r._originalPostProcess),i.setFloat("exposure",r.exposure),i.setFloat("avgLuminance",r._hdrOutputLuminance),r._needUpdate=!1}},i.prototype._createTextureAdderPostProcess=function(t,i){var r=this;this._textureAdderPostProcess=new e.PostProcess("hdr","hdr",[],["otherSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define TEXTURE_ADDER"),this._textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r._originalPostProcess)}},i.prototype._createDownSampleX4PostProcess=function(t,i){var r=this,n=new Array(32);this._downSampleX4PostProcess=new e.PostProcess("hdr","hdr",["dsOffsets"],[],i/4,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define DOWN_SAMPLE_X4"),this._downSampleX4PostProcess.onApply=function(e){if(r._needUpdate)for(var t=0,i=-2;i<2;i++)for(var o=-2;o<2;o++)n[t]=(i+.5)*(1/r._downSampleX4PostProcess.width),n[t+1]=(o+.5)*(1/r._downSampleX4PostProcess.height),t+=2;e.setArray2("dsOffsets",n)}},i.prototype._createBrightPassPostProcess=function(t,i){var r=this,n=new Array(8),o=function(e){if(r._needUpdate){var t=1/r._brightPassPostProcess.width,i=1/r._brightPassPostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i}e.setArray2("dsOffsets",n),e.setFloat("brightThreshold",r.brightThreshold)};this._brightPassPostProcess=new e.PostProcess("hdr","hdr",["dsOffsets","brightThreshold"],[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define BRIGHT_PASS"),this._brightPassPostProcess.onApply=o},i.prototype._createLuminanceGeneratorPostProcess=function(t){var r,n=this,o=i.LUM_STEPS,s=new Array(8),a=new Array(18);this._downSamplePostProcesses=new Array(o);var h=function(e,t){var i=1/e,r=1/t;s[0]=-.5*i,s[1]=.5*r,s[2]=.5*i,s[3]=.5*r,s[4]=-.5*i,s[5]=-.5*r,s[6]=.5*i,s[7]=-.5*r},c=function(e,t){for(var i=0,r=-1;r<2;r++)for(var n=-1;n<2;n++)a[i]=r/e,a[i+1]=n/t,i+=2},l=function(e){n._needUpdate&&h(n._textureAdderPostProcess.width,n._textureAdderPostProcess.height),e.setTextureFromPostProcess("textureSampler",n._textureAdderPostProcess),e.setArray2("lumOffsets",s)},u=function(e){var t=e;return function(e){h(n._downSamplePostProcesses[t].width,n._downSamplePostProcesses[t].height),c(n._downSamplePostProcesses[t].width,n._downSamplePostProcesses[t].height),r=.5/n._downSamplePostProcesses[t].width,e.setTextureFromPostProcess("textureSampler",n._downSamplePostProcesses[t+1]),e.setFloat("halfDestPixelSize",r),e.setArray2("dsOffsets",a)}},d=function(i){var r=t.getEngine().readPixels(0,0,1,1),o=new e.Vector4(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(r[0]*o.x+r[1]*o.y+r[2]*o.z+r[3]*o.w)/100},f={width:Math.pow(3,o-1),height:Math.pow(3,o-1)};this._downSamplePostProcesses[o-1]=new e.PostProcess("hdr","hdr",["lumOffsets"],[],f,null,e.Texture.NEAREST_SAMPLINGMODE,t.getEngine(),(!1),"#define LUMINANCE_GENERATOR",e.Engine.TEXTURETYPE_FLOAT),this._downSamplePostProcesses[o-1].onApply=l;for(var p=o-2;p>=0;p--){var _=Math.pow(3,p);f={width:_,height:_};var m="#define DOWN_SAMPLE\n";0===p&&(m+="#define FINAL_DOWN_SAMPLE\n"),this._downSamplePostProcesses[p]=new e.PostProcess("hdr","hdr",["dsOffsets","halfDestPixelSize"],[],f,null,e.Texture.NEAREST_SAMPLINGMODE,t.getEngine(),(!1),m,e.Engine.TEXTURETYPE_FLOAT),this._downSamplePostProcesses[p].onApply=u(p),0===p&&(this._downSamplePostProcesses[p].onAfterRender=d)}},i.prototype._createGaussianBlurPostProcess=function(t,i){var r=this,n=new Array(9),o=new Array(9),s=new Array(9),a=["blurOffsets","blurWeights","multiplier"],h=function(e){for(var i={width:t.getEngine().getRenderWidth(),height:t.getEngine().getRenderHeight()},r=0;r<9;r++){var s=(r-4)*(1/(e===!0?i.height:i.width));e?o[r]=s:n[r]=s}},c=function(){for(var e=0,t=0;t<9;t++)e=(t-4)/4,s[t]=r.gaussCoeff*(1/Math.sqrt(2*Math.PI*r.gaussStandDev))*Math.exp(-((e-r.gaussMean)*(e-r.gaussMean))/(2*r.gaussStandDev*r.gaussStandDev))},l=function(e){return function(t){r._needUpdate&&(c(),h(e)),t.setArray("blurOffsets",e?o:n),t.setArray("blurWeights",s),t.setFloat("multiplier",r.gaussMultiplier)}};this._guassianBlurHPostProcess=new e.PostProcess("hdr","hdr",a,[],i/4,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_H"),this._guassianBlurHPostProcess.onApply=l(!1),this._guassianBlurVPostProcess=new e.PostProcess("hdr","hdr",a,[],i/4,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_V"),this._guassianBlurVPostProcess.onApply=l(!0)},i.LUM_STEPS=6,i})(e.PostProcessRenderPipeline);e.HDRRenderingPipeline=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.edges=new Array,this.edgesConnectedCount=0}return e})(),i=(function(){function i(e,t,i){void 0===t&&(t=.95),void 0===i&&(i=!1),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),this._generateEdgesLines()}return i.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new e.ShaderMaterial("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},i.prototype.dispose=function(){var t=this._buffers[e.VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[e.VertexBuffer.PositionKind]=null),t=this._buffers[e.VertexBuffer.NormalKind],t&&(t.dispose(),this._buffers[e.VertexBuffer.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},i.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},i.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)?1:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)?2:-1},i.prototype._checkEdge=function(t,i,r,n,o){var s;if(void 0===i)s=!0;else{var a=e.Vector3.Dot(r[t],r[i]);s=a<this._epsilon}if(s){var h=this._linesPositions.length/3,c=n.subtract(o);c.normalize(),this._linesPositions.push(n.x),this._linesPositions.push(n.y),this._linesPositions.push(n.z),this._linesPositions.push(n.x),this._linesPositions.push(n.y),this._linesPositions.push(n.z),this._linesPositions.push(o.x),this._linesPositions.push(o.y),this._linesPositions.push(o.z),this._linesPositions.push(o.x),this._linesPositions.push(o.y),this._linesPositions.push(o.z),this._linesNormals.push(o.x),this._linesNormals.push(o.y),this._linesNormals.push(o.z),this._linesNormals.push(-1),this._linesNormals.push(o.x),this._linesNormals.push(o.y),this._linesNormals.push(o.z),this._linesNormals.push(1),this._linesNormals.push(n.x),this._linesNormals.push(n.y),this._linesNormals.push(n.z),this._linesNormals.push(-1),this._linesNormals.push(n.x),this._linesNormals.push(n.y),this._linesNormals.push(n.z),this._linesNormals.push(1),this._linesIndices.push(h),this._linesIndices.push(h+1),this._linesIndices.push(h+2),this._linesIndices.push(h),this._linesIndices.push(h+2),this._linesIndices.push(h+3)}},i.prototype._generateEdgesLines=function(){var i,r,n=this._source.getVerticesData(e.VertexBuffer.PositionKind),o=this._source.getIndices(),s=new Array,a=new Array;for(i=0;i<o.length;i+=3){r=new t;var h=o[i],c=o[i+1],l=o[i+2];r.p0=new e.Vector3(n[3*h],n[3*h+1],n[3*h+2]),r.p1=new e.Vector3(n[3*c],n[3*c+1],n[3*c+2]),r.p2=new e.Vector3(n[3*l],n[3*l+1],n[3*l+2]);var u=e.Vector3.Cross(r.p1.subtract(r.p0),r.p2.subtract(r.p1));u.normalize(),a.push(u),s.push(r)}for(i=0;i<s.length;i++){r=s[i];for(var d=i+1;d<s.length;d++){var f=s[d];if(3===r.edgesConnectedCount)break;if(3!==f.edgesConnectedCount)for(var p=o[3*d],_=o[3*d+1],m=o[3*d+2],g=0;g<3;g++){var v;if(void 0===r.edges[g]){switch(g){case 0:v=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p0,r.p1,f.p0,f.p1,f.p2):this._processEdgeForAdjacencies(o[3*i],o[3*i+1],p,_,m);break;case 1:v=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p1,r.p2,f.p0,f.p1,f.p2):this._processEdgeForAdjacencies(o[3*i+1],o[3*i+2],p,_,m);break;case 2:v=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p2,r.p0,f.p0,f.p1,f.p2):this._processEdgeForAdjacencies(o[3*i+2],o[3*i],p,_,m)}if(v!==-1&&(r.edges[g]=d,f.edges[v]=i,r.edgesConnectedCount++,f.edgesConnectedCount++,3===r.edgesConnectedCount))break}}}}for(i=0;i<s.length;i++){var y=s[i];this._checkEdge(i,y.edges[0],a,y.p0,y.p1),this._checkEdge(i,y.edges[1],a,y.p1,y.p2),this._checkEdge(i,y.edges[2],a,y.p2,y.p0)}var x=this._source.getScene().getEngine();this._buffers[e.VertexBuffer.PositionKind]=new e.VertexBuffer(x,this._linesPositions,e.VertexBuffer.PositionKind,(!1)),this._buffers[e.VertexBuffer.NormalKind]=new e.VertexBuffer(x,this._linesNormals,e.VertexBuffer.NormalKind,(!1),(!1),4),this._ib=x.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length},i.prototype.render=function(){if(this._lineShader.isReady()){var t=this._source.getScene(),i=t.getEngine();this._lineShader._preBind(),i.bindBuffers(this._buffers,this._ib,this._lineShader.getEffect()),t.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),t.activeCamera.mode===e.Camera.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",i.getAspectRatio(t.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),i.draw(!0,0,this._indicesCount),this._lineShader.unbind(),i.setDepthWrite(!0)}},i})();e.EdgesRenderer=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"})(e.TonemappingOperator||(e.TonemappingOperator={}));var t=e.TonemappingOperator,i=(function(i){function r(r,n,o,s,a,h,c){var l=this;void 0===a&&(a=e.Texture.BILINEAR_SAMPLINGMODE),void 0===c&&(c=e.Engine.TEXTURETYPE_UNSIGNED_INT),i.call(this,r,"tonemap",["_ExposureAdjustment"],null,1,s,a,h,!0,u,c),this._operator=n,this.exposureAdjustment=o;var u="#define ";this._operator===t.Hable?u+="HABLE_TONEMAPPING":this._operator===t.Reinhard?u+="REINHARD_TONEMAPPING":this._operator===t.HejiDawson?u+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===t.Photographic&&(u+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(u),this.onApply=function(e){e.setFloat("_ExposureAdjustment",l.exposureAdjustment)}}return __extends(r,i),r})(e.PostProcess);e.TonemapPostProcess=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n){var o=this;void 0===n&&(n=!0),this.name=t,this._viewMatrix=e.Matrix.Identity(),this._target=e.Vector3.Zero(),this._add=e.Vector3.Zero(),this.invertYAxis=!1,this.position=e.Vector3.Zero(),this._scene=r,this._scene.reflectionProbes.push(this),this._renderTargetTexture=new e.RenderTargetTexture(t,i,r,n,(!0),e.Engine.TEXTURETYPE_UNSIGNED_INT,(!0)),this._renderTargetTexture.onBeforeRenderObservable.add((function(t){switch(t){case 0:o._add.copyFromFloats(1,0,0);break;case 1:o._add.copyFromFloats(-1,0,0);break;case 2:o._add.copyFromFloats(0,o.invertYAxis?1:-1,0);break;case 3:o._add.copyFromFloats(0,o.invertYAxis?-1:1,0);break;case 4:o._add.copyFromFloats(0,0,1);break;case 5:o._add.copyFromFloats(0,0,-1)}o._attachedMesh&&o.position.copyFrom(o._attachedMesh.getAbsolutePosition()),o.position.addToRef(o._add,o._target),e.Matrix.LookAtLHToRef(o.position,o._target,e.Vector3.Up(),o._viewMatrix),r.setTransformMatrix(o._viewMatrix,o._projectionMatrix)})),this._renderTargetTexture.onAfterUnbindObservable.add((function(){r.updateTransformMatrix(!0)})),this._projectionMatrix=e.Matrix.PerspectiveFovLH(Math.PI/2,1,r.activeCamera.minZ,r.activeCamera.maxZ)}return Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(e){this._renderTargetTexture.refreshRate=e},enumerable:!0,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},enumerable:!0,configurable:!0}),t.prototype.attachToMesh=function(e){this._attachedMesh=e},t.prototype.dispose=function(){var e=this._scene.reflectionProbes.indexOf(this);e!==-1&&this._scene.reflectionProbes.splice(e,1),this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null)},t})();e.ReflectionProbe=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r,n,o,s,a){this.idx=0,this.color=new e.Color4(1,1,1,1),this.position=e.Vector3.Zero(),this.rotation=e.Vector3.Zero(),this.scaling=new e.Vector3(1,1,1),this.uvs=new e.Vector4(0,0,1,1),this.velocity=e.Vector3.Zero(),this.alive=!0,this.isVisible=!0,this._pos=0,this.shapeId=0,this.idxInShape=0,this.idx=t,this._pos=i,this._model=r,this.shapeId=n,this.idxInShape=o,this._sps=s,a&&(this._modelBoundingInfo=a,this._boundingInfo=new e.BoundingInfo(a.minimum,a.maximum))}return Object.defineProperty(t.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!0,configurable:!0}),t.prototype.intersectsMesh=function(t){return!(!this._boundingInfo||!t._boundingInfo)&&(this._sps._bSphereOnly?e.BoundingSphere.Intersects(this._boundingInfo.boundingSphere,t._boundingInfo.boundingSphere):this._boundingInfo.intersects(t._boundingInfo,!1))},t})();e.SolidParticle=t;var i=(function(){function e(e,t,i,r,n){this.shapeID=e,this._shape=t,this._shapeUV=i,this._positionFunction=r,this._vertexFunction=n}return e})();e.ModelShape=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t,i,r){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!0,this.counter=0,this.vars={},this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._shapeCounter=0,this._copy=new e.SolidParticle(null,null,null,null,null,null),this._color=new e.Color4(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._cam_axisZ=e.Vector3.Zero(),this._cam_axisY=e.Vector3.Zero(),this._cam_axisX=e.Vector3.Zero(),this._axisX=e.Axis.X,this._axisY=e.Axis.Y,this._axisZ=e.Axis.Z,this._camDir=e.Vector3.Zero(),this._rotMatrix=new e.Matrix,this._invertMatrix=new e.Matrix,this._rotated=e.Vector3.Zero(),this._quaternion=new e.Quaternion,this._vertex=e.Vector3.Zero(),this._normal=e.Vector3.Zero(),this._yaw=0,this._pitch=0,this._roll=0,this._halfroll=0,this._halfpitch=0,this._halfyaw=0,this._sinRoll=0,this._cosRoll=0,this._sinPitch=0,this._cosPitch=0,this._sinYaw=0,this._cosYaw=0,this._w=0,this._minimum=e.Tmp.Vector3[0],this._maximum=e.Tmp.Vector3[1],this._scale=e.Tmp.Vector3[2],this._translation=e.Tmp.Vector3[3],this._minBbox=e.Tmp.Vector3[4],this._maxBbox=e.Tmp.Vector3[5],this._particlesIntersect=!1,this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this.name=t,this._scene=i,this._camera=i.activeCamera,this._pickable=!!r&&r.isPickable,this._particlesIntersect=!!r&&r.particleIntersection,this._bSphereOnly=!!r&&r.boundingSphereOnly,this._bSphereRadiusFactor=r&&r.bSphereRadiusFactor?r.bSphereRadiusFactor:1,r&&r.updatable?this._updatable=r.updatable:this._updatable=!0,this._pickable&&(this.pickedParticles=[])}return t.prototype.buildMesh=function(){if(0===this.nbParticles){var t=e.MeshBuilder.CreateDisc("",{radius:1,tessellation:3},this._scene);this.addShape(t,1),t.dispose()}this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),this.recomputeNormals&&e.VertexData.ComputeNormals(this._positions32,this._indices,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals);var i=new e.VertexData;i.set(this._positions32,e.VertexBuffer.PositionKind),i.indices=this._indices,i.set(this._normals32,e.VertexBuffer.NormalKind),this._uvs32&&i.set(this._uvs32,e.VertexBuffer.UVKind),this._colors32&&i.set(this._colors32,e.VertexBuffer.ColorKind);var r=new e.Mesh(this.name,this._scene);return i.applyToMesh(r,this._updatable),this.mesh=r,this.mesh.isPickable=this._pickable,this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),r},t.prototype.digest=function(t,i){var r=i&&i.facetNb||1,n=i&&i.number,o=i&&i.delta||0,s=t.getVerticesData(e.VertexBuffer.PositionKind),a=t.getIndices(),h=t.getVerticesData(e.VertexBuffer.UVKind),c=t.getVerticesData(e.VertexBuffer.ColorKind),l=t.getVerticesData(e.VertexBuffer.NormalKind),u=0,d=a.length/3;n?(n=n>d?d:n,r=Math.round(d/n),o=0):r=r>d?d:r;for(var f=[],p=[],_=[],m=[],g=e.Tmp.Vector3[0],v=r;u<d;){r=v+Math.floor((1+o)*Math.random()),u>d-r&&(r=d-u),f.length=0,p.length=0,_.length=0,m.length=0;for(var y=0,x=3*u;x<3*(u+r);x++){p.push(y);var b=a[x];f.push(s[3*b],s[3*b+1],s[3*b+2]),h&&_.push(h[2*b],h[2*b+1]),c&&m.push(c[4*b],c[4*b+1],c[4*b+2],c[4*b+3]),y++}var A,T=this.nbParticles,E=this._posToShape(f),P=this._uvsToShapeUV(_);for(A=0;A<E.length;A++)g.addInPlace(E[A]);for(g.scaleInPlace(1/E.length),A=0;A<E.length;A++)E[A].subtractInPlace(g);var S;this._particlesIntersect&&(S=new e.BoundingInfo(g,g));var M=new e.ModelShape(this._shapeCounter,E,P,null,null);this._meshBuilder(this._index,E,this._positions,p,this._indices,_,this._uvs,m,this._colors,l,this._normals,T,0,null),this._addParticle(T,this._positions.length,M,this._shapeCounter,0,S),this.particles[this.nbParticles].position.addInPlace(g),this._index+=E.length,T++,this.nbParticles++,this._shapeCounter++,u+=r}return this},t.prototype._resetCopy=function(){this._copy.position.x=0,this._copy.position.y=0,this._copy.position.z=0,this._copy.rotation.x=0,this._copy.rotation.y=0,this._copy.rotation.z=0,this._copy.rotationQuaternion=null,this._copy.scaling.x=1,this._copy.scaling.y=1,this._copy.scaling.z=1,this._copy.uvs.x=0,this._copy.uvs.y=0,this._copy.uvs.z=1,this._copy.uvs.w=1,this._copy.color=null},t.prototype._meshBuilder=function(t,i,r,n,o,s,a,h,c,l,u,d,f,p){var _,m=0,g=0,v=0;for(this._resetCopy(),p&&p.positionFunction&&p.positionFunction(this._copy,d,f),this._copy.rotationQuaternion?this._quaternion.copyFrom(this._copy.rotationQuaternion):(this._yaw=this._copy.rotation.y,this._pitch=this._copy.rotation.x,this._roll=this._copy.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix(),_=0;_<i.length;_++)this._vertex.x=i[_].x,this._vertex.y=i[_].y,this._vertex.z=i[_].z,p&&p.vertexFunction&&p.vertexFunction(this._copy,this._vertex,_),this._vertex.x*=this._copy.scaling.x,this._vertex.y*=this._copy.scaling.y,this._vertex.z*=this._copy.scaling.z,e.Vector3.TransformCoordinatesToRef(this._vertex,this._rotMatrix,this._rotated),r.push(this._copy.position.x+this._rotated.x,this._copy.position.y+this._rotated.y,this._copy.position.z+this._rotated.z),s&&(a.push((this._copy.uvs.z-this._copy.uvs.x)*s[m]+this._copy.uvs.x,(this._copy.uvs.w-this._copy.uvs.y)*s[m+1]+this._copy.uvs.y),m+=2),this._copy.color?this._color=this._copy.color:h&&void 0!==h[g]?(this._color.r=h[g],this._color.g=h[g+1],this._color.b=h[g+2],this._color.a=h[g+3]):(this._color.r=1,this._color.g=1,this._color.b=1,this._color.a=1),c.push(this._color.r,this._color.g,this._color.b,this._color.a),g+=4,!this.recomputeNormals&&l&&(this._normal.x=l[v],this._normal.y=l[v+1],this._normal.z=l[v+2],e.Vector3.TransformCoordinatesToRef(this._normal,this._rotMatrix,this._normal),u.push(this._normal.x,this._normal.y,this._normal.z),v+=3);for(_=0;_<n.length;_++)o.push(t+n[_]);if(this._pickable){var y=n.length/3;for(_=0;_<y;_++)this.pickedParticles.push({idx:d,faceId:_})}},t.prototype._posToShape=function(t){for(var i=[],r=0;r<t.length;r+=3)i.push(new e.Vector3(t[r],t[r+1],t[r+2]));return i},t.prototype._uvsToShapeUV=function(e){var t=[];if(e)for(var i=0;i<e.length;i++)t.push(e[i]);return t},t.prototype._addParticle=function(t,i,r,n,o,s){this.particles.push(new e.SolidParticle(t,i,r,n,o,this,s))},t.prototype.addShape=function(t,i,r){var n,o=t.getVerticesData(e.VertexBuffer.PositionKind),s=t.getIndices(),a=t.getVerticesData(e.VertexBuffer.UVKind),h=t.getVerticesData(e.VertexBuffer.ColorKind),c=t.getVerticesData(e.VertexBuffer.NormalKind);this._particlesIntersect&&(n=t.getBoundingInfo());for(var l=this._posToShape(o),u=this._uvsToShapeUV(a),d=r?r.positionFunction:null,f=r?r.vertexFunction:null,p=new e.ModelShape(this._shapeCounter,l,u,d,f),_=this.nbParticles,m=0;m<i;m++)this._meshBuilder(this._index,l,this._positions,s,this._indices,a,this._uvs,h,this._colors,c,this._normals,_,m,r),this._updatable&&this._addParticle(_,this._positions.length,p,this._shapeCounter,m,n),this._index+=l.length,_++;return this.nbParticles+=i,this._shapeCounter++,this._shapeCounter-1},t.prototype._rebuildParticle=function(t){this._resetCopy(),t._model._positionFunction&&t._model._positionFunction(this._copy,t.idx,t.idxInShape),this._copy.rotationQuaternion?this._quaternion.copyFrom(this._copy.rotationQuaternion):(this._yaw=this._copy.rotation.y,this._pitch=this._copy.rotation.x,this._roll=this._copy.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix(),this._shape=t._model._shape;for(var i=0;i<this._shape.length;i++)this._vertex.x=this._shape[i].x,this._vertex.y=this._shape[i].y,this._vertex.z=this._shape[i].z,t._model._vertexFunction&&t._model._vertexFunction(this._copy,this._vertex,i),this._vertex.x*=this._copy.scaling.x,this._vertex.y*=this._copy.scaling.y,this._vertex.z*=this._copy.scaling.z,e.Vector3.TransformCoordinatesToRef(this._vertex,this._rotMatrix,this._rotated),this._positions32[t._pos+3*i]=this._copy.position.x+this._rotated.x,this._positions32[t._pos+3*i+1]=this._copy.position.y+this._rotated.y,this._positions32[t._pos+3*i+2]=this._copy.position.z+this._rotated.z;t.position.x=0,t.position.y=0,t.position.z=0,t.rotation.x=0,t.rotation.y=0,t.rotation.z=0,t.rotationQuaternion=null,t.scaling.x=1,t.scaling.y=1,t.scaling.z=1},t.prototype.rebuildMesh=function(){for(var t=0;t<this.particles.length;t++)this._rebuildParticle(this.particles[t]);this.mesh.updateVerticesData(e.VertexBuffer.PositionKind,this._positions32,!1,!1)},t.prototype.setParticles=function(t,i,r){if(void 0===t&&(t=0),void 0===i&&(i=this.nbParticles-1),void 0===r&&(r=!0),this._updatable){this.beforeUpdateParticles(t,i,r),this._cam_axisX.x=1,this._cam_axisX.y=0,this._cam_axisX.z=0,this._cam_axisY.x=0,this._cam_axisY.y=1,this._cam_axisY.z=0,this._cam_axisZ.x=0,this._cam_axisZ.y=0,this._cam_axisZ.z=1,this.billboard&&this.mesh._worldMatrix.decompose(this._scale,this._quaternion,this._translation)&&(this._quaternionToRotationMatrix(),this._rotMatrix.invertToRef(this._invertMatrix),this._camera._currentTarget.subtractToRef(this._camera.globalPosition,this._camDir),e.Vector3.TransformCoordinatesToRef(this._camDir,this._invertMatrix,this._cam_axisZ),this._cam_axisZ.normalize(),e.Vector3.CrossToRef(this._cam_axisZ,this._axisX,this._cam_axisY),e.Vector3.CrossToRef(this._cam_axisY,this._cam_axisZ,this._cam_axisX),this._cam_axisY.normalize(),this._cam_axisX.normalize()),e.Matrix.IdentityToRef(this._rotMatrix);var n=0,o=0,s=0,a=0,h=0,c=0,l=0;this._computeBoundingBox&&(e.Vector3.FromFloatsToRef(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,this._minimum),e.Vector3.FromFloatsToRef(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE,this._maximum)),i=i>this.nbParticles-1?this.nbParticles-1:i;for(var u=t;u<=i;u++){if(this._particle=this.particles[u],this._shape=this._particle._model._shape,this._shapeUV=this._particle._model._shapeUV,this.updateParticle(this._particle),this._particle.isVisible)for(this.billboard&&(this._particle.rotation.x=0,this._particle.rotation.y=0),(this._computeParticleRotation||this.billboard)&&(this._particle.rotationQuaternion?this._quaternion.copyFrom(this._particle.rotationQuaternion):(this._yaw=this._particle.rotation.y,this._pitch=this._particle.rotation.x,this._roll=this._particle.rotation.z,this._quaternionRotationYPR()),this._quaternionToRotationMatrix()),l=0;l<this._shape.length;l++)n=o+3*l,s=a+4*l,h=c+2*l,this._vertex.x=this._shape[l].x,this._vertex.y=this._shape[l].y,this._vertex.z=this._shape[l].z,this._computeParticleVertex&&this.updateParticleVertex(this._particle,this._vertex,l),this._vertex.x*=this._particle.scaling.x,this._vertex.y*=this._particle.scaling.y,this._vertex.z*=this._particle.scaling.z,this._w=this._vertex.x*this._rotMatrix.m[3]+this._vertex.y*this._rotMatrix.m[7]+this._vertex.z*this._rotMatrix.m[11]+this._rotMatrix.m[15],this._rotated.x=(this._vertex.x*this._rotMatrix.m[0]+this._vertex.y*this._rotMatrix.m[4]+this._vertex.z*this._rotMatrix.m[8]+this._rotMatrix.m[12])/this._w,this._rotated.y=(this._vertex.x*this._rotMatrix.m[1]+this._vertex.y*this._rotMatrix.m[5]+this._vertex.z*this._rotMatrix.m[9]+this._rotMatrix.m[13])/this._w,this._rotated.z=(this._vertex.x*this._rotMatrix.m[2]+this._vertex.y*this._rotMatrix.m[6]+this._vertex.z*this._rotMatrix.m[10]+this._rotMatrix.m[14])/this._w,this._positions32[n]=this._particle.position.x+this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._positions32[n+1]=this._particle.position.y+this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._positions32[n+2]=this._particle.position.z+this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z,this._computeBoundingBox&&(this._positions32[n]<this._minimum.x&&(this._minimum.x=this._positions32[n]),this._positions32[n]>this._maximum.x&&(this._maximum.x=this._positions32[n]),this._positions32[n+1]<this._minimum.y&&(this._minimum.y=this._positions32[n+1]),this._positions32[n+1]>this._maximum.y&&(this._maximum.y=this._positions32[n+1]),this._positions32[n+2]<this._minimum.z&&(this._minimum.z=this._positions32[n+2]),this._positions32[n+2]>this._maximum.z&&(this._maximum.z=this._positions32[n+2])),this._computeParticleVertex||(this._normal.x=this._fixedNormal32[n],this._normal.y=this._fixedNormal32[n+1],this._normal.z=this._fixedNormal32[n+2],this._w=this._normal.x*this._rotMatrix.m[3]+this._normal.y*this._rotMatrix.m[7]+this._normal.z*this._rotMatrix.m[11]+this._rotMatrix.m[15],this._rotated.x=(this._normal.x*this._rotMatrix.m[0]+this._normal.y*this._rotMatrix.m[4]+this._normal.z*this._rotMatrix.m[8]+this._rotMatrix.m[12])/this._w,this._rotated.y=(this._normal.x*this._rotMatrix.m[1]+this._normal.y*this._rotMatrix.m[5]+this._normal.z*this._rotMatrix.m[9]+this._rotMatrix.m[13])/this._w,this._rotated.z=(this._normal.x*this._rotMatrix.m[2]+this._normal.y*this._rotMatrix.m[6]+this._normal.z*this._rotMatrix.m[10]+this._rotMatrix.m[14])/this._w,this._normals32[n]=this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,this._normals32[n+1]=this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,this._normals32[n+2]=this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z),this._computeParticleColor&&(this._colors32[s]=this._particle.color.r,this._colors32[s+1]=this._particle.color.g,this._colors32[s+2]=this._particle.color.b,this._colors32[s+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[h]=this._shapeUV[2*l]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[h+1]=this._shapeUV[2*l+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);else for(l=0;l<this._shape.length;l++)n=o+3*l,s=a+4*l,h=c+2*l,this._positions32[n]=this._camera.position.x,this._positions32[n+1]=this._camera.position.y,this._positions32[n+2]=this._camera.position.z,this._normals32[n]=0,this._normals32[n+1]=0,this._normals32[n+2]=0,this._computeParticleColor&&(this._colors32[s]=this._particle.color.r,this._colors32[s+1]=this._particle.color.g,this._colors32[s+2]=this._particle.color.b,this._colors32[s+3]=this._particle.color.a),this._computeParticleTexture&&(this._uvs32[h]=this._shapeUV[2*l]*(this._particle.uvs.z-this._particle.uvs.x)+this._particle.uvs.x,this._uvs32[h+1]=this._shapeUV[2*l+1]*(this._particle.uvs.w-this._particle.uvs.y)+this._particle.uvs.y);if(this._particlesIntersect){var d=this._particle._boundingInfo,f=d.boundingBox,p=d.boundingSphere;if(!this._bSphereOnly){for(var _=0;_<f.vectors.length;_++)this._vertex.x=this._particle._modelBoundingInfo.boundingBox.vectors[_].x*this._particle.scaling.x,this._vertex.y=this._particle._modelBoundingInfo.boundingBox.vectors[_].y*this._particle.scaling.y,
this._vertex.z=this._particle._modelBoundingInfo.boundingBox.vectors[_].z*this._particle.scaling.z,this._w=this._vertex.x*this._rotMatrix.m[3]+this._vertex.y*this._rotMatrix.m[7]+this._vertex.z*this._rotMatrix.m[11]+this._rotMatrix.m[15],this._rotated.x=(this._vertex.x*this._rotMatrix.m[0]+this._vertex.y*this._rotMatrix.m[4]+this._vertex.z*this._rotMatrix.m[8]+this._rotMatrix.m[12])/this._w,this._rotated.y=(this._vertex.x*this._rotMatrix.m[1]+this._vertex.y*this._rotMatrix.m[5]+this._vertex.z*this._rotMatrix.m[9]+this._rotMatrix.m[13])/this._w,this._rotated.z=(this._vertex.x*this._rotMatrix.m[2]+this._vertex.y*this._rotMatrix.m[6]+this._vertex.z*this._rotMatrix.m[10]+this._rotMatrix.m[14])/this._w,f.vectors[_].x=this._particle.position.x+this._cam_axisX.x*this._rotated.x+this._cam_axisY.x*this._rotated.y+this._cam_axisZ.x*this._rotated.z,f.vectors[_].y=this._particle.position.y+this._cam_axisX.y*this._rotated.x+this._cam_axisY.y*this._rotated.y+this._cam_axisZ.y*this._rotated.z,f.vectors[_].z=this._particle.position.z+this._cam_axisX.z*this._rotated.x+this._cam_axisY.z*this._rotated.y+this._cam_axisZ.z*this._rotated.z;f._update(this.mesh._worldMatrix)}this._minBbox.x=this._particle._modelBoundingInfo.minimum.x*this._particle.scaling.x,this._minBbox.y=this._particle._modelBoundingInfo.minimum.y*this._particle.scaling.y,this._minBbox.z=this._particle._modelBoundingInfo.minimum.z*this._particle.scaling.z,this._maxBbox.x=this._particle._modelBoundingInfo.maximum.x*this._particle.scaling.x,this._maxBbox.y=this._particle._modelBoundingInfo.maximum.y*this._particle.scaling.y,this._maxBbox.z=this._particle._modelBoundingInfo.maximum.z*this._particle.scaling.z,p.center.x=this._particle.position.x+.5*(this._minBbox.x+this._maxBbox.x),p.center.y=this._particle.position.y+.5*(this._minBbox.y+this._maxBbox.y),p.center.z=this._particle.position.z+.5*(this._minBbox.z+this._maxBbox.z),p.radius=.5*this._bSphereRadiusFactor*Math.sqrt((this._maxBbox.x-this._minBbox.x)*(this._maxBbox.x-this._minBbox.x)+(this._maxBbox.y-this._minBbox.y)*(this._maxBbox.y-this._minBbox.y)+(this._maxBbox.z-this._minBbox.z)*(this._maxBbox.z-this._minBbox.z)),p._update(this.mesh._worldMatrix)}o=n+3,a=s+4,c=h+2}if(r&&(this._computeParticleColor&&this.mesh.updateVerticesData(e.VertexBuffer.ColorKind,this._colors32,!1,!1),this._computeParticleTexture&&this.mesh.updateVerticesData(e.VertexBuffer.UVKind,this._uvs32,!1,!1),this.mesh.updateVerticesData(e.VertexBuffer.PositionKind,this._positions32,!1,!1),!this.mesh.areNormalsFrozen)){if(this._computeParticleVertex){e.VertexData.ComputeNormals(this._positions32,this._indices,this._normals32);for(var m=0;m<this._normals32.length;m++)this._fixedNormal32[m]=this._normals32[m]}this.mesh.updateVerticesData(e.VertexBuffer.NormalKind,this._normals32,!1,!1)}this._computeBoundingBox&&(this.mesh._boundingInfo=new e.BoundingInfo(this._minimum,this._maximum),this.mesh._boundingInfo.update(this.mesh._worldMatrix)),this.afterUpdateParticles(t,i,r)}},t.prototype._quaternionRotationYPR=function(){this._halfroll=.5*this._roll,this._halfpitch=.5*this._pitch,this._halfyaw=.5*this._yaw,this._sinRoll=Math.sin(this._halfroll),this._cosRoll=Math.cos(this._halfroll),this._sinPitch=Math.sin(this._halfpitch),this._cosPitch=Math.cos(this._halfpitch),this._sinYaw=Math.sin(this._halfyaw),this._cosYaw=Math.cos(this._halfyaw),this._quaternion.x=this._cosYaw*this._sinPitch*this._cosRoll+this._sinYaw*this._cosPitch*this._sinRoll,this._quaternion.y=this._sinYaw*this._cosPitch*this._cosRoll-this._cosYaw*this._sinPitch*this._sinRoll,this._quaternion.z=this._cosYaw*this._cosPitch*this._sinRoll-this._sinYaw*this._sinPitch*this._cosRoll,this._quaternion.w=this._cosYaw*this._cosPitch*this._cosRoll+this._sinYaw*this._sinPitch*this._sinRoll},t.prototype._quaternionToRotationMatrix=function(){this._rotMatrix.m[0]=1-2*(this._quaternion.y*this._quaternion.y+this._quaternion.z*this._quaternion.z),this._rotMatrix.m[1]=2*(this._quaternion.x*this._quaternion.y+this._quaternion.z*this._quaternion.w),this._rotMatrix.m[2]=2*(this._quaternion.z*this._quaternion.x-this._quaternion.y*this._quaternion.w),this._rotMatrix.m[3]=0,this._rotMatrix.m[4]=2*(this._quaternion.x*this._quaternion.y-this._quaternion.z*this._quaternion.w),this._rotMatrix.m[5]=1-2*(this._quaternion.z*this._quaternion.z+this._quaternion.x*this._quaternion.x),this._rotMatrix.m[6]=2*(this._quaternion.y*this._quaternion.z+this._quaternion.x*this._quaternion.w),this._rotMatrix.m[7]=0,this._rotMatrix.m[8]=2*(this._quaternion.z*this._quaternion.x+this._quaternion.y*this._quaternion.w),this._rotMatrix.m[9]=2*(this._quaternion.y*this._quaternion.z-this._quaternion.x*this._quaternion.w),this._rotMatrix.m[10]=1-2*(this._quaternion.y*this._quaternion.y+this._quaternion.x*this._quaternion.x),this._rotMatrix.m[11]=0,this._rotMatrix.m[12]=0,this._rotMatrix.m[13]=0,this._rotMatrix.m[14]=0,this._rotMatrix.m[15]=1},t.prototype.dispose=function(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._positions32=null,this._normals32=null,this._fixedNormal32=null,this._uvs32=null,this._colors32=null,this.pickedParticles=null},t.prototype.refreshVisibleSize=function(){this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo()},t.prototype.setVisibilityBox=function(t){var i=t/2;this.mesh._boundingInfo=new e.BoundingInfo(new e.Vector3((-i),(-i),(-i)),new e.Vector3(i,i,i))},Object.defineProperty(t.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(e){this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVisibilityBoxLocked",{get:function(){return this._isVisibilityBoxLocked},set:function(e){this._isVisibilityBoxLocked=e,this.mesh.getBoundingInfo().isLocked=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleRotation",{get:function(){return this._computeParticleRotation},set:function(e){this._computeParticleRotation=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(e){this._computeParticleColor=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(e){this._computeParticleTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeParticleVertex",{get:function(){return this._computeParticleVertex},set:function(e){this._computeParticleVertex=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(e){this._computeBoundingBox=e},enumerable:!0,configurable:!0}),t.prototype.initParticles=function(){},t.prototype.recycleParticle=function(e){return e},t.prototype.updateParticle=function(e){return e},t.prototype.updateParticleVertex=function(e,t,i){return t},t.prototype.beforeUpdateParticles=function(e,t,i){},t.prototype.afterUpdateParticles=function(e,t,i){},t})();e.SolidParticleSystem=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function e(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}return e})(),r=(function(){function t(){}return t.ConvertCubeMapToSphericalPolynomial=function(t){for(var i=new e.SphericalHarmonics,r=0,n=2/t.size,o=n,s=.5*n-1,a=0;a<6;a++)for(var h=this.FileFaces[a],c=t[h.name],l=s,u=0;u<t.size;u++){for(var d=s,f=0;f<t.size;f++){var p=h.worldAxisForFileX.scale(d).add(h.worldAxisForFileY.scale(l)).add(h.worldAxisForNormal);p.normalize();var _,m=Math.pow(1+d*d+l*l,-1.5),g=c[u*t.size*3+3*f+0],v=c[u*t.size*3+3*f+1],y=c[u*t.size*3+3*f+2],_=new e.Color3(g,v,y);i.addLight(p,_,m),r+=m,d+=n}l+=o}var x=4*Math.PI,b=x/r;return i.scale(b),i.scale(1/Math.PI),e.SphericalPolynomial.getSphericalPolynomialFromHarmonics(i)},t.FileFaces=[new i("right",new e.Vector3(1,0,0),new e.Vector3(0,0,(-1)),new e.Vector3(0,(-1),0)),new i("left",new e.Vector3((-1),0,0),new e.Vector3(0,0,1),new e.Vector3(0,(-1),0)),new i("up",new e.Vector3(0,1,0),new e.Vector3(1,0,0),new e.Vector3(0,0,1)),new i("down",new e.Vector3(0,(-1),0),new e.Vector3(1,0,0),new e.Vector3(0,0,(-1))),new i("front",new e.Vector3(0,0,1),new e.Vector3(1,0,0),new e.Vector3(0,(-1),0)),new i("back",new e.Vector3(0,0,(-1)),new e.Vector3((-1),0,0),new e.Vector3(0,(-1),0))],t})();t.CubeMapToSphericalPolynomialTools=r})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){}return t.ConvertPanoramaToCubemap=function(e,t,i,r){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";var n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i),o=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i),s=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i),a=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i),c=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i);return{front:n,back:o,left:s,right:a,up:h,down:c,size:r}},t.CreateCubemapTexture=function(e,t,i,r,n){for(var o=new ArrayBuffer(e*e*4*3),s=new Float32Array(o),a=t[1].subtract(t[0]).scale(1/e),h=t[3].subtract(t[2]).scale(1/e),c=1/e,l=0,u=0;u<e;u++){for(var d=t[0],f=t[2],p=0;p<e;p++){var _=f.subtract(d).scale(l).add(d);_.normalize();var m=this.CalcProjectionSpherical(_,i,r,n);s[u*e*3+3*p+0]=m.r,s[u*e*3+3*p+1]=m.g,s[u*e*3+3*p+2]=m.b,d=d.add(a),f=f.add(h)}l+=c}return s},t.CalcProjectionSpherical=function(e,t,i,r){for(var n=Math.atan2(e.z,e.x),o=Math.acos(e.y);n<-Math.PI;)n+=2*Math.PI;for(;n>Math.PI;)n-=2*Math.PI;var s=n/Math.PI,a=o/Math.PI;s=.5*s+.5;var h=Math.round(s*i);h<0?h=0:h>=i&&(h=i-1);var c=Math.round(a*r);c<0?c=0:c>=r&&(c=r-1);var l=r-c-1,u=t[l*i*3+3*h+0],d=t[l*i*3+3*h+1],f=t[l*i*3+3*h+2];return{r:u,g:d,b:f}},t.FACE_FRONT=[new e.Vector3((-1),(-1),(-1)),new e.Vector3(1,(-1),(-1)),new e.Vector3((-1),1,(-1)),new e.Vector3(1,1,(-1))],t.FACE_BACK=[new e.Vector3(1,(-1),1),new e.Vector3((-1),(-1),1),new e.Vector3(1,1,1),new e.Vector3((-1),1,1)],t.FACE_RIGHT=[new e.Vector3(1,(-1),(-1)),new e.Vector3(1,(-1),1),new e.Vector3(1,1,(-1)),new e.Vector3(1,1,1)],t.FACE_LEFT=[new e.Vector3((-1),(-1),1),new e.Vector3((-1),(-1),(-1)),new e.Vector3((-1),1,1),new e.Vector3((-1),1,(-1))],t.FACE_DOWN=[new e.Vector3((-1),1,(-1)),new e.Vector3(1,1,(-1)),new e.Vector3((-1),1,1),new e.Vector3(1,1,1)],t.FACE_UP=[new e.Vector3((-1),(-1),1),new e.Vector3(1,(-1),1),new e.Vector3((-1),(-1),(-1)),new e.Vector3(1,(-1),(-1))],t})();t.PanoramaToCubeMapTools=i})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){var t=(function(){function t(){}return t.Ldexp=function(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},t.Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this.Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},t.readStringLine=function(e,t){for(var i="",r="",n=t;n<e.length-t&&(r=String.fromCharCode(e[n]),"\n"!=r);n++)i+=r;return i},t.RGBE_ReadHeader=function(e){var t=0,i=0,r=this.readStringLine(e,0);if("#"!=r[0]||"?"!=r[1])throw"Bad HDR Format.";var n=!1,o=!1,s=0;do s+=r.length+1,r=this.readStringLine(e,s),"FORMAT=32-bit_rle_rgbe"==r?o=!0:0==r.length&&(n=!0);while(!n);if(!o)throw"HDR Bad header format, unsupported FORMAT";s+=r.length+1,r=this.readStringLine(e,s);var a=/^\-Y (.*) \+X (.*)$/g,h=a.exec(r);if(h.length<3)throw"HDR Bad header format, no size";if(i=parseInt(h[2]),t=parseInt(h[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return s+=r.length+1,{height:t,width:i,dataPosition:s}},t.GetCubeMapTextureData=function(t,i){var r=new Uint8Array(t),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels_RLE(r,n),s=e.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(o,n.width,n.height,i);return s},t.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},t.RGBE_ReadPixels_RLE=function(e,t){for(var i,r,n,o,s,a=t.height,h=t.width,c=t.dataPosition,l=0,u=0,d=0,f=new ArrayBuffer(4*h),p=new Uint8Array(f),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);a>0;){if(i=e[c++],r=e[c++],n=e[c++],o=e[c++],2!=i||2!=r||128&n)throw"HDR Bad header format, not RLE";if((n<<8|o)!=h)throw"HDR Bad header format, wrong scan line width";for(l=0,d=0;d<4;d++)for(u=(d+1)*h;l<u;)if(i=e[c++],r=e[c++],i>128){if(s=i-128,0==s||s>u-l)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[l++]=r}else{if(s=i,0==s||s>u-l)throw"HDR Bad Format, bad scanline data (non-run)";if(p[l++]=r,--s>0)for(var g=0;g<s;g++)p[l++]=e[c++]}for(d=0;d<h;d++)i=p[d],r=p[d+h],n=p[d+2*h],o=p[d+3*h],this.Rgbe2float(m,i,r,n,o,(t.height-a)*h*3+3*d);a--}return m},t})();e.HDRTools=t})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(){this.min=new e.Vector3(0,0,0),this.max=new e.Vector3(0,0,0),this.clear()}return t.prototype.clear=function(){this.min.x=t.MAX,this.min.y=t.MAX,this.min.z=t.MAX,this.max.x=t.MIN,this.max.y=t.MIN,this.max.z=t.MIN},t.prototype.augment=function(e,t,i){this.min.x=Math.min(this.min.x,e),this.min.y=Math.min(this.min.y,t),this.min.z=Math.min(this.min.z,i),this.max.x=Math.max(this.max.x,e),this.max.y=Math.max(this.max.y,t),this.max.z=Math.max(this.max.z,i)},t.prototype.clampMin=function(e,t,i){this.min.x=Math.max(this.min.x,e),this.min.y=Math.max(this.min.y,t),this.min.z=Math.max(this.min.z,i)},t.prototype.clampMax=function(e,t,i){this.max.x=Math.min(this.max.x,e),this.max.y=Math.min(this.max.y,t),this.max.z=Math.min(this.max.z,i)},t.prototype.empty=function(){return this.min.x>this.max.y||this.min.y>this.max.y||this.min.z>this.max.y},t.MAX=Number.MAX_VALUE,t.MIN=Number.MIN_VALUE,t})(),r=(function(){function t(e,t,i,r,n,o,s,a,h,c){this.input=e,this.inputSize=t,this.outputSize=i,this.maxNumMipLevels=r,this.numChannels=n,this.isFloat=o,this.specularPower=s,this.cosinePowerDropPerMip=a,this.excludeBase=h,this.fixup=c,this._outputSurface=[],this._numMipLevels=0}return t.prototype.filterCubeMap=function(){return this.init(),this.filterCubeMapMipChain(),this._outputSurface},t.prototype.init=function(){var e,i,r;for(0==this.maxNumMipLevels&&(this.maxNumMipLevels=t.CP_MAX_MIPLEVELS),r=this.outputSize,i=0;i<this.maxNumMipLevels;i++){for(this._outputSurface.length++,this._outputSurface[i]=[],e=0;e<6;e++)this._outputSurface[i].length++,this.isFloat?this._outputSurface[i][e]=new Float32Array(r*r*this.numChannels):this._outputSurface[i][e]=new Uint32Array(r*r*this.numChannels);if(r>>=1,this._numMipLevels++,0==r)return void(this.maxNumMipLevels=i)}},t.prototype.filterCubeMapMipChain=function(){var e=this.specularPower;this.precomputeFilterLookupTables(this.inputSize);for(var t=0;t<this._numMipLevels;t++){this.excludeBase&&0==t&&(e=1e5);var i=this.input,r=this._outputSurface[t],n=this.outputSize>>t,o=this.getBaseFilterAngle(e);this.filterCubeSurfaces(i,this.inputSize,r,n,o,e),this.fixup&&this.fixupCubeEdges(r,n),this.excludeBase&&0==t&&(e=this.specularPower),e*=this.cosinePowerDropPerMip}},t.prototype.getBaseFilterAngle=function(e){var t=1e-6,i=180;return i=Math.acos(Math.pow(t,1/e)),i*=180/Math.PI,i*=2},t.prototype.precomputeFilterLookupTables=function(e){this._normCubeMap=[],this.buildNormalizerSolidAngleCubemap(e)},t.prototype.buildNormalizerSolidAngleCubemap=function(e){var t,i,r;for(t=0;t<6;t++){this._normCubeMap.push(new Float32Array(e*e*4));this.input[t];for(r=0;r<e;r++)for(i=0;i<e;i++){var n=this.texelCoordToVect(t,i,r,e,this.fixup);this._normCubeMap[t][4*(r*e+i)+0]=n.x,this._normCubeMap[t][4*(r*e+i)+1]=n.y,this._normCubeMap[t][4*(r*e+i)+2]=n.z;var o=this.texelCoordSolidAngle(t,i,r,e);this._normCubeMap[t][4*(r*e+i)+4]=o}}},t.prototype.texelCoordToVect=function(e,i,r,n,o){var s,a;if(s=2*(i+.5)/n-1,a=2*(r+.5)/n-1,o&&n>1){var h=Math.pow(n,2)/Math.pow(n-1,3);s=h*Math.pow(s,3)+s,a=h*Math.pow(a,3)+a}var c=t._sgFace2DMapping[e][t.CP_UDIR];t._vectorTemp.x=c[0]*s,t._vectorTemp.y=c[1]*s,t._vectorTemp.z=c[2]*s;var l=t._sgFace2DMapping[e][t.CP_VDIR];t._vectorTemp.x+=l[0]*a,t._vectorTemp.y+=l[1]*a,t._vectorTemp.z+=l[2]*a;var u=t._sgFace2DMapping[e][t.CP_FACEAXIS];return t._vectorTemp.x+=u[0],t._vectorTemp.y+=u[1],t._vectorTemp.z+=u[2],t._vectorTemp.normalize(),t._vectorTemp},t.prototype.vectToTexelCoord=function(e,i,r,n){var o,s,a=Math.abs(e),h=Math.abs(i),c=Math.abs(r);a>=h&&a>=c?(o=a,s=e>=0?t.CP_FACE_X_POS:t.CP_FACE_X_NEG):h>=a&&h>=c?(o=h,s=i>=0?t.CP_FACE_Y_POS:t.CP_FACE_Y_NEG):(o=c,s=r>=0?t.CP_FACE_Z_POS:t.CP_FACE_Z_NEG);var l=1/o;e*=l,i*=l,r*=l;var u=t._sgFace2DMapping[s][t.CP_UDIR],d=u[0]*e+u[1]*i+u[2]*r;u=t._sgFace2DMapping[s][t.CP_VDIR];var f=u[0]*e+u[1]*i+u[2]*r,p=Math.floor(.5*(n-1)*(d+1)),_=Math.floor(.5*(n-1)*(f+1));return t._vectorTemp.x=s,t._vectorTemp.y=p,t._vectorTemp.z=_,t._vectorTemp},t.prototype.areaElement=function(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))},t.prototype.texelCoordSolidAngle=function(e,t,i,r){t=2*(t+.5)/r-1,i=2*(i+.5)/r-1;var n=1/r,o=t-n,s=i-n,a=t+n,h=i+n,c=this.areaElement(o,s)-this.areaElement(o,h)-this.areaElement(a,s)+this.areaElement(a,h);return c},t.prototype.filterCubeSurfaces=function(e,t,r,n,o,s){var a,h,c,l=[];for(a=0;a<6;a++)l.push(new i);var u=180/Math.PI*Math.atan2(1,t),d=o/2;d<u&&(d=u),d>90&&(d=90);var f=Math.ceil(d/u);f<1&&(f=1);var p=Math.cos(Math.PI/180*d);for(a=0;a<6;a++)for(c=0;c<n;c++)for(h=0;h<n;h++){var _=this.texelCoordToVect(a,h,c,n,this.fixup).clone();this.clearFilterExtents(l),this.determineFilterExtents(_,t,f,l);var m=this.processFilterExtents(_,p,l,e,t,s);r[a][(c*n+h)*this.numChannels+0]=m.x,r[a][(c*n+h)*this.numChannels+1]=m.y,r[a][(c*n+h)*this.numChannels+2]=m.z}},t.prototype.clearFilterExtents=function(e){for(var t=0;t<6;t++)e[t].clear()},t.prototype.determineFilterExtents=function(e,i,r,n){var o,s,a,h=[0,0,0,0],c=[0,0,0,0],l=[0,0,0,0],u=this.vectToTexelCoord(e.x,e.y,e.z,i),d=u.x,f=u.y,p=u.z;n[d].augment(f-r,p-r,0),n[d].augment(f+r,p+r,0),n[d].clampMin(0,0,0),n[d].clampMax(i-1,i-1,0);var _=n[d].min.x,m=n[d].min.y,g=n[d].max.x,v=n[d].max.y;h[0]=r-f,c[0]=m,l[0]=v,h[1]=f+r-(i-1),c[1]=m,l[1]=v,h[2]=r-p,c[2]=_,l[2]=g,h[3]=p+r-(i-1),c[3]=_,l[3]=g;for(var y=0;y<4;y++){if(h[y]>0){switch(o=t._sgCubeNgh[d][y][0],s=t._sgCubeNgh[d][y][1],y!=s&&y+s!=3||(c[y]=i-1-c[y],l[y]=i-1-l[y]),t._sgCubeNgh[d][y][1]){case t.CP_EDGE_LEFT:n[o].augment(0,c[y],0),n[o].augment(h[y],l[y],0);break;case t.CP_EDGE_RIGHT:n[o].augment(i-1,c[y],0),n[o].augment(i-1-h[y],l[y],0);break;case t.CP_EDGE_TOP:n[o].augment(c[y],0,0),n[o].augment(l[y],h[y],0);break;case t.CP_EDGE_BOTTOM:n[o].augment(c[y],i-1,0),n[o].augment(l[y],i-1-h[y],0)}n[o].clampMin(0,0,0),n[o].clampMax(i-1,i-1,0)}if(h[y]>i){switch(d){case t.CP_FACE_X_POS:a=t.CP_FACE_X_NEG;break;case t.CP_FACE_X_NEG:a=t.CP_FACE_X_POS;break;case t.CP_FACE_Y_POS:a=t.CP_FACE_Y_NEG;break;case t.CP_FACE_Y_NEG:a=t.CP_FACE_Y_POS;break;case t.CP_FACE_Z_POS:a=t.CP_FACE_Z_NEG;break;case t.CP_FACE_Z_NEG:a=t.CP_FACE_Z_POS}n[a].augment(0,0,0),n[a].augment(i-1,i-1,0)}}},t.prototype.processFilterExtents=function(e,i,r,n,o,s){for(var a=[0,0,0,0],h=0,c=0,l=this.numChannels,u=o,d=4*u,f=u*this.numChannels,p=1,_=0;_<6;_++)if(!r[_].empty())for(var m=r[_].min.x,g=r[_].min.y,v=r[_].max.x,y=r[_].max.y,x=4*(g*u+m),b=this.numChannels*(g*u+m),A=g;A<=y;A++){for(var T=0,E=0,P=m;P<=v;P++){var S=this._normCubeMap[_][x+T+0],M=this._normCubeMap[_][x+T+1],C=this._normCubeMap[_][x+T+2],R=S*e.x+M*e.y+C*e.z;if(R>=i&&R>0){var O=this._normCubeMap[_][x+T+3];for(O*=Math.pow(R,s+p),c=0;c<l;c++)a[c]+=O*n[_][b+E],E++;h+=O}else E+=l;T+=4}x+=d,b+=f}if(0!=h)t._vectorTemp.x=a[0]/h,t._vectorTemp.y=a[1]/h,t._vectorTemp.z=a[2]/h,this.numChannels>3&&(t._vectorTemp.w=a[3]/h);else{var D=this.vectToTexelCoord(e.x,e.y,e.z,o).clone();t._vectorTemp.x=n[D.x][this.numChannels*(D.z*o+D.y)+0],t._vectorTemp.y=n[D.x][this.numChannels*(D.z*o+D.y)+1],t._vectorTemp.z=n[D.x][this.numChannels*(D.z*o+D.y)+2],this.numChannels>3&&(t._vectorTemp.z=n[D.x][this.numChannels*(D.z*o+D.y)+3])}return t._vectorTemp},t.prototype.fixupCubeEdges=function(e,i){var r,n,o,s,a=0,h=[0,0,0,0,0,0,0,0],c=[[],[],[],[]],l=[[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]]];if(!(i<1))if(1!=i){for(s=0;s<6;s++)for(c[0]=[s,0],c[1]=[s,(i-1)*this.numChannels],c[2]=[s,i*(i-1)*this.numChannels],c[3]=[s,(i*(i-1)+(i-1))*this.numChannels],a=0;a<4;a++){var u=t._sgCubeCornerList[s][a];l[u][h[u]]=c[a],h[u]++}for(a=0;a<8;a++)for(r=0;r<this.numChannels;r++){var d=0;for(o=0;o<3;o++)d+=e[l[a][o][0]][l[a][o][1]+r];for(d*=1/3,o=0;o<3;o++)e[l[a][o][0]][l[a][o][1]+r]=d}for(o=0;o<12;o++){var f=t._sgCubeEdgeList[o][0],p=t._sgCubeEdgeList[o][1],_=t._sgCubeNgh[f][p][0],m=t._sgCubeNgh[f][p][1],g=0,v=0,y=0,x=0;switch(p){case t.CP_EDGE_LEFT:y=this.numChannels*i;break;case t.CP_EDGE_RIGHT:g+=(i-1)*this.numChannels,y=this.numChannels*i;break;case t.CP_EDGE_TOP:y=this.numChannels;break;case t.CP_EDGE_BOTTOM:g+=i*(i-1)*this.numChannels,y=this.numChannels}if(p==m||p+m==3)switch(m){case t.CP_EDGE_LEFT:v+=(i-1)*i*this.numChannels,x=-(this.numChannels*i);break;case t.CP_EDGE_RIGHT:v+=((i-1)*i+(i-1))*this.numChannels,x=-(this.numChannels*i);break;case t.CP_EDGE_TOP:v+=(i-1)*this.numChannels,x=-this.numChannels;break;case t.CP_EDGE_BOTTOM:v+=((i-1)*i+(i-1))*this.numChannels,x=-this.numChannels}else switch(m){case t.CP_EDGE_LEFT:x=this.numChannels*i;break;case t.CP_EDGE_RIGHT:v+=(i-1)*this.numChannels,x=this.numChannels*i;break;case t.CP_EDGE_TOP:x=this.numChannels;break;case t.CP_EDGE_BOTTOM:v+=i*(i-1)*this.numChannels,x=this.numChannels}for(g+=y,v+=x,n=1;n<i-1;n++){for(r=0;r<this.numChannels;r++){var b=e[f][g+r],A=e[_][v+r],T=.5*(b+A);e[f][g+r]=T,e[_][v+r]=T}g+=y,v+=x}}}else for(r=0;r<this.numChannels;r++){var E=0;for(s=0;s<6;s++)E+=e[s][r];for(E/=6,s=0;s<6;s++)e[s][r]=E}},t.CP_MAX_MIPLEVELS=16,t.CP_UDIR=0,t.CP_VDIR=1,t.CP_FACEAXIS=2,t.CP_FACE_X_POS=0,t.CP_FACE_X_NEG=1,t.CP_FACE_Y_POS=2,t.CP_FACE_Y_NEG=3,t.CP_FACE_Z_POS=4,t.CP_FACE_Z_NEG=5,t.CP_EDGE_LEFT=0,t.CP_EDGE_RIGHT=1,t.CP_EDGE_TOP=2,t.CP_EDGE_BOTTOM=3,t.CP_CORNER_NNN=0,t.CP_CORNER_NNP=1,t.CP_CORNER_NPN=2,t.CP_CORNER_NPP=3,t.CP_CORNER_PNN=4,t.CP_CORNER_PNP=5,t.CP_CORNER_PPN=6,t.CP_CORNER_PPP=7,t._vectorTemp=new e.Vector4(0,0,0,0),t._sgFace2DMapping=[[[0,0,-1],[0,-1,0],[1,0,0]],[[0,0,1],[0,-1,0],[-1,0,0]],[[1,0,0],[0,0,1],[0,1,0]],[[1,0,0],[0,0,-1],[0,-1,0]],[[1,0,0],[0,-1,0],[0,0,1]],[[-1,0,0],[0,-1,0],[0,0,-1]]],t._sgCubeNgh=[[[t.CP_FACE_Z_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_Z_NEG,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_Y_NEG,t.CP_EDGE_RIGHT]],[[t.CP_FACE_Z_NEG,t.CP_EDGE_RIGHT],[t.CP_FACE_Z_POS,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_LEFT],[t.CP_FACE_Y_NEG,t.CP_EDGE_LEFT]],[[t.CP_FACE_X_NEG,t.CP_EDGE_TOP],[t.CP_FACE_X_POS,t.CP_EDGE_TOP],[t.CP_FACE_Z_NEG,t.CP_EDGE_TOP],[t.CP_FACE_Z_POS,t.CP_EDGE_TOP]],[[t.CP_FACE_X_NEG,t.CP_EDGE_BOTTOM],[t.CP_FACE_X_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_NEG,t.CP_EDGE_BOTTOM]],[[t.CP_FACE_X_NEG,t.CP_EDGE_RIGHT],[t.CP_FACE_X_POS,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Y_NEG,t.CP_EDGE_TOP]],[[t.CP_FACE_X_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_X_NEG,t.CP_EDGE_LEFT],[t.CP_FACE_Y_POS,t.CP_EDGE_TOP],[t.CP_FACE_Y_NEG,t.CP_EDGE_BOTTOM]]],t._sgCubeEdgeList=[[t.CP_FACE_X_POS,t.CP_EDGE_LEFT],[t.CP_FACE_X_POS,t.CP_EDGE_RIGHT],[t.CP_FACE_X_POS,t.CP_EDGE_TOP],[t.CP_FACE_X_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_X_NEG,t.CP_EDGE_LEFT],[t.CP_FACE_X_NEG,t.CP_EDGE_RIGHT],[t.CP_FACE_X_NEG,t.CP_EDGE_TOP],[t.CP_FACE_X_NEG,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_POS,t.CP_EDGE_TOP],[t.CP_FACE_Z_POS,t.CP_EDGE_BOTTOM],[t.CP_FACE_Z_NEG,t.CP_EDGE_TOP],[t.CP_FACE_Z_NEG,t.CP_EDGE_BOTTOM]],t._sgCubeCornerList=[[t.CP_CORNER_PPP,t.CP_CORNER_PPN,t.CP_CORNER_PNP,t.CP_CORNER_PNN],[t.CP_CORNER_NPN,t.CP_CORNER_NPP,t.CP_CORNER_NNN,t.CP_CORNER_NNP],[t.CP_CORNER_NPN,t.CP_CORNER_PPN,t.CP_CORNER_NPP,t.CP_CORNER_PPP],[t.CP_CORNER_NNP,t.CP_CORNER_PNP,t.CP_CORNER_NNN,t.CP_CORNER_PNN],[t.CP_CORNER_NPP,t.CP_CORNER_PPP,t.CP_CORNER_NNP,t.CP_CORNER_PNP],[t.CP_CORNER_PPN,t.CP_CORNER_NPN,t.CP_CORNER_PNN,t.CP_CORNER_NNN]],t})();t.PMREMGenerator=r})(t=e.Internals||(e.Internals={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s,a,h){void 0===o&&(o=!1),void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===h&&(h=!1),t.call(this,r),this._useInGammaSpace=!1,this._generateHarmonics=!0,this._isBABYLONPreprocessed=!1,this.coordinatesMode=e.Texture.CUBIC_MODE,this.sphericalPolynomial=null,this.isPMREM=!1,i&&(this.name=i,this.url=i,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=e.Matrix.Identity(),n?(this._isBABYLONPreprocessed=!1,this._noMipmap=o,this._size=n,this._useInGammaSpace=a,this._usePMREMGenerator=h&&r.getEngine().getCaps().textureLOD&&this.getScene().getEngine().getCaps().textureFloat&&!this._useInGammaSpace):(this._isBABYLONPreprocessed=!0,this._noMipmap=!1,this._useInGammaSpace=!1,this._usePMREMGenerator=r.getEngine().getCaps().textureLOD&&this.getScene().getEngine().getCaps().textureFloat&&!this._useInGammaSpace),this.isPMREM=this._usePMREMGenerator,this._texture=this._getFromCache(i,this._noMipmap),this._texture||(r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this.loadTexture()))}return __extends(i,t),i.prototype.loadBabylonTexture=function(){var t=this,i=0,r=null,n=!this._useInGammaSpace&&this.getScene().getEngine().getCaps().textureFloat?function(e){for(var n=[],o=30,s=0;s<i;s++){n.push([]);for(var a=3*Math.pow(t._size>>s,2),h=0;h<6;h++){var c=r.subarray(o,o+a);n[s].push(c),o+=a}}return n}:null,o=function(o){var s=new Int32Array(o);r=new Float32Array(o);s[0];t._size=s[1],t.getScene().getEngine().updateTextureSize(t._texture,t._size,t._size),t.sphericalPolynomial=new e.SphericalPolynomial,t.sphericalPolynomial.x.copyFromFloats(r[2],r[3],r[4]),t.sphericalPolynomial.y.copyFromFloats(r[5],r[6],r[7]),t.sphericalPolynomial.z.copyFromFloats(r[8],r[9],r[10]),t.sphericalPolynomial.xx.copyFromFloats(r[11],r[12],r[13]),t.sphericalPolynomial.yy.copyFromFloats(r[14],r[15],r[16]),t.sphericalPolynomial.zz.copyFromFloats(r[17],r[18],r[19]),t.sphericalPolynomial.xy.copyFromFloats(r[20],r[21],r[22]),t.sphericalPolynomial.yz.copyFromFloats(r[23],r[24],r[25]),t.sphericalPolynomial.zx.copyFromFloats(r[26],r[27],r[28]),i=s[29];for(var a=30,h=[],c=3*Math.pow(t._size,2),l=0;l<6;l++)h.push(r.subarray(a,a+c)),a+=c;for(var u=[],d=null,f=0;f<6;f++){var p=null;if(n)p=h[f];else{var _=[0,2,4,1,3,5][f];if(p=h[_],!t.getScene().getEngine().getCaps().textureFloat){var m=new ArrayBuffer(c);d=new Uint8Array(m)}for(var g=0;g<t._size*t._size;g++)if(t._useInGammaSpace&&(p[3*g+0]=Math.pow(p[3*g+0],e.ToGammaSpace),p[3*g+1]=Math.pow(p[3*g+1],e.ToGammaSpace),p[3*g+2]=Math.pow(p[3*g+2],e.ToGammaSpace)),d){var v=Math.max(255*p[3*g+0],0),y=Math.max(255*p[3*g+1],0),x=Math.max(255*p[3*g+2],0),b=Math.max(Math.max(v,y),x);if(b>255){var A=255/b;v*=A,y*=A,x*=A}d[3*g+0]=v,d[3*g+1]=y,d[3*g+2]=x}}d?u.push(d):u.push(p)}return u};this._texture=this.getScene().getEngine().createRawCubeTexture(this.url,this.getScene(),this._size,e.Engine.TEXTUREFORMAT_RGB,this.getScene().getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,o,n)},i.prototype.loadHDRTexture=function(){var t=this,r=function(r){var n=e.Internals.HDRTools.GetCubeMapTextureData(r,t._size);t._generateHarmonics&&(t.sphericalPolynomial=e.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(n));for(var o=[],s=null,a=0;a<6;a++){if(!t.getScene().getEngine().getCaps().textureFloat){var h=new ArrayBuffer(t._size*t._size*3);s=new Uint8Array(h)}var c=n[i._facesMapping[a]];if(t._useInGammaSpace||s)for(var l=0;l<t._size*t._size;l++)if(t._useInGammaSpace&&(c[3*l+0]=Math.pow(c[3*l+0],e.ToGammaSpace),c[3*l+1]=Math.pow(c[3*l+1],e.ToGammaSpace),c[3*l+2]=Math.pow(c[3*l+2],e.ToGammaSpace)),s){var u=Math.max(255*c[3*l+0],0),d=Math.max(255*c[3*l+1],0),f=Math.max(255*c[3*l+2],0),p=Math.max(Math.max(u,d),f);if(p>255){var _=255/p;u*=_,d*=_,f*=_}s[3*l+0]=u,s[3*l+1]=d,s[3*l+2]=f}s?o.push(s):o.push(c)}return o},n=null;!this._noMipmap&&this._usePMREMGenerator&&(n=function(i){var r=new e.Internals.PMREMGenerator(i,t._size,t._size,0,3,t.getScene().getEngine().getCaps().textureFloat,2048,.25,(!1),(!0));return r.filterCubeMap()}),this._texture=this.getScene().getEngine().createRawCubeTexture(this.url,this.getScene(),this._size,e.Engine.TEXTUREFORMAT_RGB,this.getScene().getEngine().getCaps().textureFloat?e.Engine.TEXTURETYPE_FLOAT:e.Engine.TEXTURETYPE_UNSIGNED_INT,this._noMipmap,r,n)},i.prototype.loadTexture=function(){this._isBABYLONPreprocessed?this.loadBabylonTexture():this.loadHDRTexture()},i.prototype.clone=function(){var e=this._isBABYLONPreprocessed?null:this._size,t=new i(this.url,this.getScene(),e,this._noMipmap,this._generateHarmonics,this._useInGammaSpace,this._usePMREMGenerator);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this.loadTexture())},i.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},i.Parse=function(t,i,r){var n=null;if(t.name&&!t.isRenderTarget){var o=t.isBABYLONPreprocessed?null:t.size;n=new e.HDRCubeTexture(r+t.name,i,o,t.generateHarmonics,t.useInGammaSpace,t.usePMREMGenerator),n.name=t.name,n.hasAlpha=t.hasAlpha,n.level=t.level,n.coordinatesMode=t.coordinatesMode}return n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this._useInGammaSpace,e.generateHarmonics=this._generateHarmonics,e.usePMREMGenerator=this._usePMREMGenerator,e.isBABYLONPreprocessed=this._isBABYLONPreprocessed,e.customType="BABYLON.HDRCubeTexture",e},i.generateBabylonHDROnDisk=function(e,t,r){void 0===r&&(r=null);var n=function(e){var t=new Blob([e],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download="envmap.babylon.hdr",r.click()};i.generateBabylonHDR(e,t,n,r)},i.generateBabylonHDR=function(t,i,r,n){if(void 0===n&&(n=null),!t)return null;if(!e.Tools.IsExponentOfTwo(i))return null;var o=function(t){var n=e.Internals.HDRTools.GetCubeMapTextureData(t,i),o=e.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(n),s=[];s.push(n.right),s.push(n.left),s.push(n.up),s.push(n.down),s.push(n.front),s.push(n.back);var a=new e.Internals.PMREMGenerator(s,i,i,0,3,(!0),2048,.25,(!1),(!0)),h=a.filterCubeMap(),c=4;c+=4,c+=108,c+=4;for(var l=0;l<h.length;l++){var u=i>>l;c+=6*u*u*3*4}var d=new ArrayBuffer(c),f=new Int32Array(d),p=new Float32Array(d);f[0]=1,f[1]=i,o.x.toArray(p,2),o.y.toArray(p,5),o.z.toArray(p,8),o.xx.toArray(p,11),o.yy.toArray(p,14),o.zz.toArray(p,17),o.xy.toArray(p,20),o.yz.toArray(p,23),o.zx.toArray(p,26),f[29]=h.length;for(var _=30,l=0;l<h.length;l++)for(var m=3*Math.pow(i>>l,2),g=0;g<6;g++)p.set(h[l][g],_),_+=m;r(d)};e.Tools.LoadFile(t,(function(e){o(e)}),null,null,!0,n)},i._facesMapping=["right","up","front","left","down","back"],i})(e.BaseTexture);e.HDRCubeTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=1),this.skeleton=t,this.mesh=i,this.autoUpdateBonesMatrices=n,this.renderingGroupId=o,this.color=e.Color3.White(),this._debugLines=[],this._isEnabled=!1,this._scene=r,this.update(),this._renderFunction=this.update.bind(this)}return Object.defineProperty(t.prototype,"isEnabled",{
get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,e?this._scene.registerBeforeRender(this._renderFunction):this._scene.unregisterBeforeRender(this._renderFunction))},enumerable:!0,configurable:!0}),t.prototype._getBonePosition=function(t,i,r,n,o,s){void 0===n&&(n=0),void 0===o&&(o=0),void 0===s&&(s=0);var a=e.Tmp.Matrix[0],h=i.getParent();if(a.copyFrom(i.getLocalMatrix()),0!==n||0!==o||0!==s){var c=e.Tmp.Matrix[1];e.Matrix.IdentityToRef(c),c.m[12]=n,c.m[13]=o,c.m[14]=s,c.multiplyToRef(a,a)}h&&a.multiplyToRef(h.getAbsoluteTransform(),a),a.multiplyToRef(r,a),t.x=a.m[12],t.y=a.m[13],t.z=a.m[14]},t.prototype._getLinesForBonesWithLength=function(t,i){for(var r=t.length,n=0;n<r;n++){var o=t[n],s=this._debugLines[n];s||(s=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=s),this._getBonePosition(s[0],o,i),this._getBonePosition(s[1],o,i,0,o.length,0)}},t.prototype._getLinesForBonesNoLength=function(t,i){for(var r=t.length,n=0,o=r-1;o>=0;o--){var s=t[o],a=s.getParent();if(a){var h=this._debugLines[n];h||(h=[e.Vector3.Zero(),e.Vector3.Zero()],this._debugLines[n]=h),s.getAbsolutePositionToRef(this.mesh,h[0]),a.getAbsolutePositionToRef(this.mesh,h[1]),n++}}},t.prototype.update=function(){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,this.mesh.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix()),this._debugMesh?e.MeshBuilder.CreateLineSystem(null,{lines:this._debugLines,updatable:!0,instance:this._debugMesh},this._scene):(this._debugMesh=e.MeshBuilder.CreateLineSystem(null,{lines:this._debugLines,updatable:!0},this._scene),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.color=this.color},t.prototype.dispose=function(){this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null)},t})();t.SkeletonViewer=i})(t=e.Debug||(e.Debug={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(){function t(t,i){void 0===i&&(i=1),this._xline=[e.Vector3.Zero(),e.Vector3.Zero()],this._yline=[e.Vector3.Zero(),e.Vector3.Zero()],this._zline=[e.Vector3.Zero(),e.Vector3.Zero()],this.scaleLines=1,this.scaleLines=i,this._xmesh=e.Mesh.CreateLines("xline",this._xline,t,!0),this._ymesh=e.Mesh.CreateLines("yline",this._yline,t,!0),this._zmesh=e.Mesh.CreateLines("zline",this._zline,t,!0),this._xmesh.renderingGroupId=2,this._ymesh.renderingGroupId=2,this._zmesh.renderingGroupId=2,this._xmesh.material.checkReadyOnlyOnce=!0,this._xmesh.color=new e.Color3(1,0,0),this._ymesh.material.checkReadyOnlyOnce=!0,this._ymesh.color=new e.Color3(0,1,0),this._zmesh.material.checkReadyOnlyOnce=!0,this._zmesh.color=new e.Color3(0,0,1),this.scene=t}return t.prototype.update=function(t,i,r,n){var o=this.scaleLines,s=this._xline[0],a=this._xline[1];s.x=t.x,s.y=t.y,s.z=t.z,a.x=s.x+i.x*o,a.y=s.y+i.y*o,a.z=s.z+i.z*o,e.Mesh.CreateLines(null,this._xline,null,null,this._xmesh),s=this._yline[0],a=this._yline[1],s.x=t.x,s.y=t.y,s.z=t.z,a.x=s.x+r.x*o,a.y=s.y+r.y*o,a.z=s.z+r.z*o,e.Mesh.CreateLines(null,this._yline,null,null,this._ymesh),s=this._zline[0],a=this._zline[1],s.x=t.x,s.y=t.y,s.z=t.z,a.x=s.x+n.x*o,a.y=s.y+n.y*o,a.z=s.z+n.z*o,e.Mesh.CreateLines(null,this._zline,null,null,this._zmesh)},t.prototype.dispose=function(){this._xmesh&&(this._xmesh.dispose(),this._ymesh.dispose(),this._zmesh.dispose(),this._xmesh=null,this._ymesh=null,this._zmesh=null,this._xline=null,this._yline=null,this._zline=null,this.scene=null)},t})();t.AxesViewer=i})(t=e.Debug||(e.Debug={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(t){var i=(function(t){function i(i,r,n,o){void 0===o&&(o=1),t.call(this,i,o),this.pos=e.Vector3.Zero(),this.xaxis=e.Vector3.Zero(),this.yaxis=e.Vector3.Zero(),this.zaxis=e.Vector3.Zero(),this.mesh=n,this.bone=r}return __extends(i,t),i.prototype.update=function(){var i=this.bone;i.getAbsolutePositionToRef(this.mesh,this.pos),i.getDirectionToRef(e.Axis.X,this.mesh,this.xaxis),i.getDirectionToRef(e.Axis.Y,this.mesh,this.yaxis),i.getDirectionToRef(e.Axis.Z,this.mesh,this.zaxis),t.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)},i.prototype.dispose=function(){this.pos&&(this.pos=null,this.xaxis=null,this.yaxis=null,this.zaxis=null,this.mesh=null,this.bone=null,t.prototype.dispose.call(this))},i})(t.AxesViewer);t.BoneAxesViewer=i})(t=e.Debug||(e.Debug={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r){t.call(this,r),i&&(this._textureMatrix=e.Matrix.Identity(),this.name=i,this.url=i,this.hasAlpha=!1,this.isCube=!1,this.wrapU=e.Texture.CLAMP_ADDRESSMODE,this.wrapV=e.Texture.CLAMP_ADDRESSMODE,this.anisotropicFilteringLevel=1,this._texture=this._getFromCache(i,!0),this._texture||(r.useDelayedTextureLoading?this.delayLoadState=e.Engine.DELAYLOADSTATE_NOTLOADED:this.loadTexture()))}return __extends(i,t),i.prototype.getTextureMatrix=function(){return this._textureMatrix},i.prototype.load3dlTexture=function(){var t=this,r=this.getScene().getEngine().createRawTexture(null,1,1,e.Engine.TEXTUREFORMAT_RGBA,!1,!1,e.Texture.BILINEAR_SAMPLINGMODE);this._texture=r;var n=function(n){for(var o,s,a,h=n.split("\n"),c=0,l=0,u=0,d=0,f=0,p=0;p<h.length;p++)if(a=h[p],i._noneEmptyLineRegex.test(a)&&0!==a.indexOf("#")){var _=a.split(" ");if(0!==c){if(0!=c){var m=Math.max(parseInt(_[0]),0),g=Math.max(parseInt(_[1]),0),v=Math.max(parseInt(_[2]),0);f=Math.max(m,f),f=Math.max(g,f),f=Math.max(v,f);var y=4*(l+d*c+u*c*c);s[y+0]=m,s[y+1]=g,s[y+2]=v,s[y+3]=0,d++,d%c==0&&(u++,d=0,u%c==0&&(l++,u=0))}}else c=_.length,o=new Uint8Array(c*c*c*4),s=new Float32Array(c*c*c*4)}for(var p=0;p<s.length;p++){var x=s[p];o[p]=x/f*255}t.getScene().getEngine().updateTextureSize(r,c*c,c),t.getScene().getEngine().updateRawTexture(r,o,e.Engine.TEXTUREFORMAT_RGBA,!1)};return e.Tools.LoadFile(this.url,n),this._texture},i.prototype.loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this.load3dlTexture()},i.prototype.clone=function(){var e=new i(this.url,this.getScene());return e.level=this.level,e},i.prototype.delayLoad=function(){this.delayLoadState===e.Engine.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=e.Engine.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},i.Bind=function(e,t){t.setTexture("cameraColorGrading2DSampler",e);var i=e.level,r=e.getSize().height,n=r-1,o=1/r;t.setFloat4("vCameraColorGradingInfos",i,r,n,o);var s=o/r,a=o,h=n*s,c=n/r,l=.5*s,u=.5*a;t.setFloat4("vCameraColorGradingScaleOffset",h,c,l,u)},i.PrepareUniformsAndSamplers=function(e,t){e.push("vCameraColorGradingInfos","vCameraColorGradingScaleOffset"),t.push("cameraColorGrading2DSampler")},i.Parse=function(t,i,r){var n=null;return t.name&&!t.isRenderTarget&&(n=new e.ColorGradingTexture(t.name,i),n.name=t.name,n.level=t.level),n},i.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},i._noneEmptyLineRegex=/\S+/,i})(e.BaseTexture);e.ColorGradingTexture=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this._dirty=!0,this._tempColor=new e.Color4(0,0,0,0),this._globalCurve=new e.Color4(0,0,0,0),this._highlightsCurve=new e.Color4(0,0,0,0),this._midtonesCurve=new e.Color4(0,0,0,0),this._shadowsCurve=new e.Color4(0,0,0,0),this._positiveCurve=new e.Color4(0,0,0,0),this._negativeCurve=new e.Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(t.prototype,"GlobalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"GlobalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"GlobalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"HighlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"MidtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ShadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!0,configurable:!0}),t.Bind=function(e,t){e._dirty&&(e._dirty=!1,e.getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e.getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e.getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e.getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t.setFloat4("vCameraColorCurvePositive",e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4("vCameraColorCurveNeutral",e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4("vCameraColorCurveNegative",e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a)},t.PrepareUniforms=function(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")},t.prototype.getColorGradingDataToRef=function(e,i,r,n,o){null!=e&&(e=t.clamp(e,0,360),i=t.clamp(i,-100,100),r=t.clamp(r,-100,100),n=t.clamp(n,-100,100),i=t.applyColorGradingSliderNonlinear(i),i*=.5,n=t.applyColorGradingSliderNonlinear(n),i<0&&(i*=-1,e=(e+180)%360),t.fromHSBToRef(e,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},t.applyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100},t.fromHSBToRef=function(e,i,r,n){var o=t.clamp(e,0,360),s=t.clamp(i/100,0,1),a=t.clamp(r/100,0,1);if(0===s)n.r=a,n.g=a,n.b=a;else{o/=60;var h=Math.floor(o),c=o-h,l=a*(1-s),u=a*(1-s*c),d=a*(1-s*(1-c));switch(h){case 0:n.r=a,n.g=d,n.b=l;break;case 1:n.r=u,n.g=a,n.b=l;break;case 2:n.r=l,n.g=a,n.b=d;break;case 3:n.r=l,n.g=u,n.b=a;break;case 4:n.r=d,n.g=l,n.b=a;break;default:n.r=a,n.g=l,n.b=u}}n.a=1},t.clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},t.prototype.clone=function(){return e.SerializationHelper.Clone((function(){return new t}),this)},t.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},t.Parse=function(i){return e.SerializationHelper.Parse((function(){return new t}),i,null,null)},__decorate([e.serialize()],t.prototype,"_globalHue",void 0),__decorate([e.serialize()],t.prototype,"_globalDensity",void 0),__decorate([e.serialize()],t.prototype,"_globalSaturation",void 0),__decorate([e.serialize()],t.prototype,"_globalExposure",void 0),__decorate([e.serialize()],t.prototype,"_highlightsHue",void 0),__decorate([e.serialize()],t.prototype,"_highlightsDensity",void 0),__decorate([e.serialize()],t.prototype,"_highlightsSaturation",void 0),__decorate([e.serialize()],t.prototype,"_highlightsExposure",void 0),__decorate([e.serialize()],t.prototype,"_midtonesHue",void 0),__decorate([e.serialize()],t.prototype,"_midtonesDensity",void 0),__decorate([e.serialize()],t.prototype,"_midtonesSaturation",void 0),__decorate([e.serialize()],t.prototype,"_midtonesExposure",void 0),t})();e.ColorCurves=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(e){function t(){e.call(this),this.ALBEDO=!1,this.AMBIENT=!1,this.OPACITY=!1,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.REFLECTIVITY=!1,this.BUMP=!1,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.ALPHATEST=!1,this.ALPHAFROMALBEDO=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.OPACITYFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHALBEDO=!1,this.LIGHTMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.CAMERATONEMAP=!1,this.CAMERACONTRAST=!1,this.CAMERACOLORGRADING=!1,this.CAMERACOLORCURVES=!1,this.OVERLOADEDVALUES=!1,this.OVERLOADEDSHADOWVALUES=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.LINKREFRACTIONTOTRANSPARENCY=!1,this.REFRACTIONMAPINLINEARSPACE=!1,this.LODBASEDMICROSFURACE=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.RADIANCEOVERALPHA=!1,this.USEPMREMREFLECTION=!1,this.USEPMREMREFRACTION=!1,this.OPENGLNORMALMAP=!1,this.INVERTNORMALMAPX=!1,this.INVERTNORMALMAPY=!1,this.SHADOWFULLFLOAT=!1,this.METALLICWORKFLOW=!1,this.METALLICROUGHNESSGSTOREINALPHA=!1,this.METALLICROUGHNESSGSTOREINGREEN=!1,this.rebuild()}return __extends(t,e),t})(e.MaterialDefines),i=(function(i){function r(r,n){var o=this;i.call(this,r,n),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this._lightingInfos=new e.Vector4(this.directIntensity,this.emissiveIntensity,this.environmentIntensity,this.specularIntensity),this.disableBumpMap=!1,this.overloadedShadowIntensity=1,this.overloadedShadeIntensity=1,this._overloadedShadowInfos=new e.Vector4(this.overloadedShadowIntensity,this.overloadedShadeIntensity,0,0),this.cameraExposure=1,this.cameraContrast=1,this.cameraColorGradingTexture=null,this.cameraColorCurves=null,this._cameraInfos=new e.Vector4(1,1,0,0),this._microsurfaceTextureLods=new e.Vector2(0,0),this.overloadedAmbient=e.Color3.White(),this.overloadedAmbientIntensity=0,this.overloadedAlbedo=e.Color3.White(),this.overloadedAlbedoIntensity=0,this.overloadedReflectivity=new e.Color3(.3,.3,.3),this.overloadedReflectivityIntensity=0,this.overloadedEmissive=e.Color3.White(),this.overloadedEmissiveIntensity=0,this._overloadedIntensity=new e.Vector4(this.overloadedAmbientIntensity,this.overloadedAlbedoIntensity,this.overloadedReflectivityIntensity,this.overloadedEmissiveIntensity),this.overloadedReflection=e.Color3.White(),this.overloadedReflectionIntensity=0,this.overloadedMicroSurface=0,this.overloadedMicroSurfaceIntensity=0,this._overloadedMicroSurface=new e.Vector3(this.overloadedMicroSurface,this.overloadedMicroSurfaceIntensity,this.overloadedReflectionIntensity),this.ambientTextureStrength=1,this.ambientColor=new e.Color3(0,0,0),this.albedoColor=new e.Color3(1,1,1),this.reflectivityColor=new e.Color3(1,1,1),this.reflectionColor=new e.Color3(.5,.5,.5),this.emissiveColor=new e.Color3(0,0,0),this.microSurface=.9,this.indexOfRefraction=.66,this.invertRefractionY=!1,this.linkRefractionWithTransparency=!1,this.linkEmissiveWithAlbedo=!1,this.useLightmapAsShadowmap=!1,this.useEmissiveAsIllumination=!1,this.useAlphaFromAlbedoTexture=!1,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useScalarInLinearSpace=!1,this.usePhysicalLightFalloff=!0,this.useRadianceOverAlpha=!0,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this._renderTargets=new e.SmartArray(16),this._worldViewProjectionMatrix=e.Matrix.Zero(),this._globalAmbientColor=new e.Color3(0,0,0),this._tempColor=new e.Color3,this._defines=new t,this._cachedDefines=new t,this._myScene=null,this._myShadowGenerator=null,this._cachedDefines.BonesPerMesh=-1,this.getRenderTargetTextures=function(){return o._renderTargets.reset(),o.reflectionTexture&&o.reflectionTexture.isRenderTarget&&o._renderTargets.push(o.reflectionTexture),o.refractionTexture&&o.refractionTexture.isRenderTarget&&o._renderTargets.push(o.refractionTexture),o._renderTargets}}return __extends(r,i),Object.defineProperty(r.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!0,configurable:!0}),r.prototype.needAlphaBlending=function(){return!this.linkRefractionWithTransparency&&(this.alpha<1||null!=this.opacityTexture||this._shouldUseAlphaFromAlbedoTexture()||this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled)},r.prototype.needAlphaTesting=function(){return!this.linkRefractionWithTransparency&&(null!=this.albedoTexture&&this.albedoTexture.hasAlpha)},r.prototype._shouldUseAlphaFromAlbedoTexture=function(){return null!=this.albedoTexture&&this.albedoTexture.hasAlpha&&this.useAlphaFromAlbedoTexture},r.prototype.getAlphaTestTexture=function(){return this.albedoTexture},r.prototype._checkCache=function(e,t,i){return!t||this._defines.INSTANCES===i&&!(!t._materialDefines||!t._materialDefines.isEqual(this._defines))},r.prototype.convertColorToLinearSpaceToRef=function(e,t){r.convertColorToLinearSpaceToRef(e,t,this.useScalarInLinearSpace)},r.convertColorToLinearSpaceToRef=function(e,t,i){i?(t.r=e.r,t.g=e.g,t.b=e.b):e.toLinearSpaceToRef(t)},r.BindLights=function(t,i,n,o,s,a,h){for(var c=0,l=!1,u=0;u<t.lights.length;u++){var d=t.lights[u];if(d.isEnabled()&&d.canAffectMesh(i)&&(e.MaterialHelper.BindLightProperties(d,n,c),this.convertColorToLinearSpaceToRef(d.diffuse,r._scaledAlbedo,s),r._scaledAlbedo.scaleToRef(d.intensity,r._scaledAlbedo),n.setColor4("vLightDiffuse"+c,r._scaledAlbedo,h?d.radius:d.range),o.SPECULARTERM&&(this.convertColorToLinearSpaceToRef(d.specular,r._scaledReflectivity,s),r._scaledReflectivity.scaleToRef(d.intensity,r._scaledReflectivity),n.setColor3("vLightSpecular"+c,r._scaledReflectivity)),t.shadowsEnabled&&(l=e.MaterialHelper.BindLightShadow(d,t,i,c,n,l)),c++,c===a))break}},r.prototype.isReady=function(i,r){if(this.checkReadyOnlyOnce&&this._wasPreviouslyReady)return!0;var n=this.getScene(),o=n.getEngine(),s=!1,a=!1;if(this._defines.reset(),n.lightsEnabled&&!this.disableLighting&&(s=e.MaterialHelper.PrepareDefinesForLights(n,i,this._defines,this.maxSimultaneousLights)||s),!this.checkReadyOnEveryCall&&this._renderId===n.getRenderId()&&this._checkCache(n,i,r))return!0;if(n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(this._defines.LODBASEDMICROSFURACE=!0),this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.albedoTexture.isReady())return!1;a=!0,this._defines.ALBEDO=!0}if(this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled){if(!this.ambientTexture.isReady())return!1;a=!0,this._defines.AMBIENT=!0}if(this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled){if(!this.opacityTexture.isReady())return!1;a=!0,this._defines.OPACITY=!0,this.opacityTexture.getAlphaFromRGB&&(this._defines.OPACITYRGB=!0)}if(this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady())return!1;switch(s=!0,this._defines.REFLECTION=!0,this.reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE&&(this._defines.INVERTCUBICMAP=!0),this._defines.REFLECTIONMAP_3D=this.reflectionTexture.isCube,this.reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:this._defines.REFLECTIONMAP_CUBIC=!0;break;case e.Texture.EXPLICIT_MODE:this._defines.REFLECTIONMAP_EXPLICIT=!0;break;case e.Texture.PLANAR_MODE:this._defines.REFLECTIONMAP_PLANAR=!0;break;case e.Texture.PROJECTION_MODE:this._defines.REFLECTIONMAP_PROJECTION=!0;break;case e.Texture.SKYBOX_MODE:this._defines.REFLECTIONMAP_SKYBOX=!0;break;case e.Texture.SPHERICAL_MODE:this._defines.REFLECTIONMAP_SPHERICAL=!0;break;case e.Texture.EQUIRECTANGULAR_MODE:this._defines.REFLECTIONMAP_EQUIRECTANGULAR=!0}this.reflectionTexture instanceof e.HDRCubeTexture&&this.reflectionTexture&&(this._defines.USESPHERICALFROMREFLECTIONMAP=!0,s=!0,this.reflectionTexture.isPMREM&&(this._defines.USEPMREMREFLECTION=!0))}if(this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled){if(!this.lightmapTexture.isReady())return!1;a=!0,this._defines.LIGHTMAP=!0,this._defines.USELIGHTMAPASSHADOWMAP=this.useLightmapAsShadowmap}if(this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady())return!1;a=!0,this._defines.EMISSIVE=!0}if(e.StandardMaterial.SpecularTextureEnabled)if(this.metallicTexture){if(!this.metallicTexture.isReady())return!1;a=!0,this._defines.METALLICWORKFLOW=!0,this._defines.METALLICROUGHNESSGSTOREINALPHA=this.useRoughnessFromMetallicTextureAlpha,this._defines.METALLICROUGHNESSGSTOREINGREEN=!this.useRoughnessFromMetallicTextureAlpha&&this.useRoughnessFromMetallicTextureGreen}else if(this.reflectivityTexture){if(!this.reflectivityTexture.isReady())return!1;a=!0,this._defines.REFLECTIVITY=!0,this._defines.MICROSURFACEFROMREFLECTIVITYMAP=this.useMicroSurfaceFromReflectivityMapAlpha,this._defines.MICROSURFACEAUTOMATIC=this.useAutoMicroSurfaceFromReflectivityMap}if(n.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap){if(!this.bumpTexture.isReady())return!1;a=!0,this._defines.BUMP=!0,this.useParallax&&this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._defines.PARALLAX=!0,this.useParallaxOcclusion&&(this._defines.PARALLAXOCCLUSION=!0)),this.invertNormalMapX&&(this._defines.INVERTNORMALMAPX=!0),this.invertNormalMapY&&(this._defines.INVERTNORMALMAPY=!0)}if(this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled){if(!this.refractionTexture.isReady())return!1;a=!0,this._defines.REFRACTION=!0,this._defines.REFRACTIONMAP_3D=this.refractionTexture.isCube,this.linkRefractionWithTransparency&&(this._defines.LINKREFRACTIONTOTRANSPARENCY=!0),this.refractionTexture instanceof e.HDRCubeTexture&&(this._defines.REFRACTIONMAPINLINEARSPACE=!0,this.refractionTexture.isPMREM&&(this._defines.USEPMREMREFRACTION=!0))}if(this.cameraColorGradingTexture&&e.StandardMaterial.ColorGradingTextureEnabled){if(!this.cameraColorGradingTexture.isReady())return!1;this._defines.CAMERACOLORGRADING=!0}}if(n.clipPlane&&(this._defines.CLIPPLANE=!0),o.getAlphaTesting()&&(this._defines.ALPHATEST=!0),this._shouldUseAlphaFromAlbedoTexture()&&(this._defines.ALPHAFROMALBEDO=!0),this.useEmissiveAsIllumination&&(this._defines.EMISSIVEASILLUMINATION=!0),this.linkEmissiveWithAlbedo&&(this._defines.LINKEMISSIVEWITHALBEDO=!0),this.useLogarithmicDepth&&(this._defines.LOGARITHMICDEPTH=!0),1!=this.cameraContrast&&(this._defines.CAMERACONTRAST=!0),1!=this.cameraExposure&&(this._defines.CAMERATONEMAP=!0),this.cameraColorCurves&&(this._defines.CAMERACOLORCURVES=!0),1==this.overloadedShadeIntensity&&1==this.overloadedShadowIntensity||(this._defines.OVERLOADEDSHADOWVALUES=!0),(this.overloadedMicroSurfaceIntensity>0||this.overloadedEmissiveIntensity>0||this.overloadedReflectivityIntensity>0||this.overloadedAlbedoIntensity>0||this.overloadedAmbientIntensity>0||this.overloadedReflectionIntensity>0)&&(this._defines.OVERLOADEDVALUES=!0),(this.pointsCloud||n.forcePointsCloud)&&(this._defines.POINTSIZE=!0),n.fogEnabled&&i&&i.applyFog&&n.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled&&(this._defines.FOG=!0),e.StandardMaterial.FresnelEnabled&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled||this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled)&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&(this._defines.OPACITYFRESNEL=!0),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._defines.EMISSIVEFRESNEL=!0),s=!0,this._defines.FRESNEL=!0),this._defines.SPECULARTERM&&this.useSpecularOverAlpha&&(this._defines.SPECULAROVERALPHA=!0),this.usePhysicalLightFalloff&&(this._defines.USEPHYSICALLIGHTFALLOFF=!0),this.useRadianceOverAlpha&&(this._defines.RADIANCEOVERALPHA=!0),i&&(s&&i.isVerticesDataPresent(e.VertexBuffer.NormalKind)&&(this._defines.NORMAL=!0),a&&(i.isVerticesDataPresent(e.VertexBuffer.UVKind)&&(this._defines.UV1=!0),i.isVerticesDataPresent(e.VertexBuffer.UV2Kind)&&(this._defines.UV2=!0)),i.useVertexColors&&i.isVerticesDataPresent(e.VertexBuffer.ColorKind)&&(this._defines.VERTEXCOLOR=!0,i.hasVertexAlpha&&(this._defines.VERTEXALPHA=!0)),i.useBones&&i.computeBonesUsingShaders&&(this._defines.NUM_BONE_INFLUENCERS=i.numBoneInfluencers,this._defines.BonesPerMesh=i.skeleton.bones.length+1),r&&(this._defines.INSTANCES=!0)),!this._defines.isEqual(this._cachedDefines)){this._defines.cloneTo(this._cachedDefines),n.resetCachedMaterial();var h=new e.EffectFallbacks;this._defines.REFLECTION&&h.addFallback(0,"REFLECTION"),this._defines.REFRACTION&&h.addFallback(0,"REFRACTION"),this._defines.REFLECTIVITY&&h.addFallback(0,"REFLECTIVITY"),this._defines.BUMP&&h.addFallback(0,"BUMP"),this._defines.PARALLAX&&h.addFallback(1,"PARALLAX"),this._defines.PARALLAXOCCLUSION&&h.addFallback(0,"PARALLAXOCCLUSION"),this._defines.SPECULAROVERALPHA&&h.addFallback(0,"SPECULAROVERALPHA"),this._defines.FOG&&h.addFallback(1,"FOG"),this._defines.POINTSIZE&&h.addFallback(0,"POINTSIZE"),this._defines.LOGARITHMICDEPTH&&h.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(this._defines,h,this.maxSimultaneousLights),this._defines.SPECULARTERM&&h.addFallback(0,"SPECULARTERM"),this._defines.OPACITYFRESNEL&&h.addFallback(1,"OPACITYFRESNEL"),this._defines.EMISSIVEFRESNEL&&h.addFallback(2,"EMISSIVEFRESNEL"),this._defines.FRESNEL&&h.addFallback(3,"FRESNEL"),this._defines.NUM_BONE_INFLUENCERS>0&&h.addCPUSkinningFallback(0,i);var c=[e.VertexBuffer.PositionKind];this._defines.NORMAL&&c.push(e.VertexBuffer.NormalKind),this._defines.UV1&&c.push(e.VertexBuffer.UVKind),this._defines.UV2&&c.push(e.VertexBuffer.UV2Kind),this._defines.VERTEXCOLOR&&c.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(c,i,this._defines,h),e.MaterialHelper.PrepareAttributesForInstances(c,this._defines);var l=this._defines.toString(),u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vReflectivityInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","depthValues","opacityParts","emissiveLeftColor","emissiveRightColor","vLightingIntensity","vOverloadedShadowIntensity","vOverloadedIntensity","vOverloadedAlbedo","vOverloadedReflection","vOverloadedReflectivity","vOverloadedEmissive","vOverloadedMicroSurface","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX","vSphericalYY","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vMicrosurfaceTextureLods","vCameraInfos"],d=["albedoSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","reflectivitySampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"];e.ColorCurves.PrepareUniforms(u),e.ColorGradingTexture.PrepareUniformsAndSamplers(u,d),e.MaterialHelper.PrepareUniformsAndSamplersList(u,d,this._defines,this.maxSimultaneousLights),this._effect=n.getEngine().createEffect("pbr",c,u,d,l,h,this.onCompiled,this.onError,{maxSimultaneousLights:this.maxSimultaneousLights})}return!!this._effect.isReady()&&(this._renderId=n.getRenderId(),this._wasPreviouslyReady=!0,i&&(i._materialDefines||(i._materialDefines=new t),this._defines.cloneTo(i._materialDefines)),!0)},r.prototype.unbind=function(){this.reflectionTexture&&this.reflectionTexture.isRenderTarget&&this._effect.setTexture("reflection2DSampler",null),this.refractionTexture&&this.refractionTexture.isRenderTarget&&this._effect.setTexture("refraction2DSampler",null),i.prototype.unbind.call(this)},r.prototype.bindOnlyWorldMatrix=function(e){this._effect.setMatrix("world",e)},r.prototype.bind=function(t,n){if(this._myScene=this.getScene(),this.bindOnlyWorldMatrix(t),e.MaterialHelper.BindBonesParameters(n,this._effect),this._myScene.getCachedMaterial()!==this){if(this._effect.setMatrix("viewProjection",this._myScene.getTransformMatrix()),e.StandardMaterial.FresnelEnabled&&(this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._effect.setColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._effect.setColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._effect.setColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),this._myScene.texturesEnabled){if(this.albedoTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._effect.setTexture("albedoSampler",this.albedoTexture),this._effect.setFloat2("vAlbedoInfos",this.albedoTexture.coordinatesIndex,this.albedoTexture.level),
this._effect.setMatrix("albedoMatrix",this.albedoTexture.getTextureMatrix())),this.ambientTexture&&e.StandardMaterial.AmbientTextureEnabled&&(this._effect.setTexture("ambientSampler",this.ambientTexture),this._effect.setFloat3("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level,this.ambientTextureStrength),this._effect.setMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix())),this.opacityTexture&&e.StandardMaterial.OpacityTextureEnabled&&(this._effect.setTexture("opacitySampler",this.opacityTexture),this._effect.setFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level),this._effect.setMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix())),this.reflectionTexture&&e.StandardMaterial.ReflectionTextureEnabled&&(this._microsurfaceTextureLods.x=Math.round(Math.log(this.reflectionTexture.getSize().width)*Math.LOG2E),this.reflectionTexture.isCube?this._effect.setTexture("reflectionCubeSampler",this.reflectionTexture):this._effect.setTexture("reflection2DSampler",this.reflectionTexture),this._effect.setMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix()),this._effect.setFloat2("vReflectionInfos",this.reflectionTexture.level,0),this._defines.USESPHERICALFROMREFLECTIONMAP&&(this._effect.setFloat3("vSphericalX",this.reflectionTexture.sphericalPolynomial.x.x,this.reflectionTexture.sphericalPolynomial.x.y,this.reflectionTexture.sphericalPolynomial.x.z),this._effect.setFloat3("vSphericalY",this.reflectionTexture.sphericalPolynomial.y.x,this.reflectionTexture.sphericalPolynomial.y.y,this.reflectionTexture.sphericalPolynomial.y.z),this._effect.setFloat3("vSphericalZ",this.reflectionTexture.sphericalPolynomial.z.x,this.reflectionTexture.sphericalPolynomial.z.y,this.reflectionTexture.sphericalPolynomial.z.z),this._effect.setFloat3("vSphericalXX",this.reflectionTexture.sphericalPolynomial.xx.x,this.reflectionTexture.sphericalPolynomial.xx.y,this.reflectionTexture.sphericalPolynomial.xx.z),this._effect.setFloat3("vSphericalYY",this.reflectionTexture.sphericalPolynomial.yy.x,this.reflectionTexture.sphericalPolynomial.yy.y,this.reflectionTexture.sphericalPolynomial.yy.z),this._effect.setFloat3("vSphericalZZ",this.reflectionTexture.sphericalPolynomial.zz.x,this.reflectionTexture.sphericalPolynomial.zz.y,this.reflectionTexture.sphericalPolynomial.zz.z),this._effect.setFloat3("vSphericalXY",this.reflectionTexture.sphericalPolynomial.xy.x,this.reflectionTexture.sphericalPolynomial.xy.y,this.reflectionTexture.sphericalPolynomial.xy.z),this._effect.setFloat3("vSphericalYZ",this.reflectionTexture.sphericalPolynomial.yz.x,this.reflectionTexture.sphericalPolynomial.yz.y,this.reflectionTexture.sphericalPolynomial.yz.z),this._effect.setFloat3("vSphericalZX",this.reflectionTexture.sphericalPolynomial.zx.x,this.reflectionTexture.sphericalPolynomial.zx.y,this.reflectionTexture.sphericalPolynomial.zx.z))),this.emissiveTexture&&e.StandardMaterial.EmissiveTextureEnabled&&(this._effect.setTexture("emissiveSampler",this.emissiveTexture),this._effect.setFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level),this._effect.setMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix())),this.lightmapTexture&&e.StandardMaterial.LightmapTextureEnabled&&(this._effect.setTexture("lightmapSampler",this.lightmapTexture),this._effect.setFloat2("vLightmapInfos",this.lightmapTexture.coordinatesIndex,this.lightmapTexture.level),this._effect.setMatrix("lightmapMatrix",this.lightmapTexture.getTextureMatrix())),e.StandardMaterial.SpecularTextureEnabled&&(this.metallicTexture?(this._effect.setTexture("reflectivitySampler",this.metallicTexture),this._effect.setFloat2("vReflectivityInfos",this.metallicTexture.coordinatesIndex,this.metallicTexture.level),this._effect.setMatrix("reflectivityMatrix",this.metallicTexture.getTextureMatrix())):this.reflectivityTexture&&(this._effect.setTexture("reflectivitySampler",this.reflectivityTexture),this._effect.setFloat2("vReflectivityInfos",this.reflectivityTexture.coordinatesIndex,this.reflectivityTexture.level),this._effect.setMatrix("reflectivityMatrix",this.reflectivityTexture.getTextureMatrix()))),this.bumpTexture&&this._myScene.getEngine().getCaps().standardDerivatives&&e.StandardMaterial.BumpTextureEnabled&&!this.disableBumpMap&&(this._effect.setTexture("bumpSampler",this.bumpTexture),this._effect.setFloat3("vBumpInfos",this.bumpTexture.coordinatesIndex,1/this.bumpTexture.level,this.parallaxScaleBias),this._effect.setMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix())),this.refractionTexture&&e.StandardMaterial.RefractionTextureEnabled){this._microsurfaceTextureLods.y=Math.round(Math.log(this.refractionTexture.getSize().width)*Math.LOG2E);var o=1;this.refractionTexture.isCube?this._effect.setTexture("refractionCubeSampler",this.refractionTexture):(this._effect.setTexture("refraction2DSampler",this.refractionTexture),this._effect.setMatrix("refractionMatrix",this.refractionTexture.getReflectionTextureMatrix()),this.refractionTexture.depth&&(o=this.refractionTexture.depth)),this._effect.setFloat4("vRefractionInfos",this.refractionTexture.level,this.indexOfRefraction,o,this.invertRefractionY?-1:1)}(this.reflectionTexture||this.refractionTexture)&&this._effect.setFloat2("vMicrosurfaceTextureLods",this._microsurfaceTextureLods.x,this._microsurfaceTextureLods.y),this.cameraColorGradingTexture&&e.StandardMaterial.ColorGradingTextureEnabled&&e.ColorGradingTexture.Bind(this.cameraColorGradingTexture,this._effect)}e.MaterialHelper.BindClipPlane(this._effect,this._myScene),this.pointsCloud&&this._effect.setFloat("pointSize",this.pointSize),this._myScene.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),this.convertColorToLinearSpaceToRef(this.reflectivityColor,r._scaledReflectivity),this._effect.setVector3("vEyePosition",this._myScene._mirroredCameraPosition?this._myScene._mirroredCameraPosition:this._myScene.activeCamera.position),this._effect.setColor3("vAmbientColor",this._globalAmbientColor),this._effect.setColor4("vReflectivityColor",r._scaledReflectivity,this.microSurface),this.convertColorToLinearSpaceToRef(this.emissiveColor,r._scaledEmissive),this._effect.setColor3("vEmissiveColor",r._scaledEmissive),this.convertColorToLinearSpaceToRef(this.reflectionColor,r._scaledReflection),this._effect.setColor3("vReflectionColor",r._scaledReflection)}this._myScene.getCachedMaterial()===this&&this.isFrozen||(this.convertColorToLinearSpaceToRef(this.albedoColor,r._scaledAlbedo),this._effect.setColor4("vAlbedoColor",r._scaledAlbedo,this.alpha*n.visibility),this._myScene.lightsEnabled&&!this.disableLighting&&r.BindLights(this._myScene,n,this._effect,this._defines,this.useScalarInLinearSpace,this.maxSimultaneousLights,this.usePhysicalLightFalloff),(this._myScene.fogEnabled&&n.applyFog&&this._myScene.fogMode!==e.Scene.FOGMODE_NONE||this.reflectionTexture)&&this._effect.setMatrix("view",this._myScene.getViewMatrix()),e.MaterialHelper.BindFogParameters(this._myScene,n,this._effect),this._lightingInfos.x=this.directIntensity,this._lightingInfos.y=this.emissiveIntensity,this._lightingInfos.z=this.environmentIntensity,this._lightingInfos.w=this.specularIntensity,this._effect.setVector4("vLightingIntensity",this._lightingInfos),this._overloadedShadowInfos.x=this.overloadedShadowIntensity,this._overloadedShadowInfos.y=this.overloadedShadeIntensity,this._effect.setVector4("vOverloadedShadowIntensity",this._overloadedShadowInfos),this._cameraInfos.x=this.cameraExposure,this._cameraInfos.y=this.cameraContrast,this._effect.setVector4("vCameraInfos",this._cameraInfos),this.cameraColorCurves&&e.ColorCurves.Bind(this.cameraColorCurves,this._effect),this._overloadedIntensity.x=this.overloadedAmbientIntensity,this._overloadedIntensity.y=this.overloadedAlbedoIntensity,this._overloadedIntensity.z=this.overloadedReflectivityIntensity,this._overloadedIntensity.w=this.overloadedEmissiveIntensity,this._effect.setVector4("vOverloadedIntensity",this._overloadedIntensity),this.convertColorToLinearSpaceToRef(this.overloadedAmbient,this._tempColor),this._effect.setColor3("vOverloadedAmbient",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedAlbedo,this._tempColor),this._effect.setColor3("vOverloadedAlbedo",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedReflectivity,this._tempColor),this._effect.setColor3("vOverloadedReflectivity",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedEmissive,this._tempColor),this._effect.setColor3("vOverloadedEmissive",this._tempColor),this.convertColorToLinearSpaceToRef(this.overloadedReflection,this._tempColor),this._effect.setColor3("vOverloadedReflection",this._tempColor),this._overloadedMicroSurface.x=this.overloadedMicroSurface,this._overloadedMicroSurface.y=this.overloadedMicroSurfaceIntensity,this._overloadedMicroSurface.z=this.overloadedReflectionIntensity,this._effect.setVector3("vOverloadedMicroSurface",this._overloadedMicroSurface),e.MaterialHelper.BindLogDepth(this._defines,this._effect,this._myScene)),i.prototype.bind.call(this,t,n),this._myScene=null},r.prototype.getAnimatables=function(){var e=[];return this.albedoTexture&&this.albedoTexture.animations&&this.albedoTexture.animations.length>0&&e.push(this.albedoTexture),this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0&&e.push(this.ambientTexture),this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0&&e.push(this.opacityTexture),this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0&&e.push(this.reflectionTexture),this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0&&e.push(this.emissiveTexture),this.metallicTexture&&this.metallicTexture.animations&&this.metallicTexture.animations.length>0?e.push(this.metallicTexture):this.reflectivityTexture&&this.reflectivityTexture.animations&&this.reflectivityTexture.animations.length>0&&e.push(this.reflectivityTexture),this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this.lightmapTexture&&this.lightmapTexture.animations&&this.lightmapTexture.animations.length>0&&e.push(this.lightmapTexture),this.refractionTexture&&this.refractionTexture.animations&&this.refractionTexture.animations.length>0&&e.push(this.refractionTexture),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.animations&&this.cameraColorGradingTexture.animations.length>0&&e.push(this.cameraColorGradingTexture),e},r.prototype.dispose=function(e,t){t&&(this.albedoTexture&&this.albedoTexture.dispose(),this.ambientTexture&&this.ambientTexture.dispose(),this.opacityTexture&&this.opacityTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose(),this.emissiveTexture&&this.emissiveTexture.dispose(),this.metallicTexture&&this.metallicTexture.dispose(),this.reflectivityTexture&&this.reflectivityTexture.dispose(),this.bumpTexture&&this.bumpTexture.dispose(),this.lightmapTexture&&this.lightmapTexture.dispose(),this.refractionTexture&&this.refractionTexture.dispose(),this.cameraColorGradingTexture&&this.cameraColorGradingTexture.dispose()),i.prototype.dispose.call(this,e,t)},r.prototype.clone=function(t){var i=this;return e.SerializationHelper.Clone((function(){return new r(t,i.getScene())}),this)},r.prototype.serialize=function(){var t=e.SerializationHelper.Serialize(this);return t.customType="BABYLON.PBRMaterial",t},r.Parse=function(t,i,n){return e.SerializationHelper.Parse((function(){return new r(t.name,i)}),t,i,n)},r._scaledAlbedo=new e.Color3,r._scaledReflectivity=new e.Color3,r._scaledEmissive=new e.Color3,r._scaledReflection=new e.Color3,__decorate([e.serialize()],r.prototype,"directIntensity",void 0),__decorate([e.serialize()],r.prototype,"emissiveIntensity",void 0),__decorate([e.serialize()],r.prototype,"environmentIntensity",void 0),__decorate([e.serialize()],r.prototype,"specularIntensity",void 0),__decorate([e.serialize()],r.prototype,"disableBumpMap",void 0),__decorate([e.serialize()],r.prototype,"overloadedShadowIntensity",void 0),__decorate([e.serialize()],r.prototype,"overloadedShadeIntensity",void 0),__decorate([e.serialize()],r.prototype,"cameraExposure",void 0),__decorate([e.serialize()],r.prototype,"cameraContrast",void 0),__decorate([e.serializeAsTexture()],r.prototype,"cameraColorGradingTexture",void 0),__decorate([e.serializeAsColorCurves()],r.prototype,"cameraColorCurves",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedAmbient",void 0),__decorate([e.serialize()],r.prototype,"overloadedAmbientIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedAlbedo",void 0),__decorate([e.serialize()],r.prototype,"overloadedAlbedoIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedReflectivity",void 0),__decorate([e.serialize()],r.prototype,"overloadedReflectivityIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedEmissive",void 0),__decorate([e.serialize()],r.prototype,"overloadedEmissiveIntensity",void 0),__decorate([e.serializeAsColor3()],r.prototype,"overloadedReflection",void 0),__decorate([e.serialize()],r.prototype,"overloadedReflectionIntensity",void 0),__decorate([e.serialize()],r.prototype,"overloadedMicroSurface",void 0),__decorate([e.serialize()],r.prototype,"overloadedMicroSurfaceIntensity",void 0),__decorate([e.serializeAsTexture()],r.prototype,"albedoTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"ambientTexture",void 0),__decorate([e.serialize()],r.prototype,"ambientTextureStrength",void 0),__decorate([e.serializeAsTexture()],r.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"reflectivityTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"metallicTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture()],r.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],r.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("albedo")],r.prototype,"albedoColor",void 0),__decorate([e.serializeAsColor3("reflectivity")],r.prototype,"reflectivityColor",void 0),__decorate([e.serializeAsColor3("reflection")],r.prototype,"reflectionColor",void 0),__decorate([e.serializeAsColor3("emissive")],r.prototype,"emissiveColor",void 0),__decorate([e.serialize()],r.prototype,"microSurface",void 0),__decorate([e.serialize()],r.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],r.prototype,"invertRefractionY",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters()],r.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize()],r.prototype,"linkRefractionWithTransparency",void 0),__decorate([e.serialize()],r.prototype,"linkEmissiveWithAlbedo",void 0),__decorate([e.serialize()],r.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serialize()],r.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize()],r.prototype,"useAlphaFromAlbedoTexture",void 0),__decorate([e.serialize()],r.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),__decorate([e.serialize()],r.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),__decorate([e.serialize()],r.prototype,"useRoughnessFromMetallicTextureGreen",void 0),__decorate([e.serialize()],r.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),__decorate([e.serialize()],r.prototype,"useScalarInLinearSpace",void 0),__decorate([e.serialize()],r.prototype,"usePhysicalLightFalloff",void 0),__decorate([e.serialize()],r.prototype,"useRadianceOverAlpha",void 0),__decorate([e.serialize()],r.prototype,"useParallax",void 0),__decorate([e.serialize()],r.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],r.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize()],r.prototype,"disableLighting",void 0),__decorate([e.serialize()],r.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapX",void 0),__decorate([e.serialize()],r.prototype,"invertNormalMapY",void 0),__decorate([e.serialize()],r.prototype,"useLogarithmicDepth",null),r})(e.Material);e.PBRMaterial=i})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(t){var i=this;this._transformationMatrix=e.Matrix.Identity(),this._enabled=!1,this._labelsEnabled=!1,this._displayStatistics=!0,this._displayTree=!1,this._displayLogs=!1,this._skeletonViewers=new Array,this._identityMatrix=e.Matrix.Identity(),this.axisRatio=.02,this.accentColor="orange",this._scene=t,this._syncPositions=function(){var e=i._scene.getEngine(),t=e.getRenderingCanvasClientRect();i._showUI&&(i._statsDiv.style.left=t.width-410+"px",i._statsDiv.style.top=t.height-290+"px",i._statsDiv.style.width="400px",i._statsDiv.style.height="auto",i._statsSubsetDiv.style.maxHeight="240px",i._optionsDiv.style.left="0px",i._optionsDiv.style.top="10px",i._optionsDiv.style.width="200px",i._optionsDiv.style.height="auto",i._optionsSubsetDiv.style.maxHeight=t.height-225+"px",i._logDiv.style.left="0px",i._logDiv.style.top=t.height-170+"px",i._logDiv.style.width="600px",i._logDiv.style.height="160px",i._treeDiv.style.left=t.width-310+"px",i._treeDiv.style.top="10px",i._treeDiv.style.width="300px",i._treeDiv.style.height="auto",i._treeSubsetDiv.style.maxHeight=t.height-340+"px"),i._globalDiv.style.left=t.left+"px",i._globalDiv.style.top=t.top+"px",i._drawingCanvas.style.left="0px",i._drawingCanvas.style.top="0px",i._drawingCanvas.style.width=e.getRenderWidth()+"px",i._drawingCanvas.style.height=e.getRenderHeight()+"px";var r=window.devicePixelRatio||1,n=i._drawingContext,o=n.webkitBackingStorePixelRatio||n.mozBackingStorePixelRatio||n.msBackingStorePixelRatio||n.oBackingStorePixelRatio||n.backingStorePixelRatio||1;i._ratio=r/o,i._drawingCanvas.width=e.getRenderWidth()*i._ratio,i._drawingCanvas.height=e.getRenderHeight()*i._ratio},this._onCanvasClick=function(e){i._clickPosition={x:e.clientX*i._ratio,y:e.clientY*i._ratio}},this._syncUI=function(){i._showUI&&(i._displayStatistics?(i._displayStats(),i._statsDiv.style.display=""):i._statsDiv.style.display="none",i._displayLogs?i._logDiv.style.display="":i._logDiv.style.display="none",i._displayTree?(i._treeDiv.style.display="",i._needToRefreshMeshesTree&&(i._needToRefreshMeshesTree=!1,i._refreshMeshesTreeContent())):i._treeDiv.style.display="none")},this._syncData=function(){if(i._labelsEnabled||!i._showUI){i._camera.getViewMatrix().multiplyToRef(i._camera.getProjectionMatrix(),i._transformationMatrix),i._drawingContext.clearRect(0,0,i._drawingCanvas.width,i._drawingCanvas.height);var t,r,n=i._scene.getEngine(),o=i._camera.viewport,s=o.toGlobal(n.getRenderWidth(),n.getRenderHeight()),a=i._camera.getActiveMeshes();for(t=0;t<a.length;t++){var h=a.data[t],c=h.getBoundingInfo().boundingSphere.center;r=e.Vector3.Project(c,h.getWorldMatrix(),i._transformationMatrix,s),(h.renderOverlay||i.shouldDisplayAxis&&i.shouldDisplayAxis(h))&&i._renderAxis(r,h,s),i.shouldDisplayLabel&&!i.shouldDisplayLabel(h)||i._renderLabel(h.name,r,12,(function(){h.renderOverlay=!h.renderOverlay}),(function(){return h.renderOverlay?"red":"black"}))}var l=i._scene.cameras;for(t=0;t<l.length;t++){var u=l[t];u!==i._camera&&(r=e.Vector3.Project(e.Vector3.Zero(),u.getWorldMatrix(),i._transformationMatrix,s),i.shouldDisplayLabel&&!i.shouldDisplayLabel(u)||i._renderLabel(u.name,r,12,(function(){i._camera.detachControl(n.getRenderingCanvas()),i._camera=u,i._camera.attachControl(n.getRenderingCanvas())}),(function(){return"purple"})))}var d=i._scene.lights;for(t=0;t<d.length;t++){var f=d[t];f.position&&(r=e.Vector3.Project(f.getAbsolutePosition(),i._identityMatrix,i._transformationMatrix,s),i.shouldDisplayLabel&&!i.shouldDisplayLabel(f)||i._renderLabel(f.name,r,-20,(function(){f.setEnabled(!f.isEnabled())}),(function(){return f.isEnabled()?"orange":"gray"})))}}i._clickPosition=void 0}}return t.prototype._refreshMeshesTreeContent=function(){for(;this._treeSubsetDiv.hasChildNodes();)this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);var e=this._scene.meshes.slice(0,this._scene.meshes.length);e.sort((function(e,t){return e.name===t.name?0:e.name>t.name?1:-1}));for(var t=0;t<e.length;t++){var i=e[t];i.isEnabled()&&this._generateAdvancedCheckBox(this._treeSubsetDiv,i.name,i.getTotalVertices()+" verts",i.isVisible,(function(e,t){t.isVisible=e.checked}),i)}},t.prototype._renderSingleAxis=function(e,t,i,r,n){this._drawingContext.beginPath(),this._drawingContext.moveTo(e.x,e.y),this._drawingContext.lineTo(t.x,t.y),this._drawingContext.strokeStyle=n,this._drawingContext.lineWidth=4,this._drawingContext.stroke(),this._drawingContext.font="normal 14px Segoe UI",this._drawingContext.fillStyle=n,this._drawingContext.fillText(r,i.x,i.y)},t.prototype._renderAxis=function(t,i,r){var n=i.getBoundingInfo().boundingSphere.center,o=i.getWorldMatrix(),s=e.Vector3.UnprojectFromTransform(t.add(new e.Vector3(this._drawingCanvas.width*this.axisRatio,0,0)),r.width,r.height,o,this._transformationMatrix),a=s.subtract(n).length(),h=e.Vector3.Project(n.add(new e.Vector3(a,0,0)),o,this._transformationMatrix,r),c=e.Vector3.Project(n.add(new e.Vector3(1.5*a,0,0)),o,this._transformationMatrix,r);this._renderSingleAxis(t,h,c,"x","#FF0000");var l=e.Vector3.Project(n.add(new e.Vector3(0,a,0)),o,this._transformationMatrix,r),u=e.Vector3.Project(n.add(new e.Vector3(0,1.5*a,0)),o,this._transformationMatrix,r);this._renderSingleAxis(t,l,u,"y","#00FF00");var d=e.Vector3.Project(n.add(new e.Vector3(0,0,a)),o,this._transformationMatrix,r),f=e.Vector3.Project(n.add(new e.Vector3(0,0,1.5*a)),o,this._transformationMatrix,r);this._renderSingleAxis(t,d,f,"z","#0000FF")},t.prototype._renderLabel=function(e,t,i,r,n){if(t.z>0&&t.z<1){this._drawingContext.font="normal 12px Segoe UI";var o=this._drawingContext.measureText(e),s=t.x-o.width/2,a=t.y,h=this._drawingCanvas.getBoundingClientRect();this._showUI&&this._isClickInsideRect(h.left*this._ratio+s-5,h.top*this._ratio+a-i-12,o.width+10,17)&&r(),this._drawingContext.beginPath(),this._drawingContext.rect(s-5,a-i-12,o.width+10,17),this._drawingContext.fillStyle=n(),this._drawingContext.globalAlpha=.5,this._drawingContext.fill(),this._drawingContext.globalAlpha=1,this._drawingContext.strokeStyle="#FFFFFF",this._drawingContext.lineWidth=1,this._drawingContext.stroke(),this._drawingContext.fillStyle="#FFFFFF",this._drawingContext.fillText(e,s,a-i),this._drawingContext.beginPath(),this._drawingContext.arc(t.x,a,5,0,2*Math.PI,!1),this._drawingContext.fill()}},t.prototype._isClickInsideRect=function(e,t,i,r){return!!this._clickPosition&&(!(this._clickPosition.x<e||this._clickPosition.x>e+i)&&!(this._clickPosition.y<t||this._clickPosition.y>t+r))},t.prototype.isVisible=function(){return this._enabled},t.prototype.hide=function(){if(this._enabled){this._enabled=!1;var t=this._scene.getEngine();this._scene.unregisterBeforeRender(this._syncData),this._scene.unregisterAfterRender(this._syncUI),this._rootElement.removeChild(this._globalDiv),this._scene.forceShowBoundingBoxes=!1,this._scene.forceWireframe=!1,e.StandardMaterial.DiffuseTextureEnabled=!0,e.StandardMaterial.AmbientTextureEnabled=!0,e.StandardMaterial.SpecularTextureEnabled=!0,e.StandardMaterial.EmissiveTextureEnabled=!0,e.StandardMaterial.BumpTextureEnabled=!0,e.StandardMaterial.OpacityTextureEnabled=!0,e.StandardMaterial.ReflectionTextureEnabled=!0,e.StandardMaterial.LightmapTextureEnabled=!0,e.StandardMaterial.RefractionTextureEnabled=!0,e.StandardMaterial.ColorGradingTextureEnabled=!0,this._scene.shadowsEnabled=!0,this._scene.particlesEnabled=!0,this._scene.postProcessesEnabled=!0,this._scene.collisionsEnabled=!0,this._scene.lightsEnabled=!0,this._scene.texturesEnabled=!0,this._scene.lensFlaresEnabled=!0,this._scene.proceduralTexturesEnabled=!0,this._scene.renderTargetsEnabled=!0,this._scene.probesEnabled=!0,t.getRenderingCanvas().removeEventListener("click",this._onCanvasClick),this._clearSkeletonViewers()}},t.prototype._clearSkeletonViewers=function(){for(var e=0;e<this._skeletonViewers.length;e++)this._skeletonViewers[e].dispose();this._skeletonViewers=[]},t.prototype.show=function(e,t,i){if(void 0===e&&(e=!0),void 0===t&&(t=null),void 0===i&&(i=null),!this._enabled){this._enabled=!0,t?this._camera=t:this._camera=this._scene.activeCamera,this._showUI=e;var r=this._scene.getEngine();this._globalDiv=document.createElement("div"),this._rootElement=i||document.body,this._rootElement.appendChild(this._globalDiv),this._generateDOMelements(),r.getRenderingCanvas().addEventListener("click",this._onCanvasClick),this._syncPositions(),this._scene.registerBeforeRender(this._syncData),this._scene.registerAfterRender(this._syncUI)}},t.prototype._clearLabels=function(){this._drawingContext.clearRect(0,0,this._drawingCanvas.width,this._drawingCanvas.height);for(var e=0;e<this._scene.meshes.length;e++){var t=this._scene.meshes[e];t.renderOverlay=!1}},t.prototype._generateheader=function(e,t){var i=document.createElement("div");i.innerHTML=t+"&nbsp;",i.style.textAlign="right",i.style.width="100%",i.style.color="white",i.style.backgroundColor="Black",i.style.padding="5px 5px 4px 0px",i.style.marginLeft="-5px",i.style.fontWeight="bold",e.appendChild(i)},t.prototype._generateTexBox=function(e,t,i){var r=document.createElement("label");r.style.display="inline",r.innerHTML=t,r.style.color=i,e.appendChild(r),e.appendChild(document.createElement("br"))},t.prototype._generateAdvancedCheckBox=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=document.createElement("label");s.style.display="inline";var a=document.createElement("input");a.type="checkbox",a.checked=r,a.style.display="inline",a.style.margin="0px 5px 0px 0px",a.style.verticalAlign="sub",a.addEventListener("change",(function(e){n(e.target,o)})),s.appendChild(a);var h=document.createElement("span"),c=document.createElement("span"),l=document.createElement("span");l.style.cssFloat="right",c.innerHTML=t,l.innerHTML=i,l.style.fontSize="12px",l.style.maxWidth="200px",h.appendChild(c),h.appendChild(l),s.appendChild(h),e.appendChild(s),e.appendChild(document.createElement("br"))},t.prototype._generateCheckBox=function(e,t,i,r,n){void 0===n&&(n=null);var o=document.createElement("label");o.style.display="inline";var s=document.createElement("input");s.type="checkbox",s.checked=i,s.style.display="inline",s.style.margin="0px 5px 0px 0px",s.style.verticalAlign="sub",s.addEventListener("change",(function(e){r(e.target,n)})),o.appendChild(s),o.appendChild(document.createTextNode(t)),e.appendChild(o),e.appendChild(document.createElement("br"))},t.prototype._generateButton=function(e,t,i,r){void 0===r&&(r=null);var n=document.createElement("button");n.innerHTML=t,n.style.height="24px",n.style.width="150px",n.style.marginBottom="5px",n.style.color="#444444",n.style.border="1px solid white",n.className="debugLayerButton",n.addEventListener("click",(function(e){i(e.target,r)})),e.appendChild(n),e.appendChild(document.createElement("br"))},t.prototype._generateRadio=function(e,t,i,r,n,o){void 0===o&&(o=null);var s=document.createElement("label");s.style.display="inline";var a=document.createElement("input");a.type="radio",a.name=i,a.checked=r,a.style.display="inline",a.style.margin="0px 5px 0px 0px",a.style.verticalAlign="sub",a.addEventListener("change",(function(e){n(e.target,o)})),s.appendChild(a),s.appendChild(document.createTextNode(t)),e.appendChild(s),e.appendChild(document.createElement("br"))},t.prototype._generateDOMelements=function(){var t=this;if(this._globalDiv.id="DebugLayer",this._globalDiv.style.position="absolute",this._globalDiv.style.fontFamily="Segoe UI, Arial",this._globalDiv.style.fontSize="14px",this._globalDiv.style.color="white",this._drawingCanvas=document.createElement("canvas"),this._drawingCanvas.id="DebugLayerDrawingCanvas",this._drawingCanvas.style.position="absolute",this._drawingCanvas.style.pointerEvents="none",this._drawingCanvas.style.backgroundColor="transparent",this._drawingContext=this._drawingCanvas.getContext("2d"),this._globalDiv.appendChild(this._drawingCanvas),this._showUI){var i="rgba(128, 128, 128, 0.4)",r="rgb(180, 180, 180) solid 1px";this._statsDiv=document.createElement("div"),this._statsDiv.id="DebugLayerStats",this._statsDiv.style.border=r,this._statsDiv.style.position="absolute",this._statsDiv.style.background=i,this._statsDiv.style.padding="0px 0px 0px 5px",this._generateheader(this._statsDiv,"STATISTICS"),this._statsSubsetDiv=document.createElement("div"),this._statsSubsetDiv.style.paddingTop="5px",this._statsSubsetDiv.style.paddingBottom="5px",this._statsSubsetDiv.style.overflowY="auto",this._statsDiv.appendChild(this._statsSubsetDiv),this._treeDiv=document.createElement("div"),this._treeDiv.id="DebugLayerTree",this._treeDiv.style.border=r,this._treeDiv.style.position="absolute",this._treeDiv.style.background=i,this._treeDiv.style.padding="0px 0px 0px 5px",this._treeDiv.style.display="none",this._generateheader(this._treeDiv,"MESHES TREE"),this._treeSubsetDiv=document.createElement("div"),this._treeSubsetDiv.style.paddingTop="5px",this._treeSubsetDiv.style.paddingRight="5px",this._treeSubsetDiv.style.overflowY="auto",this._treeSubsetDiv.style.maxHeight="300px",this._treeDiv.appendChild(this._treeSubsetDiv),this._needToRefreshMeshesTree=!0,this._logDiv=document.createElement("div"),this._logDiv.style.border=r,this._logDiv.id="DebugLayerLogs",this._logDiv.style.position="absolute",this._logDiv.style.background=i,this._logDiv.style.padding="0px 0px 0px 5px",this._logDiv.style.display="none",this._generateheader(this._logDiv,"LOGS"),this._logSubsetDiv=document.createElement("div"),this._logSubsetDiv.style.height="127px",this._logSubsetDiv.style.paddingTop="5px",this._logSubsetDiv.style.overflowY="auto",this._logSubsetDiv.style.fontSize="12px",this._logSubsetDiv.style.fontFamily="consolas",this._logSubsetDiv.innerHTML=e.Tools.LogCache,this._logDiv.appendChild(this._logSubsetDiv),e.Tools.OnNewCacheEntry=function(e){t._logSubsetDiv.innerHTML=e+t._logSubsetDiv.innerHTML},this._optionsDiv=document.createElement("div"),this._optionsDiv.id="DebugLayerOptions",this._optionsDiv.style.border=r,this._optionsDiv.style.position="absolute",this._optionsDiv.style.background=i,this._optionsDiv.style.padding="0px 0px 0px 5px",this._optionsDiv.style.overflowY="auto",this._generateheader(this._optionsDiv,"OPTIONS"),this._optionsSubsetDiv=document.createElement("div"),this._optionsSubsetDiv.style.paddingTop="5px",this._optionsSubsetDiv.style.paddingBottom="5px",this._optionsSubsetDiv.style.overflowY="auto",this._optionsSubsetDiv.style.maxHeight="200px",this._optionsDiv.appendChild(this._optionsSubsetDiv),this._generateTexBox(this._optionsSubsetDiv,"<b>Windows:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Statistics",this._displayStatistics,(function(e){t._displayStatistics=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Logs",this._displayLogs,(function(e){t._displayLogs=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Meshes tree",this._displayTree,(function(e){t._displayTree=e.checked,t._needToRefreshMeshesTree=!0})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>General:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Bounding boxes",this._scene.forceShowBoundingBoxes,(function(e){t._scene.forceShowBoundingBoxes=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Clickable labels",this._labelsEnabled,(function(e){t._labelsEnabled=e.checked,t._labelsEnabled||t._clearLabels()})),
this._generateCheckBox(this._optionsSubsetDiv,"Generate user marks (F12)",e.Tools.PerformanceLogLevel===e.Tools.PerformanceUserMarkLogLevel,(function(t){t.checked?e.Tools.PerformanceLogLevel=e.Tools.PerformanceUserMarkLogLevel:e.Tools.PerformanceLogLevel=e.Tools.PerformanceNoneLogLevel})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Rendering mode:</b>",this.accentColor),this._generateRadio(this._optionsSubsetDiv,"Solid","renderMode",!this._scene.forceWireframe&&!this._scene.forcePointsCloud,(function(e){e.checked&&(t._scene.forceWireframe=!1,t._scene.forcePointsCloud=!1)})),this._generateRadio(this._optionsSubsetDiv,"Wireframe","renderMode",this._scene.forceWireframe,(function(e){e.checked&&(t._scene.forceWireframe=!0,t._scene.forcePointsCloud=!1)})),this._generateRadio(this._optionsSubsetDiv,"Point","renderMode",this._scene.forcePointsCloud,(function(e){e.checked&&(t._scene.forceWireframe=!1,t._scene.forcePointsCloud=!0)})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Texture channels:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Diffuse",e.StandardMaterial.DiffuseTextureEnabled,(function(t){e.StandardMaterial.DiffuseTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Ambient",e.StandardMaterial.AmbientTextureEnabled,(function(t){e.StandardMaterial.AmbientTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Specular",e.StandardMaterial.SpecularTextureEnabled,(function(t){e.StandardMaterial.SpecularTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Emissive",e.StandardMaterial.EmissiveTextureEnabled,(function(t){e.StandardMaterial.EmissiveTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Bump",e.StandardMaterial.BumpTextureEnabled,(function(t){e.StandardMaterial.BumpTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Opacity",e.StandardMaterial.OpacityTextureEnabled,(function(t){e.StandardMaterial.OpacityTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Reflection",e.StandardMaterial.ReflectionTextureEnabled,(function(t){e.StandardMaterial.ReflectionTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Refraction",e.StandardMaterial.RefractionTextureEnabled,(function(t){e.StandardMaterial.RefractionTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"ColorGrading",e.StandardMaterial.ColorGradingTextureEnabled,(function(t){e.StandardMaterial.ColorGradingTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Lightmap",e.StandardMaterial.LightmapTextureEnabled,(function(t){e.StandardMaterial.LightmapTextureEnabled=t.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Fresnel",e.StandardMaterial.FresnelEnabled,(function(t){e.StandardMaterial.FresnelEnabled=t.checked})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Options:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Animations",this._scene.animationsEnabled,(function(e){t._scene.animationsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Collisions",this._scene.collisionsEnabled,(function(e){t._scene.collisionsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Fog",this._scene.fogEnabled,(function(e){t._scene.fogEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Lens flares",this._scene.lensFlaresEnabled,(function(e){t._scene.lensFlaresEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Lights",this._scene.lightsEnabled,(function(e){t._scene.lightsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Particles",this._scene.particlesEnabled,(function(e){t._scene.particlesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Post-processes",this._scene.postProcessesEnabled,(function(e){t._scene.postProcessesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Probes",this._scene.probesEnabled,(function(e){t._scene.probesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Procedural textures",this._scene.proceduralTexturesEnabled,(function(e){t._scene.proceduralTexturesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Render targets",this._scene.renderTargetsEnabled,(function(e){t._scene.renderTargetsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Shadows",this._scene.shadowsEnabled,(function(e){t._scene.shadowsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Skeletons",this._scene.skeletonsEnabled,(function(e){t._scene.skeletonsEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Sprites",this._scene.spritesEnabled,(function(e){t._scene.spritesEnabled=e.checked})),this._generateCheckBox(this._optionsSubsetDiv,"Textures",this._scene.texturesEnabled,(function(e){t._scene.texturesEnabled=e.checked})),e.AudioEngine&&e.Engine.audioEngine.canUseWebAudio&&(this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Audio:</b>",this.accentColor),this._generateRadio(this._optionsSubsetDiv,"Headphones","panningModel",this._scene.headphone,(function(e){e.checked&&(t._scene.headphone=!0)})),this._generateRadio(this._optionsSubsetDiv,"Normal Speakers","panningModel",!this._scene.headphone,(function(e){e.checked&&(t._scene.headphone=!1)})),this._generateCheckBox(this._optionsSubsetDiv,"Disable audio",!this._scene.audioEnabled,(function(e){t._scene.audioEnabled=!e.checked}))),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Viewers:</b>",this.accentColor),this._generateCheckBox(this._optionsSubsetDiv,"Skeletons",!1,(function(i){if(!i.checked)return void t._clearSkeletonViewers();for(var r=0;r<t._scene.meshes.length;r++){var n=t._scene.meshes[r];if(n.skeleton){for(var o=!1,s=0;s<t._skeletonViewers.length;s++)if(t._skeletonViewers[s].skeleton===n.skeleton){o=!0;break}if(o)continue;var a=new e.Debug.SkeletonViewer(n.skeleton,n,t._scene);a.isEnabled=!0,t._skeletonViewers.push(a)}}})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._generateTexBox(this._optionsSubsetDiv,"<b>Tools:</b>",this.accentColor),this._generateButton(this._optionsSubsetDiv,"Dump rendertargets",(function(e){t._scene.dumpNextRenderTargets=!0})),this._generateButton(this._optionsSubsetDiv,"Run SceneOptimizer",(function(i){e.SceneOptimizer.OptimizeAsync(t._scene)})),this._generateButton(this._optionsSubsetDiv,"Log camera object",(function(e){t._camera?console.log(t._camera):console.warn("No camera defined, or debug layer created before camera creation!")})),this._optionsSubsetDiv.appendChild(document.createElement("br")),this._globalDiv.appendChild(this._statsDiv),this._globalDiv.appendChild(this._logDiv),this._globalDiv.appendChild(this._optionsDiv),this._globalDiv.appendChild(this._treeDiv)}},t.prototype._displayStats=function(){var t=this._scene,i=t.getEngine(),r=i.getGlInfo();this._statsSubsetDiv.innerHTML="Babylon.js v"+e.Engine.Version+" - <b>"+e.Tools.Format(i.getFps(),0)+" fps</b><br><br><div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'><b>Count</b><br>Total meshes: "+t.meshes.length+"<br>Total lights: "+t.lights.length+"<br>Total vertices: "+t.getTotalVertices()+"<br>Total materials: "+t.materials.length+"<br>Total textures: "+t.textures.length+"<br>Active meshes: "+t.getActiveMeshes().length+"<br>Active indices: "+t.getActiveIndices()+"<br>Active bones: "+t.getActiveBones()+"<br>Active particles: "+t.getActiveParticles()+"<br><b>Draw calls: "+i.drawCalls+"</b><br><br><b>Duration</b><br>Meshes selection:</i> "+e.Tools.Format(t.getEvaluateActiveMeshesDuration())+" ms<br>Render Targets: "+e.Tools.Format(t.getRenderTargetsDuration())+" ms<br>Particles: "+e.Tools.Format(t.getParticlesDuration())+" ms<br>Sprites: "+e.Tools.Format(t.getSpritesDuration())+" ms<br><br>Render: <b>"+e.Tools.Format(t.getRenderDuration())+" ms</b><br>Frame: "+e.Tools.Format(t.getLastFrameDuration())+" ms<br>Potential FPS: "+e.Tools.Format(1e3/t.getLastFrameDuration(),0)+"<br>Resolution: "+i.getRenderWidth()+"x"+i.getRenderHeight()+"<br><br></div><div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'><b>Extensions</b><br>Std derivatives: "+(i.getCaps().standardDerivatives?"Yes":"No")+"<br>Compressed textures: "+(i.getCaps().s3tc?"Yes":"No")+"<br>Hardware instances: "+(i.getCaps().instancedArrays?"Yes":"No")+"<br>Texture float: "+(i.getCaps().textureFloat?"Yes":"No")+"<br><br>32bits indices: "+(i.getCaps().uintIndices?"Yes":"No")+"<br>Fragment depth: "+(i.getCaps().fragmentDepthSupported?"Yes":"No")+"<br>High precision shaders: "+(i.getCaps().highPrecisionShaderSupported?"Yes":"No")+"<br>Draw buffers: "+(i.getCaps().drawBuffersExtension?"Yes":"No")+"<br></div><br><div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'><b>Caps.</b><br>Stencil: "+(i.isStencilEnable?"Enabled":"Disabled")+"<br>Max textures units: "+i.getCaps().maxTexturesImageUnits+"<br>Max textures size: "+i.getCaps().maxTextureSize+"<br>Max anisotropy: "+i.getCaps().maxAnisotropy+"<br><b>Info</b><br>WebGL feature level: "+i.webGLVersion+"<br>"+r.version+"<br></div><br>"+r.renderer+"<br>",this.customStatsFunction&&(this._statsSubsetDiv.innerHTML+=this.customStatsFunction())},t})();e.DebugLayer=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(t){function i(i,r,n,o,s){var a=this;void 0===o&&(o=null),t.call(this,r.getEngine(),i),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.gaussianBlurHPostProcesses=[],this.gaussianBlurVPostProcesses=[],this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.depthOfFieldPostProcess=null,this.brightThreshold=1,this.blurWidth=2,this.gaussianCoefficient=.25,this.gaussianMean=1,this.gaussianStandardDeviation=1,this.exposure=1,this.lensTexture=null,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.animations=[],this._depthRenderer=null,this._depthOfFieldEnabled=!0,this._lensFlareEnabled=!0,this._scene=r,o?this.originalPostProcess=o:this.originalPostProcess=new e.PostProcess("HDRPass","standard",[],[],n,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),(!0),"#define PASS_POST_PROCESS",e.Engine.TEXTURETYPE_FLOAT),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),"HDRPassPostProcess",function(){return a.originalPostProcess},(!0))),this._createDownSampleX4PostProcess(r,n/2),this._createBrightPassPostProcess(r,n/2),this._createGaussianBlurPostProcesses(r,n/2,0),this._createGaussianBlurPostProcesses(r,n/4,1),this._createGaussianBlurPostProcesses(r,n/8,2),this._createGaussianBlurPostProcesses(r,n/16,3),this._createTextureAdderPostProcess(r,n),this.textureAdderFinalPostProcess=new e.PostProcess("HDRDepthOfFieldSource","standard",[],[],n,null,e.Texture.BILINEAR_SAMPLINGMODE,r.getEngine(),(!0),"#define PASS_POST_PROCESS",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(r.getEngine(),"HDRDepthOfFieldSource",function(){return a.textureAdderFinalPostProcess},(!0))),this._createLensFlarePostProcess(r,n),this._createGaussianBlurPostProcesses(r,n/2,5),this._createDepthOfFieldPostProcess(r,n),r.postProcessRenderPipelineManager.addPipeline(this),null!==s&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(i,s),this.LensFlareEnabled=!1,this.DepthOfFieldEnabled=!1}return __extends(i,t),Object.defineProperty(i.prototype,"DepthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){var t=this.gaussianBlurHPostProcesses.length-1;e&&!this._depthOfFieldEnabled?(this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRDepthOfField",this._scene.cameras),this._depthRenderer=this._scene.enableDepthRenderer()):!e&&this._depthOfFieldEnabled&&(this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRDepthOfField",this._scene.cameras)),this._depthOfFieldEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"LensFlareEnabled",{get:function(){return this._lensFlareEnabled},set:function(e){var t=this.gaussianBlurHPostProcesses.length-2;e&&!this._lensFlareEnabled?(this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRLensFlare",this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRLensFlareShift",this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name,"HDRLensFlareCompose",this._scene.cameras)):!e&&this._lensFlareEnabled&&(this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRLensFlare",this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRLensFlareShift",this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurH"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRGaussianBlurV"+t,this._scene.cameras),this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name,"HDRLensFlareCompose",this._scene.cameras)),this._lensFlareEnabled=e},enumerable:!0,configurable:!0}),i.prototype._createDownSampleX4PostProcess=function(t,i){var r=this,n=new Array(32);this.downSampleX4PostProcess=new e.PostProcess("HDRDownSampleX4","standard",["dsOffsets"],[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define DOWN_SAMPLE_X4",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.downSampleX4PostProcess.onApply=function(e){for(var t=0,i=-2;i<2;i++)for(var o=-2;o<2;o++)n[t]=(i+.5)*(1/r.downSampleX4PostProcess.width),n[t+1]=(o+.5)*(1/r.downSampleX4PostProcess.height),t+=2;e.setArray2("dsOffsets",n)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDownSampleX4",function(){return r.downSampleX4PostProcess},(!0)))},i.prototype._createBrightPassPostProcess=function(t,i){var r=this,n=new Array(8);this.brightPassPostProcess=new e.PostProcess("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define BRIGHT_PASS",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.brightPassPostProcess.onApply=function(e){var t=1/r.brightPassPostProcess.width,i=1/r.brightPassPostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i,e.setArray2("dsOffsets",n),e.setFloat("brightThreshold",r.brightThreshold)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRBrightPass",function(){return r.brightPassPostProcess},(!0)))},i.prototype._createGaussianBlurPostProcesses=function(t,i,r){var n=this,o=new Array(9),s=new Array(9),a=["blurOffsets","blurWeights","blurWidth"],h=function(e){return function(i){for(var r=0,a=0;a<9;a++)r=(a-4)/4,s[a]=n.gaussianCoefficient*(1/Math.sqrt(2*Math.PI*n.gaussianStandardDeviation))*Math.exp(-((r-n.gaussianMean)*(r-n.gaussianMean))/(2*n.gaussianStandardDeviation*n.gaussianStandardDeviation));for(var h={width:t.getEngine().getRenderWidth(),height:t.getEngine().getRenderHeight()},a=0;a<9;a++){var c=(a-4)*(1/(e===!0?h.height:h.width));o[a]=c}i.setArray("blurOffsets",o),i.setArray("blurWeights",s),i.setFloat("blurWidth",n.blurWidth)}},c=new e.PostProcess("HDRGaussianBlurH"+i,"standard",a,[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_H",e.Engine.TEXTURETYPE_UNSIGNED_INT);c.onApply=h(!1);var l=new e.PostProcess("HDRGaussianBlurV"+i,"standard",a,[],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define GAUSSIAN_BLUR_V",e.Engine.TEXTURETYPE_UNSIGNED_INT);l.onApply=h(!0),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRGaussianBlurH"+r,function(){return c},(!0))),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRGaussianBlurV"+r,function(){return l},(!0))),this.gaussianBlurHPostProcesses.push(c),this.gaussianBlurVPostProcesses.push(l)},i.prototype._createTextureAdderPostProcess=function(t,i){var r=this;this.gaussianBlurVPostProcesses[3];this.textureAdderPostProcess=new e.PostProcess("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define TEXTURE_ADDER",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r.originalPostProcess),e.setTexture("lensSampler",r.lensTexture),e.setFloat("exposure",r.exposure)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRTextureAdder",function(){return r.textureAdderPostProcess},(!0)))},i.prototype._createLensFlarePostProcess=function(t,i){var r=this;this.lensFlarePostProcess=new e.PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],i/2,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!0),"#define LENS_FLARE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlare",function(){return r.lensFlarePostProcess},(!1))),this._createGaussianBlurPostProcesses(t,i/4,4),this.lensFlareComposePostProcess=new e.PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define LENS_FLARE_COMPOSE",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRLensFlareCompose",function(){return r.lensFlareComposePostProcess},(!1)));var n=new e.Vector2(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",r.gaussianBlurHPostProcesses[0]),e.setTexture("lensColorSampler",r.lensColorTexture),e.setFloat("strength",r.lensFlareStrength),e.setFloat("ghostDispersal",r.lensFlareGhostDispersal),e.setFloat("haloWidth",r.lensFlareHaloWidth),n.x=r.lensFlarePostProcess.width,n.y=r.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",r.lensFlareDistortionStrength)};var o=e.Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=e.Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(t){t.setTextureFromPostProcess("otherSampler",r.textureAdderFinalPostProcess),t.setTexture("lensDirtSampler",r.lensFlareDirtTexture),t.setTexture("lensStarSampler",r.lensStarTexture);var i=r._scene.activeCamera.getViewMatrix().getRow(0),n=r._scene.activeCamera.getViewMatrix().getRow(2),a=e.Vector3.Dot(i.toVector3(),new e.Vector3(1,0,0))+e.Vector3.Dot(n.toVector3(),new e.Vector3(0,0,1));a*=4;var h=e.Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),c=s.multiply(h).multiply(o);t.setMatrix("lensStarMatrix",c)}},i.prototype._createDepthOfFieldPostProcess=function(t,i){var r=this;this.depthOfFieldPostProcess=new e.PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],i,null,e.Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),(!1),"#define DEPTH_OF_FIELD",e.Engine.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",r.textureAdderFinalPostProcess),e.setTexture("depthSampler",r._depthRenderer.getDepthMap()),e.setFloat("distance",r.depthOfFieldDistance)},this.addEffect(new e.PostProcessRenderEffect(t.getEngine(),"HDRDepthOfField",function(){return r.depthOfFieldPostProcess},(!0)))},i.prototype.dispose=function(){for(var e=0;e<this._scene.cameras.length;e++){var i=this._scene.cameras[e];this.originalPostProcess.dispose(i),this.downSampleX4PostProcess.dispose(i),this.brightPassPostProcess.dispose(i),this.textureAdderPostProcess.dispose(i);for(var r=0;r<this.gaussianBlurHPostProcesses.length;r++)this.gaussianBlurHPostProcesses[r].dispose(i);for(var r=0;r<this.gaussianBlurVPostProcesses.length;r++)this.gaussianBlurVPostProcesses[r].dispose(i);this.textureAdderFinalPostProcess.dispose(i),this.lensFlarePostProcess.dispose(i),this.lensFlareComposePostProcess.dispose(i),this.depthOfFieldPostProcess.dispose(i)}this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),t.prototype.dispose.call(this)},i})(e.PostProcessRenderPipeline);e.StandardRenderingPipeline=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore={anaglyphPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}",blackAndWhitePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}",blurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",chromaticAberrationPixelShader:"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}",colorPixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",colorVertexShader:"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}",colorCorrectionPixelShader:"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}",convolutionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}",defaultPixelShader:"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}",
defaultVertexShader:"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}",depthPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}",depthVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",depthBoxBlurPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}",depthOfFieldPixelShader:"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n",displayPassPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}",filterPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}",fxaaPixelShader:"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}",glowBlurPostProcessPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}",glowMapGenerationPixelShader:"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}",glowMapGenerationVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",glowMapMergePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}",glowMapMergeVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",hdrPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n",layerPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}",layerVertexShader:"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}",lensFlarePixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}",lensFlareVertexShader:"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}",lensHighlightsPixelShader:"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}",linePixelShader:"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}",lineVertexShader:"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}",outlinePixelShader:"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}",outlineVertexShader:"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n",particlesPixelShader:"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}",particlesVertexShader:"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}",passPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}",pbrPixelShader:"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}",
pbrVertexShader:"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}",postprocessVertexShader:"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}",proceduralVertexShader:"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}",refractionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}",shadowMapPixelShader:"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}",shadowMapVertexShader:"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}",spritesPixelShader:"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}",spritesVertexShader:"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}",ssaoPixelShader:"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n",ssaoCombinePixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n",standardPixelShader:"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n",stereoscopicInterlacePixelShader:"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}",tonemapPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}",volumetricLightScatteringPixelShader:"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n",volumetricLightScatteringPassPixelShader:"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n",vrDistortionCorrectionPixelShader:"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"},BABYLON.Effect.IncludesShadersStore={bonesDeclaration:"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif",bonesVertex:"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif",bumpFragment:"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif",bumpFragmentFunctions:"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif",clipPlaneFragment:"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif",clipPlaneFragmentDeclaration:"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif",clipPlaneVertex:"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif",clipPlaneVertexDeclaration:"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif",colorCurves:"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}",colorCurvesDefinition:"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;",colorGrading:"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}",colorGradingDefinition:"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;",fogFragment:"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif",fogFragmentDeclaration:"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif",fogVertex:"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif",fogVertexDeclaration:"#ifdef FOG\nvarying float fFogDistance;\n#endif",fresnelFunction:"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif",harmonicsFunctions:"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif",helperFunctions:"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}",instancesDeclaration:"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif",instancesVertex:"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif",lightFragment:"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif",lightFragmentDeclaration:"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif",lightsFragmentFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n",
logDepthDeclaration:"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif",logDepthFragment:"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif",logDepthVertex:"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif",pbrFunctions:"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif",pbrLightFunctions:"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}",pbrLightFunctionsCall:"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif",pbrShadowFunctions:"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif",pointCloudVertex:"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif",pointCloudVertexDeclaration:"#ifdef POINTSIZE\nuniform float pointSize;\n#endif",reflectionFunction:"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}",shadowsFragmentFunctions:"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif",shadowsVertex:"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif",shadowsVertexDeclaration:"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"},("undefined"!=typeof window&&window.module||"undefined"!=typeof module)&&"undefined"!=typeof module.exports&&(module.exports=BABYLON);